blob: 74b2a1eb85e9cce0b4e2863a3f0bcc20dc54ee06 [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;
Fariborz Jahanian1c2cb6d2010-01-11 22:48:40 +0000790 typedefString += "// @class ";
791 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
792 I != E; ++I) {
793 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
794 typedefString += ForwardDecl->getNameAsString();
795 if (I+1 != E)
796 typedefString += ", ";
797 else
798 typedefString += ";\n";
799 }
800
Chris Lattner9ee23b72009-02-20 18:04:31 +0000801 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
802 I != E; ++I) {
Ted Kremenek9b124e12009-11-18 00:28:11 +0000803 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
Steve Naroff1b232132007-11-09 12:50:28 +0000804 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000805 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000806 typedefString += "\n";
807 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000808 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000809 typedefString += "\n";
Steve Naroff98eb8d12007-11-05 14:36:37 +0000810 typedefString += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000811 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000812 typedefString += ";\n#endif\n";
Steve Naroff574440f2007-10-24 22:48:43 +0000813 }
Mike Stump11289f42009-09-09 15:08:12 +0000814
Steve Naroff574440f2007-10-24 22:48:43 +0000815 // Replace the @class with typedefs corresponding to the classes.
Mike Stump11289f42009-09-09 15:08:12 +0000816 ReplaceText(startLoc, semiPtr-startBuf+1,
Chris Lattner9cc55f52008-01-31 19:51:04 +0000817 typedefString.c_str(), typedefString.size());
Chris Lattner3c799d72007-10-24 17:06:59 +0000818}
819
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000820void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff3ce37a62007-12-14 23:37:57 +0000821 SourceLocation LocStart = Method->getLocStart();
822 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000823
Chris Lattner88ea93e2009-02-04 01:06:56 +0000824 if (SM->getInstantiationLineNumber(LocEnd) >
825 SM->getInstantiationLineNumber(LocStart)) {
Steve Naroffe020fa12008-10-21 13:37:27 +0000826 InsertText(LocStart, "#if 0\n", 6);
827 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff3ce37a62007-12-14 23:37:57 +0000828 } else {
Chris Lattner1780a852008-01-31 19:42:41 +0000829 InsertText(LocStart, "// ", 3);
Steve Naroff5448cf62007-10-30 13:30:57 +0000830 }
831}
832
Mike Stump11289f42009-09-09 15:08:12 +0000833void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000834 SourceLocation Loc = prop->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000835
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000836 ReplaceText(Loc, 0, "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +0000837
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000838 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahaniane8a30162007-11-07 00:09:37 +0000839}
840
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000841void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000842 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000843
Steve Naroff5448cf62007-10-30 13:30:57 +0000844 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000845 ReplaceText(LocStart, 0, "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +0000846
847 for (ObjCCategoryDecl::instmeth_iterator
848 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000849 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000850 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +0000851 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000852 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000853 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000854 RewriteMethodDeclaration(*I);
855
Steve Naroff5448cf62007-10-30 13:30:57 +0000856 // Lastly, comment out the @end.
Ted Kremenekc7c64312010-01-07 01:20:12 +0000857 ReplaceText(CatDecl->getAtEndRange().getBegin(), 0, "// ", 3);
Steve Naroff5448cf62007-10-30 13:30:57 +0000858}
859
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000860void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000861 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Mike Stump11289f42009-09-09 15:08:12 +0000862
Steve Narofff921385f2007-10-30 16:42:30 +0000863 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000864
Steve Narofff921385f2007-10-30 16:42:30 +0000865 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000866 ReplaceText(LocStart, 0, "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +0000867
868 for (ObjCProtocolDecl::instmeth_iterator
869 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000870 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000871 RewriteMethodDeclaration(*I);
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000872 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000873 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000874 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000875 RewriteMethodDeclaration(*I);
876
Steve Narofff921385f2007-10-30 16:42:30 +0000877 // Lastly, comment out the @end.
Ted Kremenekc7c64312010-01-07 01:20:12 +0000878 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Chris Lattner9cc55f52008-01-31 19:51:04 +0000879 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroffa509f042007-11-14 15:03:57 +0000880
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000881 // Must comment out @optional/@required
882 const char *startBuf = SM->getCharacterData(LocStart);
883 const char *endBuf = SM->getCharacterData(LocEnd);
884 for (const char *p = startBuf; p < endBuf; p++) {
885 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
886 std::string CommentedOptional = "/* @optional */";
Steve Naroffa509f042007-11-14 15:03:57 +0000887 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattner9cc55f52008-01-31 19:51:04 +0000888 ReplaceText(OptionalLoc, strlen("@optional"),
889 CommentedOptional.c_str(), CommentedOptional.size());
Mike Stump11289f42009-09-09 15:08:12 +0000890
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000891 }
892 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
893 std::string CommentedRequired = "/* @required */";
Steve Naroffa509f042007-11-14 15:03:57 +0000894 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattner9cc55f52008-01-31 19:51:04 +0000895 ReplaceText(OptionalLoc, strlen("@required"),
896 CommentedRequired.c_str(), CommentedRequired.size());
Mike Stump11289f42009-09-09 15:08:12 +0000897
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000898 }
899 }
Steve Narofff921385f2007-10-30 16:42:30 +0000900}
901
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000902void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000903 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffc17b0562007-11-14 03:37:28 +0000904 if (LocStart.isInvalid())
905 assert(false && "Invalid SourceLocation");
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000906 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000907 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000908}
909
Mike Stump11289f42009-09-09 15:08:12 +0000910void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000911 std::string &ResultStr) {
Steve Naroff295570a2008-10-30 12:09:33 +0000912 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroffb067bbd2008-07-16 14:40:40 +0000913 const FunctionType *FPRetType = 0;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000914 ResultStr += "\nstatic ";
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000915 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanian24cb52c2007-12-17 21:03:50 +0000916 ResultStr += "id";
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000917 else if (OMD->getResultType()->isFunctionPointerType() ||
918 OMD->getResultType()->isBlockPointerType()) {
Steve Naroffb067bbd2008-07-16 14:40:40 +0000919 // needs special handling, since pointer-to-functions have special
920 // syntax (where a decaration models use).
921 QualType retType = OMD->getResultType();
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000922 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000923 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000924 PointeeTy = PT->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000925 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000926 PointeeTy = BPT->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +0000927 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000928 ResultStr += FPRetType->getResultType().getAsString();
929 ResultStr += "(*";
Steve Naroffb067bbd2008-07-16 14:40:40 +0000930 }
931 } else
Fariborz Jahanian24cb52c2007-12-17 21:03:50 +0000932 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian7262fca2008-01-10 01:39:52 +0000933 ResultStr += " ";
Mike Stump11289f42009-09-09 15:08:12 +0000934
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000935 // Unique method name
Fariborz Jahanian56338352007-11-13 21:02:00 +0000936 std::string NameStr;
Mike Stump11289f42009-09-09 15:08:12 +0000937
Douglas Gregorffca3a22009-01-09 17:18:27 +0000938 if (OMD->isInstanceMethod())
Fariborz Jahanian56338352007-11-13 21:02:00 +0000939 NameStr += "_I_";
940 else
941 NameStr += "_C_";
Mike Stump11289f42009-09-09 15:08:12 +0000942
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000943 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +0000944 NameStr += "_";
Mike Stump11289f42009-09-09 15:08:12 +0000945
946 if (ObjCCategoryImplDecl *CID =
Steve Naroff11b387f2009-01-08 19:41:02 +0000947 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000948 NameStr += CID->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +0000949 NameStr += "_";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000950 }
Mike Stump11289f42009-09-09 15:08:12 +0000951 // Append selector names, replacing ':' with '_'
Chris Lattnere4b95692008-11-24 03:33:13 +0000952 {
953 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000954 int len = selString.size();
955 for (int i = 0; i < len; i++)
956 if (selString[i] == ':')
957 selString[i] = '_';
Fariborz Jahanian56338352007-11-13 21:02:00 +0000958 NameStr += selString;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000959 }
Fariborz Jahanian56338352007-11-13 21:02:00 +0000960 // Remember this name for metadata emission
961 MethodInternalNames[OMD] = NameStr;
962 ResultStr += NameStr;
Mike Stump11289f42009-09-09 15:08:12 +0000963
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000964 // Rewrite arguments
965 ResultStr += "(";
Mike Stump11289f42009-09-09 15:08:12 +0000966
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000967 // invisible arguments
Douglas Gregorffca3a22009-01-09 17:18:27 +0000968 if (OMD->isInstanceMethod()) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000969 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000970 selfTy = Context->getPointerType(selfTy);
Steve Naroffdc5b6b22008-03-12 00:25:36 +0000971 if (!LangOpts.Microsoft) {
972 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
973 ResultStr += "struct ";
974 }
975 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000976 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +0000977 ResultStr += " *";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000978 }
979 else
Steve Naroffd9803712009-04-29 16:37:50 +0000980 ResultStr += Context->getObjCClassType().getAsString();
Mike Stump11289f42009-09-09 15:08:12 +0000981
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000982 ResultStr += " self, ";
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000983 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000984 ResultStr += " _cmd";
Mike Stump11289f42009-09-09 15:08:12 +0000985
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000986 // Method arguments.
Chris Lattnera4997152009-02-20 18:43:26 +0000987 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
988 E = OMD->param_end(); PI != E; ++PI) {
989 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000990 ResultStr += ", ";
Steve Naroffdcdcdcd2008-04-18 21:13:19 +0000991 if (PDecl->getType()->isObjCQualifiedIdType()) {
992 ResultStr += "id ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000993 ResultStr += PDecl->getNameAsString();
Steve Naroffdcdcdcd2008-04-18 21:13:19 +0000994 } else {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000995 std::string Name = PDecl->getNameAsString();
Steve Naroffa5c0db82008-12-11 21:05:33 +0000996 if (isTopLevelBlockPointerType(PDecl->getType())) {
Steve Naroff44df6a22008-10-30 14:45:29 +0000997 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000998 const BlockPointerType *BPT = PDecl->getType()->getAs<BlockPointerType>();
Douglas Gregor7de59662009-05-29 20:38:28 +0000999 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name,
1000 Context->PrintingPolicy);
Steve Naroff44df6a22008-10-30 14:45:29 +00001001 } else
Douglas Gregor7de59662009-05-29 20:38:28 +00001002 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001003 ResultStr += Name;
1004 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001005 }
Fariborz Jahanianeab81cd2008-01-21 20:14:23 +00001006 if (OMD->isVariadic())
1007 ResultStr += ", ...";
Fariborz Jahanian7262fca2008-01-10 01:39:52 +00001008 ResultStr += ") ";
Mike Stump11289f42009-09-09 15:08:12 +00001009
Steve Naroffb067bbd2008-07-16 14:40:40 +00001010 if (FPRetType) {
1011 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump11289f42009-09-09 15:08:12 +00001012
Steve Naroffb067bbd2008-07-16 14:40:40 +00001013 // Now, emit the argument types (if any).
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001014 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroffb067bbd2008-07-16 14:40:40 +00001015 ResultStr += "(";
1016 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1017 if (i) ResultStr += ", ";
1018 std::string ParamStr = FT->getArgType(i).getAsString();
1019 ResultStr += ParamStr;
1020 }
1021 if (FT->isVariadic()) {
1022 if (FT->getNumArgs()) ResultStr += ", ";
1023 ResultStr += "...";
1024 }
1025 ResultStr += ")";
1026 } else {
1027 ResultStr += "()";
1028 }
1029 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001030}
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001031void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001032 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1033 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump11289f42009-09-09 15:08:12 +00001034
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00001035 if (IMD)
Chris Lattner1780a852008-01-31 19:42:41 +00001036 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00001037 else
Chris Lattner1780a852008-01-31 19:42:41 +00001038 InsertText(CID->getLocStart(), "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +00001039
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001040 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001041 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1042 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001043 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001044 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001045 ObjCMethodDecl *OMD = *I;
1046 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001047 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001048 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redla7b98a72009-04-26 20:35:05 +00001049
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001050 const char *startBuf = SM->getCharacterData(LocStart);
1051 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattner9cc55f52008-01-31 19:51:04 +00001052 ReplaceText(LocStart, endBuf-startBuf,
1053 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001054 }
Mike Stump11289f42009-09-09 15:08:12 +00001055
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001056 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001057 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1058 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001059 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001060 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001061 ObjCMethodDecl *OMD = *I;
1062 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001063 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001064 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +00001065
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001066 const char *startBuf = SM->getCharacterData(LocStart);
1067 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattner9cc55f52008-01-31 19:51:04 +00001068 ReplaceText(LocStart, endBuf-startBuf,
Mike Stump11289f42009-09-09 15:08:12 +00001069 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001070 }
Steve Naroffe1908e32008-12-01 20:33:01 +00001071 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001072 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001073 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001074 I != E; ++I) {
Steve Naroffc038b3a2008-12-02 17:36:43 +00001075 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffe1908e32008-12-01 20:33:01 +00001076 }
1077
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00001078 if (IMD)
Chris Lattner1780a852008-01-31 19:42:41 +00001079 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00001080 else
Mike Stump11289f42009-09-09 15:08:12 +00001081 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001082}
1083
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001084void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffc5484042007-10-30 02:23:23 +00001085 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001086 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff2f55b982007-11-01 03:35:41 +00001087 // we haven't seen a forward decl - generate a typedef.
Steve Naroff03f27672007-11-14 23:02:56 +00001088 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001089 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001090 ResultStr += "\n";
1091 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001092 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001093 ResultStr += "\n";
Steve Naroffa1e115e2008-03-10 23:16:54 +00001094 ResultStr += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001095 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001096 ResultStr += ";\n#endif\n";
Steve Naroff2f55b982007-11-01 03:35:41 +00001097 // Mark this typedef as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001098 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff2f55b982007-11-01 03:35:41 +00001099 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001100 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump11289f42009-09-09 15:08:12 +00001101
1102 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001103 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff0c0f5ba2009-01-11 01:06:09 +00001104 RewriteProperty(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001105 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001106 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001107 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001108 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001109 for (ObjCInterfaceDecl::classmeth_iterator
1110 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001111 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001112 RewriteMethodDeclaration(*I);
1113
Steve Naroff4cd61ac2007-10-30 03:43:13 +00001114 // Lastly, comment out the @end.
Ted Kremenekc7c64312010-01-07 01:20:12 +00001115 ReplaceText(ClassDecl->getAtEndRange().getBegin(), 0, "// ", 3);
Steve Naroff161a92b2007-10-26 20:53:56 +00001116}
1117
Steve Naroff08628db2008-12-09 12:56:34 +00001118Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1119 SourceRange SrcRange) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00001120 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1121 // This allows us to reuse all the fun and games in SynthMessageExpr().
1122 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1123 ObjCMessageExpr *MsgExpr;
1124 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1125 llvm::SmallVector<Expr *, 1> ExprVec;
1126 ExprVec.push_back(newStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001127
Steve Naroff1042ff32008-12-08 16:43:47 +00001128 Stmt *Receiver = PropRefExpr->getBase();
1129 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1130 if (PRE && PropGetters[PRE]) {
1131 // This allows us to handle chain/nested property getters.
1132 Receiver = PropGetters[PRE];
1133 }
Mike Stump11289f42009-09-09 15:08:12 +00001134 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
1135 PDecl->getSetterName(), PDecl->getType(),
1136 PDecl->getSetterMethodDecl(),
1137 SourceLocation(), SourceLocation(),
Steve Naroff4588d0f2008-12-04 16:24:46 +00001138 &ExprVec[0], 1);
1139 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001140
Steve Naroff4588d0f2008-12-04 16:24:46 +00001141 // Now do the actual rewrite.
Steve Naroff08628db2008-12-09 12:56:34 +00001142 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffdf705772008-12-10 14:53:27 +00001143 //delete BinOp;
Ted Kremenek5a201952009-02-07 01:47:29 +00001144 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1145 // to things that stay around.
1146 Context->Deallocate(MsgExpr);
Steve Naroff4588d0f2008-12-04 16:24:46 +00001147 return ReplacingStmt;
Steve Narofff326f402008-12-03 00:56:33 +00001148}
1149
Steve Naroff4588d0f2008-12-04 16:24:46 +00001150Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Narofff326f402008-12-03 00:56:33 +00001151 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1152 // This allows us to reuse all the fun and games in SynthMessageExpr().
1153 ObjCMessageExpr *MsgExpr;
1154 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
Mike Stump11289f42009-09-09 15:08:12 +00001155
Steve Naroff1042ff32008-12-08 16:43:47 +00001156 Stmt *Receiver = PropRefExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00001157
Steve Naroff1042ff32008-12-08 16:43:47 +00001158 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1159 if (PRE && PropGetters[PRE]) {
1160 // This allows us to handle chain/nested property getters.
1161 Receiver = PropGetters[PRE];
1162 }
Mike Stump11289f42009-09-09 15:08:12 +00001163 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
1164 PDecl->getGetterName(), PDecl->getType(),
1165 PDecl->getGetterMethodDecl(),
1166 SourceLocation(), SourceLocation(),
Steve Narofff326f402008-12-03 00:56:33 +00001167 0, 0);
1168
Steve Naroff22216db2008-12-04 23:50:32 +00001169 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001170
1171 if (!PropParentMap)
1172 PropParentMap = new ParentMap(CurrentBody);
1173
1174 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1175 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1176 // We stash away the ReplacingStmt since actually doing the
1177 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1178 PropGetters[PropRefExpr] = ReplacingStmt;
Ted Kremenek5a201952009-02-07 01:47:29 +00001179 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1180 // to things that stay around.
1181 Context->Deallocate(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001182 return PropRefExpr; // return the original...
1183 } else {
1184 ReplaceStmt(PropRefExpr, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001185 // delete PropRefExpr; elsewhere...
Ted Kremenek5a201952009-02-07 01:47:29 +00001186 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1187 // to things that stay around.
1188 Context->Deallocate(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001189 return ReplacingStmt;
1190 }
Steve Narofff326f402008-12-03 00:56:33 +00001191}
1192
Mike Stump11289f42009-09-09 15:08:12 +00001193Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001194 SourceLocation OrigStart) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001195 ObjCIvarDecl *D = IV->getDecl();
Fariborz Jahanian0f3aecf2010-01-07 18:18:32 +00001196 const Expr *BaseExpr = IV->getBase();
Steve Naroff677ab3a2008-10-27 17:20:55 +00001197 if (CurMethodDef) {
Fariborz Jahanian14442302010-01-07 22:15:31 +00001198 if (IV->isArrow() && isa<DeclRefExpr>(BaseExpr)) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001199 ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian0f3aecf2010-01-07 18:18:32 +00001200 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroffb1c02372008-05-08 17:52:16 +00001201 // lookup which class implements the instance variable.
1202 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001203 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001204 clsDeclared);
Steve Naroffb1c02372008-05-08 17:52:16 +00001205 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001206
Steve Naroffb1c02372008-05-08 17:52:16 +00001207 // Synthesize an explicit cast to gain access to the ivar.
1208 std::string RecName = clsDeclared->getIdentifier()->getName();
1209 RecName += "_IMPL";
1210 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00001211 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001212 SourceLocation(), II);
Steve Naroffb1c02372008-05-08 17:52:16 +00001213 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1214 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Mike Stump11289f42009-09-09 15:08:12 +00001215 CastExpr *castExpr = new (Context) CStyleCastExpr(castT,
Anders Carlssona2615922009-07-31 00:48:10 +00001216 CastExpr::CK_Unknown,
1217 IV->getBase(),
1218 castT,SourceLocation(),
1219 SourceLocation());
Steve Naroffb1c02372008-05-08 17:52:16 +00001220 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001221 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1222 IV->getBase()->getLocEnd(),
1223 castExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001224 if (IV->isFreeIvar() &&
Steve Naroff677ab3a2008-10-27 17:20:55 +00001225 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001226 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1227 IV->getLocation(),
1228 D->getType());
Steve Naroffb1c02372008-05-08 17:52:16 +00001229 ReplaceStmt(IV, ME);
Steve Naroff22216db2008-12-04 23:50:32 +00001230 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffb1c02372008-05-08 17:52:16 +00001231 return ME;
Steve Naroff05caa482007-11-15 11:33:00 +00001232 }
Mike Stump11289f42009-09-09 15:08:12 +00001233
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001234 ReplaceStmt(IV->getBase(), PE);
1235 // Cannot delete IV->getBase(), since PE points to it.
1236 // Replace the old base with the cast. This is important when doing
1237 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001238 IV->setBase(PE);
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001239 return IV;
Steve Naroff05caa482007-11-15 11:33:00 +00001240 }
Steve Naroff24840f62008-04-18 21:55:08 +00001241 } else { // we are outside a method.
Steve Naroff29ce4e52008-05-06 23:20:07 +00001242 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump11289f42009-09-09 15:08:12 +00001243
Steve Naroff29ce4e52008-05-06 23:20:07 +00001244 // Explicit ivar refs need to have a cast inserted.
1245 // FIXME: consider sharing some of this code with the code above.
Fariborz Jahanian9146e442010-01-11 17:50:35 +00001246 if (IV->isArrow()) {
1247 ObjCInterfaceType *iFaceDecl =
1248 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001249 // lookup which class implements the instance variable.
1250 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001251 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001252 clsDeclared);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001253 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001254
Steve Naroff29ce4e52008-05-06 23:20:07 +00001255 // Synthesize an explicit cast to gain access to the ivar.
1256 std::string RecName = clsDeclared->getIdentifier()->getName();
1257 RecName += "_IMPL";
1258 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00001259 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001260 SourceLocation(), II);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001261 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1262 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Mike Stump11289f42009-09-09 15:08:12 +00001263 CastExpr *castExpr = new (Context) CStyleCastExpr(castT,
Anders Carlssona2615922009-07-31 00:48:10 +00001264 CastExpr::CK_Unknown,
1265 IV->getBase(),
Ted Kremenek5a201952009-02-07 01:47:29 +00001266 castT, SourceLocation(),
1267 SourceLocation());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001268 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001269 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner34873d22008-05-28 16:38:23 +00001270 IV->getBase()->getLocEnd(), castExpr);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001271 ReplaceStmt(IV->getBase(), PE);
1272 // Cannot delete IV->getBase(), since PE points to it.
1273 // Replace the old base with the cast. This is important when doing
1274 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001275 IV->setBase(PE);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001276 return IV;
1277 }
Steve Naroff05caa482007-11-15 11:33:00 +00001278 }
Steve Naroff24840f62008-04-18 21:55:08 +00001279 return IV;
Steve Narofff60782b2007-11-15 02:58:25 +00001280}
1281
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001282/// SynthCountByEnumWithState - To print:
1283/// ((unsigned int (*)
1284/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001285/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001286/// sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001287/// "countByEnumeratingWithState:objects:count:"),
1288/// &enumState,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001289/// (id *)items, (unsigned int)16)
1290///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001291void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001292 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1293 "id *, unsigned int))(void *)objc_msgSend)";
1294 buf += "\n\t\t";
1295 buf += "((id)l_collection,\n\t\t";
1296 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1297 buf += "\n\t\t";
1298 buf += "&enumState, "
1299 "(id *)items, (unsigned int)16)";
1300}
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001301
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001302/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1303/// statement to exit to its outer synthesized loop.
1304///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001305Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001306 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1307 return S;
1308 // replace break with goto __break_label
1309 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001310
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001311 SourceLocation startLoc = S->getLocStart();
1312 buf = "goto __break_label_";
1313 buf += utostr(ObjCBcLabelNo.back());
Chris Lattner9cc55f52008-01-31 19:51:04 +00001314 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001315
1316 return 0;
1317}
1318
1319/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1320/// statement to continue with its inner synthesized loop.
1321///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001322Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001323 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1324 return S;
1325 // replace continue with goto __continue_label
1326 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001327
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001328 SourceLocation startLoc = S->getLocStart();
1329 buf = "goto __continue_label_";
1330 buf += utostr(ObjCBcLabelNo.back());
Chris Lattner9cc55f52008-01-31 19:51:04 +00001331 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001332
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001333 return 0;
1334}
1335
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001336/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001337/// It rewrites:
1338/// for ( type elem in collection) { stmts; }
Mike Stump11289f42009-09-09 15:08:12 +00001339
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001340/// Into:
1341/// {
Mike Stump11289f42009-09-09 15:08:12 +00001342/// type elem;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001343/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001344/// id items[16];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001345/// id l_collection = (id)collection;
Mike Stump11289f42009-09-09 15:08:12 +00001346/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001347/// objects:items count:16];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001348/// if (limit) {
1349/// unsigned long startMutations = *enumState.mutationsPtr;
1350/// do {
1351/// unsigned long counter = 0;
1352/// do {
Mike Stump11289f42009-09-09 15:08:12 +00001353/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001354/// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001355/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001356/// stmts;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001357/// __continue_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001358/// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001359/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001360/// objects:items count:16]);
1361/// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001362/// __break_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001363/// }
1364/// else
1365/// elem = nil;
1366/// }
1367///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001368Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattnera779d692008-01-31 05:10:40 +00001369 SourceLocation OrigEnd) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001370 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001371 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001372 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump11289f42009-09-09 15:08:12 +00001373 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001374 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001375
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001376 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001377 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001378 const char *elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001379 std::string elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001380 std::string buf;
1381 buf = "\n{\n\t";
1382 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1383 // type elem;
Chris Lattner529efc72009-03-28 06:33:19 +00001384 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek292b3842008-10-06 22:16:13 +00001385 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001386 if (ElementType->isObjCQualifiedIdType() ||
1387 ElementType->isObjCQualifiedInterfaceType())
1388 // Simply use 'id' for all qualified types.
1389 elementTypeAsString = "id";
1390 else
1391 elementTypeAsString = ElementType.getAsString();
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001392 buf += elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001393 buf += " ";
Chris Lattner86d7d912008-11-24 03:54:41 +00001394 elementName = D->getNameAsCString();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001395 buf += elementName;
1396 buf += ";\n\t";
1397 }
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001398 else {
1399 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner86d7d912008-11-24 03:54:41 +00001400 elementName = DR->getDecl()->getNameAsCString();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001401 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1402 if (VD->getType()->isObjCQualifiedIdType() ||
1403 VD->getType()->isObjCQualifiedInterfaceType())
1404 // Simply use 'id' for all qualified types.
1405 elementTypeAsString = "id";
1406 else
1407 elementTypeAsString = VD->getType().getAsString();
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001408 }
Mike Stump11289f42009-09-09 15:08:12 +00001409
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001410 // struct __objcFastEnumerationState enumState = { 0 };
1411 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1412 // id items[16];
1413 buf += "id items[16];\n\t";
1414 // id l_collection = (id)
1415 buf += "id l_collection = (id)";
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001416 // Find start location of 'collection' the hard way!
1417 const char *startCollectionBuf = startBuf;
1418 startCollectionBuf += 3; // skip 'for'
1419 startCollectionBuf = strchr(startCollectionBuf, '(');
1420 startCollectionBuf++; // skip '('
1421 // find 'in' and skip it.
1422 while (*startCollectionBuf != ' ' ||
1423 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1424 (*(startCollectionBuf+3) != ' ' &&
1425 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1426 startCollectionBuf++;
1427 startCollectionBuf += 3;
Mike Stump11289f42009-09-09 15:08:12 +00001428
1429 // Replace: "for (type element in" with string constructed thus far.
Chris Lattner9cc55f52008-01-31 19:51:04 +00001430 ReplaceText(startLoc, startCollectionBuf - startBuf,
1431 buf.c_str(), buf.size());
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001432 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001433 SourceLocation rightParenLoc = S->getRParenLoc();
1434 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1435 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001436 buf = ";\n\t";
Mike Stump11289f42009-09-09 15:08:12 +00001437
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001438 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1439 // objects:items count:16];
1440 // which is synthesized into:
Mike Stump11289f42009-09-09 15:08:12 +00001441 // unsigned int limit =
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001442 // ((unsigned int (*)
1443 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001444 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001445 // sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001446 // "countByEnumeratingWithState:objects:count:"),
1447 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001448 // (id *)items, (unsigned int)16);
1449 buf += "unsigned long limit =\n\t\t";
1450 SynthCountByEnumWithState(buf);
1451 buf += ";\n\t";
1452 /// if (limit) {
1453 /// unsigned long startMutations = *enumState.mutationsPtr;
1454 /// do {
1455 /// unsigned long counter = 0;
1456 /// do {
Mike Stump11289f42009-09-09 15:08:12 +00001457 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001458 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001459 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001460 buf += "if (limit) {\n\t";
1461 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1462 buf += "do {\n\t\t";
1463 buf += "unsigned long counter = 0;\n\t\t";
1464 buf += "do {\n\t\t\t";
1465 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1466 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1467 buf += elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001468 buf += " = (";
1469 buf += elementTypeAsString;
1470 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001471 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattner9cc55f52008-01-31 19:51:04 +00001472 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001473
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001474 /// __continue_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001475 /// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001476 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001477 /// objects:items count:16]);
1478 /// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001479 /// __break_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001480 /// }
1481 /// else
1482 /// elem = nil;
1483 /// }
Mike Stump11289f42009-09-09 15:08:12 +00001484 ///
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001485 buf = ";\n\t";
1486 buf += "__continue_label_";
1487 buf += utostr(ObjCBcLabelNo.back());
1488 buf += ": ;";
1489 buf += "\n\t\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001490 buf += "} while (counter < limit);\n\t";
1491 buf += "} while (limit = ";
1492 SynthCountByEnumWithState(buf);
1493 buf += ");\n\t";
1494 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001495 buf += " = ((";
1496 buf += elementTypeAsString;
1497 buf += ")0);\n\t";
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001498 buf += "__break_label_";
1499 buf += utostr(ObjCBcLabelNo.back());
1500 buf += ": ;\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001501 buf += "}\n\t";
1502 buf += "else\n\t\t";
1503 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001504 buf += " = ((";
1505 buf += elementTypeAsString;
1506 buf += ")0);\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001507 buf += "}\n";
Mike Stump11289f42009-09-09 15:08:12 +00001508
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001509 // Insert all these *after* the statement body.
Sebastian Redla7b98a72009-04-26 20:35:05 +00001510 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Narofff0ff8792008-07-21 18:26:02 +00001511 if (isa<CompoundStmt>(S->getBody())) {
1512 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1513 InsertText(endBodyLoc, buf.c_str(), buf.size());
1514 } else {
1515 /* Need to treat single statements specially. For example:
1516 *
1517 * for (A *a in b) if (stuff()) break;
1518 * for (A *a in b) xxxyy;
1519 *
1520 * The following code simply scans ahead to the semi to find the actual end.
1521 */
1522 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1523 const char *semiBuf = strchr(stmtBuf, ';');
1524 assert(semiBuf && "Can't find ';'");
1525 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1526 InsertText(endBodyLoc, buf.c_str(), buf.size());
1527 }
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001528 Stmts.pop_back();
1529 ObjCBcLabelNo.pop_back();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001530 return 0;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001531}
1532
Mike Stump11289f42009-09-09 15:08:12 +00001533/// RewriteObjCSynchronizedStmt -
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001534/// This routine rewrites @synchronized(expr) stmt;
1535/// into:
1536/// objc_sync_enter(expr);
1537/// @try stmt @finally { objc_sync_exit(expr); }
1538///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001539Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001540 // Get the start location and compute the semi location.
1541 SourceLocation startLoc = S->getLocStart();
1542 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001543
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001544 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump11289f42009-09-09 15:08:12 +00001545
1546 std::string buf;
Steve Naroffb2fc0522008-08-21 13:03:03 +00001547 buf = "objc_sync_enter((id)";
1548 const char *lparenBuf = startBuf;
1549 while (*lparenBuf != '(') lparenBuf++;
1550 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001551 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1552 // the sync expression is typically a message expression that's already
Steve Naroffad7013b2008-08-19 13:04:19 +00001553 // been rewritten! (which implies the SourceLocation's are invalid).
1554 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001555 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffad7013b2008-08-19 13:04:19 +00001556 while (*endBuf != ')') endBuf--;
1557 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001558 buf = ");\n";
1559 // declare a new scope with two variables, _stack and _rethrow.
1560 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1561 buf += "int buf[18/*32-bit i386*/];\n";
1562 buf += "char *pointers[4];} _stack;\n";
1563 buf += "id volatile _rethrow = 0;\n";
1564 buf += "objc_exception_try_enter(&_stack);\n";
1565 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001566 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001567 startLoc = S->getSynchBody()->getLocEnd();
1568 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001569
Steve Naroffad7013b2008-08-19 13:04:19 +00001570 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001571 SourceLocation lastCurlyLoc = startLoc;
1572 buf = "}\nelse {\n";
1573 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroffd9803712009-04-29 16:37:50 +00001574 buf += "}\n";
1575 buf += "{ /* implicit finally clause */\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001576 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffec60b432009-12-05 21:43:12 +00001577
1578 std::string syncBuf;
1579 syncBuf += " objc_sync_exit(";
Mike Stump11289f42009-09-09 15:08:12 +00001580 Expr *syncExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00001581 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00001582 S->getSynchExpr(),
Ted Kremenek5a201952009-02-07 01:47:29 +00001583 Context->getObjCIdType(),
1584 SourceLocation(),
1585 SourceLocation());
Ted Kremenek2d470fc2008-09-13 05:16:45 +00001586 std::string syncExprBufS;
1587 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00001588 syncExpr->printPretty(syncExprBuf, *Context, 0,
1589 PrintingPolicy(LangOpts));
Steve Naroffec60b432009-12-05 21:43:12 +00001590 syncBuf += syncExprBuf.str();
1591 syncBuf += ");";
1592
1593 buf += syncBuf;
1594 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001595 buf += "}\n";
1596 buf += "}";
Mike Stump11289f42009-09-09 15:08:12 +00001597
Chris Lattner9cc55f52008-01-31 19:51:04 +00001598 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffec60b432009-12-05 21:43:12 +00001599
1600 bool hasReturns = false;
1601 HasReturnStmts(S->getSynchBody(), hasReturns);
1602 if (hasReturns)
1603 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1604
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001605 return 0;
1606}
1607
Steve Naroffec60b432009-12-05 21:43:12 +00001608void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1609{
Steve Naroff6d6da252008-12-05 17:03:39 +00001610 // Perform a bottom up traversal of all children.
1611 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1612 CI != E; ++CI)
1613 if (*CI)
Steve Naroffec60b432009-12-05 21:43:12 +00001614 WarnAboutReturnGotoStmts(*CI);
Steve Naroff6d6da252008-12-05 17:03:39 +00001615
Steve Naroffec60b432009-12-05 21:43:12 +00001616 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump11289f42009-09-09 15:08:12 +00001617 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff6d6da252008-12-05 17:03:39 +00001618 TryFinallyContainsReturnDiag);
1619 }
1620 return;
1621}
1622
Steve Naroffec60b432009-12-05 21:43:12 +00001623void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1624{
1625 // Perform a bottom up traversal of all children.
1626 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1627 CI != E; ++CI)
1628 if (*CI)
1629 HasReturnStmts(*CI, hasReturns);
1630
1631 if (isa<ReturnStmt>(S))
1632 hasReturns = true;
1633 return;
1634}
1635
1636void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1637 // Perform a bottom up traversal of all children.
1638 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1639 CI != E; ++CI)
1640 if (*CI) {
1641 RewriteTryReturnStmts(*CI);
1642 }
1643 if (isa<ReturnStmt>(S)) {
1644 SourceLocation startLoc = S->getLocStart();
1645 const char *startBuf = SM->getCharacterData(startLoc);
1646
1647 const char *semiBuf = strchr(startBuf, ';');
1648 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1649 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1650
1651 std::string buf;
1652 buf = "{ objc_exception_try_exit(&_stack); return";
1653
1654 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
1655 InsertText(onePastSemiLoc, "}", 1);
1656 }
1657 return;
1658}
1659
1660void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1661 // Perform a bottom up traversal of all children.
1662 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1663 CI != E; ++CI)
1664 if (*CI) {
1665 RewriteSyncReturnStmts(*CI, syncExitBuf);
1666 }
1667 if (isa<ReturnStmt>(S)) {
1668 SourceLocation startLoc = S->getLocStart();
1669 const char *startBuf = SM->getCharacterData(startLoc);
1670
1671 const char *semiBuf = strchr(startBuf, ';');
1672 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1673 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1674
1675 std::string buf;
1676 buf = "{ objc_exception_try_exit(&_stack);";
1677 buf += syncExitBuf;
1678 buf += " return";
1679
1680 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
1681 InsertText(onePastSemiLoc, "}", 1);
1682 }
1683 return;
1684}
1685
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001686Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001687 // Get the start location and compute the semi location.
1688 SourceLocation startLoc = S->getLocStart();
1689 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001690
Steve Naroffbf478ec2007-11-07 04:08:17 +00001691 assert((*startBuf == '@') && "bogus @try location");
1692
1693 std::string buf;
1694 // declare a new scope with two variables, _stack and _rethrow.
1695 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1696 buf += "int buf[18/*32-bit i386*/];\n";
1697 buf += "char *pointers[4];} _stack;\n";
1698 buf += "id volatile _rethrow = 0;\n";
1699 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff16018582007-11-07 18:43:40 +00001700 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffbf478ec2007-11-07 04:08:17 +00001701
Chris Lattner9cc55f52008-01-31 19:51:04 +00001702 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001703
Steve Naroffbf478ec2007-11-07 04:08:17 +00001704 startLoc = S->getTryBody()->getLocEnd();
1705 startBuf = SM->getCharacterData(startLoc);
1706
1707 assert((*startBuf == '}') && "bogus @try block");
Mike Stump11289f42009-09-09 15:08:12 +00001708
Steve Naroffbf478ec2007-11-07 04:08:17 +00001709 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffce2dca12008-07-16 15:31:30 +00001710 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1711 if (catchList) {
1712 startLoc = startLoc.getFileLocWithOffset(1);
1713 buf = " /* @catch begin */ else {\n";
1714 buf += " id _caught = objc_exception_extract(&_stack);\n";
1715 buf += " objc_exception_try_enter (&_stack);\n";
1716 buf += " if (_setjmp(_stack.buf))\n";
1717 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1718 buf += " else { /* @catch continue */";
Mike Stump11289f42009-09-09 15:08:12 +00001719
Steve Naroffce2dca12008-07-16 15:31:30 +00001720 InsertText(startLoc, buf.c_str(), buf.size());
Steve Narofffac18fe2008-09-09 19:59:12 +00001721 } else { /* no catch list */
1722 buf = "}\nelse {\n";
1723 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1724 buf += "}";
1725 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffce2dca12008-07-16 15:31:30 +00001726 }
Steve Naroffbf478ec2007-11-07 04:08:17 +00001727 bool sawIdTypedCatch = false;
1728 Stmt *lastCatchBody = 0;
Steve Naroffbf478ec2007-11-07 04:08:17 +00001729 while (catchList) {
Steve Naroff371b8fb2009-03-03 19:52:17 +00001730 ParmVarDecl *catchDecl = catchList->getCatchParamDecl();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001731
Mike Stump11289f42009-09-09 15:08:12 +00001732 if (catchList == S->getCatchStmts())
Steve Naroffbf478ec2007-11-07 04:08:17 +00001733 buf = "if ("; // we are generating code for the first catch clause
1734 else
1735 buf = "else if (";
1736 startLoc = catchList->getLocStart();
1737 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001738
Steve Naroffbf478ec2007-11-07 04:08:17 +00001739 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump11289f42009-09-09 15:08:12 +00001740
Steve Naroffbf478ec2007-11-07 04:08:17 +00001741 const char *lParenLoc = strchr(startBuf, '(');
1742
Steve Naroffe6b7ffd2008-02-01 22:08:12 +00001743 if (catchList->hasEllipsis()) {
Steve Naroffedb5bc62008-02-01 20:02:07 +00001744 // Now rewrite the body...
1745 lastCatchBody = catchList->getCatchBody();
Steve Naroffedb5bc62008-02-01 20:02:07 +00001746 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1747 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001748 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1749 "bogus @catch paren location");
Steve Naroffedb5bc62008-02-01 20:02:07 +00001750 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001751
Steve Naroffedb5bc62008-02-01 20:02:07 +00001752 buf += "1) { id _tmp = _caught;";
Daniel Dunbardec484a2009-08-19 19:10:30 +00001753 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff371b8fb2009-03-03 19:52:17 +00001754 } else if (catchDecl) {
1755 QualType t = catchDecl->getType();
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001756 if (t == Context->getObjCIdType()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001757 buf += "1) { ";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001758 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001759 sawIdTypedCatch = true;
Fariborz Jahanian59516092010-01-12 01:22:23 +00001760 } else if (t->isObjCObjectPointerType()) {
1761 QualType InterfaceTy = t->getPointeeType();
1762 const ObjCInterfaceType *cls = // Should be a pointer to a class.
1763 InterfaceTy->getAs<ObjCInterfaceType>();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001764 if (cls) {
Steve Naroff16018582007-11-07 18:43:40 +00001765 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001766 buf += cls->getDecl()->getNameAsString();
Steve Naroff16018582007-11-07 18:43:40 +00001767 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001768 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001769 }
1770 }
1771 // Now rewrite the body...
1772 lastCatchBody = catchList->getCatchBody();
1773 SourceLocation rParenLoc = catchList->getRParenLoc();
1774 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1775 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1776 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1777 assert((*rParenBuf == ')') && "bogus @catch paren location");
1778 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001779
Steve Naroffbf478ec2007-11-07 04:08:17 +00001780 buf = " = _caught;";
Mike Stump11289f42009-09-09 15:08:12 +00001781 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroffbf478ec2007-11-07 04:08:17 +00001782 // declares the @catch parameter).
Chris Lattner9cc55f52008-01-31 19:51:04 +00001783 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff371b8fb2009-03-03 19:52:17 +00001784 } else {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001785 assert(false && "@catch rewrite bug");
Steve Naroffa733c7f2007-11-07 15:32:26 +00001786 }
Steve Naroffedb5bc62008-02-01 20:02:07 +00001787 // make sure all the catch bodies get rewritten!
Steve Naroffbf478ec2007-11-07 04:08:17 +00001788 catchList = catchList->getNextCatchStmt();
1789 }
1790 // Complete the catch list...
1791 if (lastCatchBody) {
1792 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001793 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1794 "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001795
Steve Naroff4adbe312008-09-11 15:29:03 +00001796 // Insert the last (implicit) else clause *before* the right curly brace.
1797 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1798 buf = "} /* last catch end */\n";
1799 buf += "else {\n";
1800 buf += " _rethrow = _caught;\n";
1801 buf += " objc_exception_try_exit(&_stack);\n";
1802 buf += "} } /* @catch end */\n";
1803 if (!S->getFinallyStmt())
1804 buf += "}\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001805 InsertText(bodyLoc, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001806
Steve Naroffbf478ec2007-11-07 04:08:17 +00001807 // Set lastCurlyLoc
1808 lastCurlyLoc = lastCatchBody->getLocEnd();
1809 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001810 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001811 startLoc = finalStmt->getLocStart();
1812 startBuf = SM->getCharacterData(startLoc);
1813 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump11289f42009-09-09 15:08:12 +00001814
Steve Naroffbf478ec2007-11-07 04:08:17 +00001815 buf = "/* @finally */";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001816 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001817
Steve Naroffbf478ec2007-11-07 04:08:17 +00001818 Stmt *body = finalStmt->getFinallyBody();
1819 SourceLocation startLoc = body->getLocStart();
1820 SourceLocation endLoc = body->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001821 assert(*SM->getCharacterData(startLoc) == '{' &&
1822 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001823 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001824 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001825
Steve Naroffbf478ec2007-11-07 04:08:17 +00001826 startLoc = startLoc.getFileLocWithOffset(1);
1827 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001828 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001829 endLoc = endLoc.getFileLocWithOffset(-1);
1830 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001831 InsertText(endLoc, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001832
Steve Naroffbf478ec2007-11-07 04:08:17 +00001833 // Set lastCurlyLoc
1834 lastCurlyLoc = body->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00001835
Steve Naroff6d6da252008-12-05 17:03:39 +00001836 // Now check for any return/continue/go statements within the @try.
Steve Naroffec60b432009-12-05 21:43:12 +00001837 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff4adbe312008-09-11 15:29:03 +00001838 } else { /* no finally clause - make sure we synthesize an implicit one */
1839 buf = "{ /* implicit finally clause */\n";
1840 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1841 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1842 buf += "}";
1843 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffec60b432009-12-05 21:43:12 +00001844
1845 // Now check for any return/continue/go statements within the @try.
1846 // The implicit finally clause won't called if the @try contains any
1847 // jump statements.
1848 bool hasReturns = false;
1849 HasReturnStmts(S->getTryBody(), hasReturns);
1850 if (hasReturns)
1851 RewriteTryReturnStmts(S->getTryBody());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001852 }
1853 // Now emit the final closing curly brace...
1854 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1855 buf = " } /* @try scope end */\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001856 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001857 return 0;
1858}
1859
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001860Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001861 return 0;
1862}
1863
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001864Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001865 return 0;
1866}
1867
Mike Stump11289f42009-09-09 15:08:12 +00001868// This can't be done with ReplaceStmt(S, ThrowExpr), since
1869// the throw expression is typically a message expression that's already
Steve Naroffa733c7f2007-11-07 15:32:26 +00001870// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001871Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroffa733c7f2007-11-07 15:32:26 +00001872 // Get the start location and compute the semi location.
1873 SourceLocation startLoc = S->getLocStart();
1874 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001875
Steve Naroffa733c7f2007-11-07 15:32:26 +00001876 assert((*startBuf == '@') && "bogus @throw location");
1877
1878 std::string buf;
1879 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffc7d2df22008-01-19 00:42:38 +00001880 if (S->getThrowExpr())
1881 buf = "objc_exception_throw(";
1882 else // add an implicit argument
1883 buf = "objc_exception_throw(_caught";
Mike Stump11289f42009-09-09 15:08:12 +00001884
Steve Naroff29788342008-07-25 15:41:30 +00001885 // handle "@ throw" correctly.
1886 const char *wBuf = strchr(startBuf, 'w');
1887 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1888 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001889
Steve Naroffa733c7f2007-11-07 15:32:26 +00001890 const char *semiBuf = strchr(startBuf, ';');
1891 assert((*semiBuf == ';') && "@throw: can't find ';'");
1892 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1893 buf = ");";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001894 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroffa733c7f2007-11-07 15:32:26 +00001895 return 0;
1896}
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001897
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001898Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerc6d91c02007-10-17 22:35:30 +00001899 // Create a new string expression.
1900 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlssond8499822007-10-29 05:01:08 +00001901 std::string StrEncoding;
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00001902 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00001903 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
1904 StrEncoding.length(), false,StrType,
1905 SourceLocation());
Chris Lattner2e0d2602008-01-31 19:37:57 +00001906 ReplaceStmt(Exp, Replacement);
Mike Stump11289f42009-09-09 15:08:12 +00001907
Chris Lattner4431a1b2007-11-30 22:53:43 +00001908 // Replace this subexpr in the parent.
Steve Naroff22216db2008-12-04 23:50:32 +00001909 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattner69534692007-10-24 16:57:36 +00001910 return Replacement;
Chris Lattnera7c19fe2007-10-16 22:36:42 +00001911}
1912
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001913Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff2654e182008-12-22 22:16:07 +00001914 if (!SelGetUidFunctionDecl)
1915 SynthSelGetUidFunctionDecl();
Steve Naroffe4f9b232007-11-05 14:50:49 +00001916 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1917 // Create a call to sel_registerName("selName").
1918 llvm::SmallVector<Expr*, 8> SelExprs;
1919 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00001920 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00001921 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00001922 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00001923 false, argType, SourceLocation()));
Steve Naroffe4f9b232007-11-05 14:50:49 +00001924 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1925 &SelExprs[0], SelExprs.size());
Chris Lattner2e0d2602008-01-31 19:37:57 +00001926 ReplaceStmt(Exp, SelExp);
Steve Naroff22216db2008-12-04 23:50:32 +00001927 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffe4f9b232007-11-05 14:50:49 +00001928 return SelExp;
1929}
1930
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001931CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff574440f2007-10-24 22:48:43 +00001932 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001933 // Get the type, we will need to reference it in a couple spots.
Steve Naroff574440f2007-10-24 22:48:43 +00001934 QualType msgSendType = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001935
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001936 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek5a201952009-02-07 01:47:29 +00001937 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001938
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001939 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattner3c799d72007-10-24 17:06:59 +00001940 QualType pToFunc = Context->getPointerType(msgSendType);
Mike Stump11289f42009-09-09 15:08:12 +00001941 ImplicitCastExpr *ICE = new (Context) ImplicitCastExpr(pToFunc,
Anders Carlssona2615922009-07-31 00:48:10 +00001942 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00001943 DRE,
Douglas Gregora11693b2008-11-12 17:17:38 +00001944 /*isLvalue=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00001945
John McCall9dd450b2009-09-21 23:43:11 +00001946 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00001947
Ted Kremenekd7b4f402009-02-09 20:51:47 +00001948 return new (Context) CallExpr(*Context, ICE, args, nargs, FT->getResultType(),
1949 SourceLocation());
Steve Naroff574440f2007-10-24 22:48:43 +00001950}
1951
Steve Naroff50d42052007-11-01 13:24:47 +00001952static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1953 const char *&startRef, const char *&endRef) {
1954 while (startBuf < endBuf) {
1955 if (*startBuf == '<')
1956 startRef = startBuf; // mark the start.
1957 if (*startBuf == '>') {
Steve Naroff1b232132007-11-09 12:50:28 +00001958 if (startRef && *startRef == '<') {
1959 endRef = startBuf; // mark the end.
1960 return true;
1961 }
1962 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00001963 }
1964 startBuf++;
1965 }
1966 return false;
1967}
1968
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00001969static void scanToNextArgument(const char *&argRef) {
1970 int angle = 0;
1971 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1972 if (*argRef == '<')
1973 angle++;
1974 else if (*argRef == '>')
1975 angle--;
1976 argRef++;
1977 }
1978 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1979}
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00001980
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001981bool RewriteObjC::needToScanForQualifiers(QualType T) {
Steve Naroffc277ad12009-07-18 15:33:26 +00001982 return T->isObjCQualifiedIdType() || T->isObjCQualifiedInterfaceType();
Steve Naroff50d42052007-11-01 13:24:47 +00001983}
1984
Steve Naroff873bd842008-07-29 18:15:38 +00001985void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1986 QualType Type = E->getType();
1987 if (needToScanForQualifiers(Type)) {
Steve Naroffdbfc6932008-11-19 21:15:47 +00001988 SourceLocation Loc, EndLoc;
Mike Stump11289f42009-09-09 15:08:12 +00001989
Steve Naroffdbfc6932008-11-19 21:15:47 +00001990 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
1991 Loc = ECE->getLParenLoc();
1992 EndLoc = ECE->getRParenLoc();
1993 } else {
1994 Loc = E->getLocStart();
1995 EndLoc = E->getLocEnd();
1996 }
1997 // This will defend against trying to rewrite synthesized expressions.
1998 if (Loc.isInvalid() || EndLoc.isInvalid())
1999 return;
2000
Steve Naroff873bd842008-07-29 18:15:38 +00002001 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffdbfc6932008-11-19 21:15:47 +00002002 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff873bd842008-07-29 18:15:38 +00002003 const char *startRef = 0, *endRef = 0;
2004 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2005 // Get the locations of the startRef, endRef.
2006 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
2007 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
2008 // Comment out the protocol references.
2009 InsertText(LessLoc, "/*", 2);
2010 InsertText(GreaterLoc, "*/", 2);
2011 }
2012 }
2013}
2014
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002015void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002016 SourceLocation Loc;
2017 QualType Type;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002018 const FunctionProtoType *proto = 0;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002019 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2020 Loc = VD->getLocation();
2021 Type = VD->getType();
2022 }
2023 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2024 Loc = FD->getLocation();
2025 // Check for ObjC 'id' and class types that have been adorned with protocol
2026 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall9dd450b2009-09-21 23:43:11 +00002027 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002028 assert(funcType && "missing function type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002029 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002030 if (!proto)
2031 return;
2032 Type = proto->getResultType();
2033 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00002034 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2035 Loc = FD->getLocation();
2036 Type = FD->getType();
2037 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002038 else
2039 return;
Mike Stump11289f42009-09-09 15:08:12 +00002040
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002041 if (needToScanForQualifiers(Type)) {
Steve Naroff50d42052007-11-01 13:24:47 +00002042 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002043
Steve Naroff50d42052007-11-01 13:24:47 +00002044 const char *endBuf = SM->getCharacterData(Loc);
2045 const char *startBuf = endBuf;
Steve Naroff930e0992008-05-31 05:02:17 +00002046 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroff50d42052007-11-01 13:24:47 +00002047 startBuf--; // scan backward (from the decl location) for return type.
2048 const char *startRef = 0, *endRef = 0;
2049 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2050 // Get the locations of the startRef, endRef.
2051 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2052 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2053 // Comment out the protocol references.
Chris Lattner1780a852008-01-31 19:42:41 +00002054 InsertText(LessLoc, "/*", 2);
2055 InsertText(GreaterLoc, "*/", 2);
Steve Naroff37e011c2007-10-31 04:38:33 +00002056 }
2057 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002058 if (!proto)
2059 return; // most likely, was a variable
Steve Naroff50d42052007-11-01 13:24:47 +00002060 // Now check arguments.
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002061 const char *startBuf = SM->getCharacterData(Loc);
2062 const char *startFuncBuf = startBuf;
Steve Naroff50d42052007-11-01 13:24:47 +00002063 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2064 if (needToScanForQualifiers(proto->getArgType(i))) {
2065 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002066
Steve Naroff50d42052007-11-01 13:24:47 +00002067 const char *endBuf = startBuf;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002068 // scan forward (from the decl location) for argument types.
2069 scanToNextArgument(endBuf);
Steve Naroff50d42052007-11-01 13:24:47 +00002070 const char *startRef = 0, *endRef = 0;
2071 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2072 // Get the locations of the startRef, endRef.
Mike Stump11289f42009-09-09 15:08:12 +00002073 SourceLocation LessLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002074 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump11289f42009-09-09 15:08:12 +00002075 SourceLocation GreaterLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002076 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroff50d42052007-11-01 13:24:47 +00002077 // Comment out the protocol references.
Chris Lattner1780a852008-01-31 19:42:41 +00002078 InsertText(LessLoc, "/*", 2);
2079 InsertText(GreaterLoc, "*/", 2);
Steve Naroff50d42052007-11-01 13:24:47 +00002080 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002081 startBuf = ++endBuf;
2082 }
2083 else {
Steve Naroffc884aa82008-08-06 15:58:23 +00002084 // If the function name is derived from a macro expansion, then the
2085 // argument buffer will not follow the name. Need to speak with Chris.
2086 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002087 startBuf++; // scan forward (from the decl location) for argument types.
2088 startBuf++;
2089 }
Steve Naroff50d42052007-11-01 13:24:47 +00002090 }
Steve Naroff37e011c2007-10-31 04:38:33 +00002091}
2092
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002093// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002094void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002095 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2096 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002097 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002098 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002099 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002100 false /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002101 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002102 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002103 SelGetUidIdent, getFuncType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002104 FunctionDecl::Extern, false);
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002105}
2106
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002107void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002108 // declared in <objc/objc.h>
Douglas Gregor1e21c192009-01-09 01:47:02 +00002109 if (FD->getIdentifier() &&
2110 strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002111 SelGetUidFunctionDecl = FD;
Steve Naroff37e011c2007-10-31 04:38:33 +00002112 return;
2113 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002114 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002115}
2116
Steve Naroff17978c42008-03-11 17:37:02 +00002117// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002118void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroff17978c42008-03-11 17:37:02 +00002119 if (SuperContructorFunctionDecl)
2120 return;
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002121 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroff17978c42008-03-11 17:37:02 +00002122 llvm::SmallVector<QualType, 16> ArgTys;
2123 QualType argT = Context->getObjCIdType();
2124 assert(!argT.isNull() && "Can't find 'id' type");
2125 ArgTys.push_back(argT);
2126 ArgTys.push_back(argT);
2127 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2128 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002129 false, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002130 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002131 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002132 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002133 FunctionDecl::Extern, false);
Steve Naroff17978c42008-03-11 17:37:02 +00002134}
2135
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002136// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002137void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002138 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2139 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002140 QualType argT = Context->getObjCIdType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002141 assert(!argT.isNull() && "Can't find 'id' type");
2142 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002143 argT = Context->getObjCSelType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002144 assert(!argT.isNull() && "Can't find 'SEL' type");
2145 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002146 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002147 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002148 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002149 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002150 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002151 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002152 FunctionDecl::Extern, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002153}
2154
Steve Naroff7fa2f042007-11-15 10:28:18 +00002155// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002156void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002157 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2158 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002159 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002160 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002161 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002162 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2163 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2164 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002165 argT = Context->getObjCSelType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002166 assert(!argT.isNull() && "Can't find 'SEL' type");
2167 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002168 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff7fa2f042007-11-15 10:28:18 +00002169 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002170 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002171 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002172 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002173 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002174 FunctionDecl::Extern, false);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002175}
2176
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002177// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002178void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002179 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2180 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002181 QualType argT = Context->getObjCIdType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002182 assert(!argT.isNull() && "Can't find 'id' type");
2183 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002184 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002185 assert(!argT.isNull() && "Can't find 'SEL' type");
2186 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002187 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002188 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002189 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002190 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002191 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002192 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002193 FunctionDecl::Extern, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002194}
2195
Mike Stump11289f42009-09-09 15:08:12 +00002196// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002197// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002198void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump11289f42009-09-09 15:08:12 +00002199 IdentifierInfo *msgSendIdent =
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002200 &Context->Idents.get("objc_msgSendSuper_stret");
2201 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002202 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002203 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002204 &Context->Idents.get("objc_super"));
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002205 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2206 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2207 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002208 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002209 assert(!argT.isNull() && "Can't find 'SEL' type");
2210 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002211 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002212 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002213 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002214 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002215 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002216 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002217 FunctionDecl::Extern, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002218}
2219
Steve Naroff2e4e3852008-05-08 22:02:18 +00002220// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002221void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002222 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2223 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002224 QualType argT = Context->getObjCIdType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002225 assert(!argT.isNull() && "Can't find 'id' type");
2226 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002227 argT = Context->getObjCSelType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002228 assert(!argT.isNull() && "Can't find 'SEL' type");
2229 ArgTys.push_back(argT);
Steve Naroff2e4e3852008-05-08 22:02:18 +00002230 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002231 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002232 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002233 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002234 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002235 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002236 FunctionDecl::Extern, false);
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002237}
2238
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002239// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002240void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002241 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2242 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002243 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002244 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002245 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002246 false /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002247 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002248 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002249 getClassIdent, getClassType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002250 FunctionDecl::Extern, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002251}
2252
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002253// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002254void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002255 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2256 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002257 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002258 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002259 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002260 false /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002261 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002262 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002263 getClassIdent, getClassType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002264 FunctionDecl::Extern, false);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002265}
2266
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002267Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffce8e8862008-03-15 00:55:56 +00002268 QualType strType = getConstantStringStructType();
2269
2270 std::string S = "__NSConstantStringImpl_";
Steve Naroffa6141f02008-05-31 03:35:42 +00002271
2272 std::string tmpName = InFileName;
2273 unsigned i;
2274 for (i=0; i < tmpName.length(); i++) {
2275 char c = tmpName.at(i);
2276 // replace any non alphanumeric characters with '_'.
2277 if (!isalpha(c) && (c < '0' || c > '9'))
2278 tmpName[i] = '_';
2279 }
2280 S += tmpName;
2281 S += "_";
Steve Naroffce8e8862008-03-15 00:55:56 +00002282 S += utostr(NumObjCStringLiterals++);
2283
Steve Naroff00a31762008-03-27 22:29:16 +00002284 Preamble += "static __NSConstantStringImpl " + S;
2285 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2286 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffce8e8862008-03-15 00:55:56 +00002287 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremenek2d470fc2008-09-13 05:16:45 +00002288 std::string prettyBufS;
2289 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00002290 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2291 PrintingPolicy(LangOpts));
Steve Naroff00a31762008-03-27 22:29:16 +00002292 Preamble += prettyBuf.str();
2293 Preamble += ",";
Steve Naroff94ed6dc2009-12-06 01:48:44 +00002294 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00002295
2296 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2297 &Context->Idents.get(S.c_str()), strType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002298 VarDecl::Static);
Ted Kremenek5a201952009-02-07 01:47:29 +00002299 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
2300 Expr *Unop = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002301 Context->getPointerType(DRE->getType()),
Steve Naroffce8e8862008-03-15 00:55:56 +00002302 SourceLocation());
Steve Naroff265a6b92007-11-08 14:30:50 +00002303 // cast to NSConstantString *
Mike Stump11289f42009-09-09 15:08:12 +00002304 CastExpr *cast = new (Context) CStyleCastExpr(Exp->getType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002305 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002306 Unop, Exp->getType(),
2307 SourceLocation(),
Anders Carlssona2615922009-07-31 00:48:10 +00002308 SourceLocation());
Chris Lattner2e0d2602008-01-31 19:37:57 +00002309 ReplaceStmt(Exp, cast);
Steve Naroff22216db2008-12-04 23:50:32 +00002310 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff265a6b92007-11-08 14:30:50 +00002311 return cast;
Steve Naroffa397efd2007-11-03 11:27:19 +00002312}
2313
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002314ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002315 // check if we are sending a message to 'super'
Douglas Gregorffca3a22009-01-09 17:18:27 +00002316 if (!CurMethodDef || !CurMethodDef->isInstanceMethod()) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002317
Douglas Gregor8ea1f532008-11-04 14:56:14 +00002318 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
Mike Stump11289f42009-09-09 15:08:12 +00002319 const ObjCObjectPointerType *OPT =
John McCall9dd450b2009-09-21 23:43:11 +00002320 Super->getType()->getAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00002321 assert(OPT);
2322 const ObjCInterfaceType *IT = OPT->getInterfaceType();
Chris Lattnera9b3cae2008-06-21 18:04:54 +00002323 return IT->getDecl();
2324 }
2325 return 0;
Steve Naroff7fa2f042007-11-15 10:28:18 +00002326}
2327
2328// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002329QualType RewriteObjC::getSuperStructType() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002330 if (!SuperStructDecl) {
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002331 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002332 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002333 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002334 QualType FieldTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00002335
Steve Naroff7fa2f042007-11-15 10:28:18 +00002336 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002337 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002338 // struct objc_class *super;
Mike Stump11289f42009-09-09 15:08:12 +00002339 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor91f84212008-12-11 16:49:14 +00002340
Steve Naroff7fa2f042007-11-15 10:28:18 +00002341 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002342 for (unsigned i = 0; i < 2; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002343 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2344 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002345 FieldTypes[i], 0,
2346 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002347 /*Mutable=*/false));
Douglas Gregor91f84212008-12-11 16:49:14 +00002348 }
Mike Stump11289f42009-09-09 15:08:12 +00002349
Douglas Gregor91f84212008-12-11 16:49:14 +00002350 SuperStructDecl->completeDefinition(*Context);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002351 }
2352 return Context->getTagDeclType(SuperStructDecl);
2353}
2354
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002355QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffce8e8862008-03-15 00:55:56 +00002356 if (!ConstantStringDecl) {
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002357 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002358 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002359 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffce8e8862008-03-15 00:55:56 +00002360 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00002361
Steve Naroffce8e8862008-03-15 00:55:56 +00002362 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002363 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffce8e8862008-03-15 00:55:56 +00002364 // int flags;
Mike Stump11289f42009-09-09 15:08:12 +00002365 FieldTypes[1] = Context->IntTy;
Steve Naroffce8e8862008-03-15 00:55:56 +00002366 // char *str;
Mike Stump11289f42009-09-09 15:08:12 +00002367 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffce8e8862008-03-15 00:55:56 +00002368 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00002369 FieldTypes[3] = Context->LongTy;
Douglas Gregor91f84212008-12-11 16:49:14 +00002370
Steve Naroffce8e8862008-03-15 00:55:56 +00002371 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002372 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002373 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2374 ConstantStringDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00002375 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002376 FieldTypes[i], 0,
Douglas Gregor91f84212008-12-11 16:49:14 +00002377 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002378 /*Mutable=*/true));
Douglas Gregor91f84212008-12-11 16:49:14 +00002379 }
2380
2381 ConstantStringDecl->completeDefinition(*Context);
Steve Naroffce8e8862008-03-15 00:55:56 +00002382 }
2383 return Context->getTagDeclType(ConstantStringDecl);
2384}
2385
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002386Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002387 if (!SelGetUidFunctionDecl)
2388 SynthSelGetUidFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002389 if (!MsgSendFunctionDecl)
2390 SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002391 if (!MsgSendSuperFunctionDecl)
2392 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002393 if (!MsgSendStretFunctionDecl)
2394 SynthMsgSendStretFunctionDecl();
2395 if (!MsgSendSuperStretFunctionDecl)
2396 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002397 if (!MsgSendFpretFunctionDecl)
2398 SynthMsgSendFpretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002399 if (!GetClassFunctionDecl)
2400 SynthGetClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002401 if (!GetMetaClassFunctionDecl)
2402 SynthGetMetaClassFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002403
Steve Naroff7fa2f042007-11-15 10:28:18 +00002404 // default to objc_msgSend().
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002405 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2406 // May need to use objc_msgSend_stret() as well.
2407 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroffd9803712009-04-29 16:37:50 +00002408 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2409 QualType resultType = mDecl->getResultType();
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002410 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002411 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002412 else if (resultType->isRealFloatingType())
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002413 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002414 }
Mike Stump11289f42009-09-09 15:08:12 +00002415
Steve Naroff574440f2007-10-24 22:48:43 +00002416 // Synthesize a call to objc_msgSend().
2417 llvm::SmallVector<Expr*, 8> MsgExprs;
2418 IdentifierInfo *clsName = Exp->getClassName();
Mike Stump11289f42009-09-09 15:08:12 +00002419
Steve Naroff574440f2007-10-24 22:48:43 +00002420 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2421 if (clsName) { // class message.
Steve Naroff6c79f972008-07-24 19:44:33 +00002422 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2423 // the 'super' idiom within a class method.
Daniel Dunbar07d07852009-10-18 21:17:35 +00002424 if (clsName->getName() == "super") {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002425 MsgSendFlavor = MsgSendSuperFunctionDecl;
2426 if (MsgSendStretFlavor)
2427 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2428 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002429
2430 ObjCInterfaceDecl *SuperDecl =
Steve Naroff677ab3a2008-10-27 17:20:55 +00002431 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002432
2433 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00002434
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002435 // set the receiver to self, the first argument to all methods.
Steve Naroffd9803712009-04-29 16:37:50 +00002436 InitExprs.push_back(
Mike Stump11289f42009-09-09 15:08:12 +00002437 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002438 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002439 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroffd9803712009-04-29 16:37:50 +00002440 Context->getObjCIdType(),
2441 SourceLocation()),
2442 Context->getObjCIdType(),
2443 SourceLocation(), SourceLocation())); // set the 'receiver'.
2444
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002445 llvm::SmallVector<Expr*, 8> ClsExprs;
2446 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002447 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002448 SuperDecl->getIdentifier()->getNameStart(),
2449 SuperDecl->getIdentifier()->getLength(),
2450 false, argType, SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002451 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002452 &ClsExprs[0],
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002453 ClsExprs.size());
2454 // To turn off a warning, type-cast to 'id'
Douglas Gregore200adc2008-10-27 19:41:14 +00002455 InitExprs.push_back( // set 'super class', using objc_getClass().
Mike Stump11289f42009-09-09 15:08:12 +00002456 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002457 CastExpr::CK_Unknown,
Douglas Gregore200adc2008-10-27 19:41:14 +00002458 Cls, Context->getObjCIdType(),
Mike Stump11289f42009-09-09 15:08:12 +00002459 SourceLocation(), SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002460 // struct objc_super
2461 QualType superType = getSuperStructType();
Steve Naroff0b844f02008-03-11 18:14:26 +00002462 Expr *SuperRep;
Mike Stump11289f42009-09-09 15:08:12 +00002463
Steve Naroff0b844f02008-03-11 18:14:26 +00002464 if (LangOpts.Microsoft) {
2465 SynthSuperContructorFunctionDecl();
2466 // Simulate a contructor call...
Mike Stump11289f42009-09-09 15:08:12 +00002467 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff0b844f02008-03-11 18:14:26 +00002468 superType, SourceLocation());
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002469 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002470 InitExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002471 superType, SourceLocation());
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002472 // The code for super is a little tricky to prevent collision with
2473 // the structure definition in the header. The rewriter has it's own
2474 // internal definition (__rw_objc_super) that is uses. This is why
2475 // we need the cast below. For example:
2476 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2477 //
Ted Kremenek5a201952009-02-07 01:47:29 +00002478 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002479 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002480 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002481 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
2482 CastExpr::CK_Unknown, SuperRep,
Anders Carlssona2615922009-07-31 00:48:10 +00002483 Context->getPointerType(superType),
Mike Stump11289f42009-09-09 15:08:12 +00002484 SourceLocation(), SourceLocation());
2485 } else {
Steve Naroff0b844f02008-03-11 18:14:26 +00002486 // (struct objc_super) { <exprs from above> }
Mike Stump11289f42009-09-09 15:08:12 +00002487 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2488 &InitExprs[0], InitExprs.size(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002489 SourceLocation());
Ted Kremenek5a201952009-02-07 01:47:29 +00002490 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE,
Chris Lattner07d754a2008-10-26 23:43:26 +00002491 false);
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002492 // struct objc_super *
Ted Kremenek5a201952009-02-07 01:47:29 +00002493 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002494 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002495 SourceLocation());
Steve Naroff0b844f02008-03-11 18:14:26 +00002496 }
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002497 MsgExprs.push_back(SuperRep);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002498 } else {
2499 llvm::SmallVector<Expr*, 8> ClsExprs;
2500 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002501 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002502 clsName->getNameStart(),
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002503 clsName->getLength(),
2504 false, argType,
2505 SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002506 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002507 &ClsExprs[0],
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002508 ClsExprs.size());
2509 MsgExprs.push_back(Cls);
2510 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002511 } else { // instance message.
2512 Expr *recExpr = Exp->getReceiver();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002513
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002514 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002515 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002516 if (MsgSendStretFlavor)
2517 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff7fa2f042007-11-15 10:28:18 +00002518 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002519
Steve Naroff7fa2f042007-11-15 10:28:18 +00002520 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00002521
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002522 InitExprs.push_back(
Mike Stump11289f42009-09-09 15:08:12 +00002523 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002524 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002525 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroff97adf602008-07-16 22:35:27 +00002526 Context->getObjCIdType(),
Douglas Gregore200adc2008-10-27 19:41:14 +00002527 SourceLocation()),
2528 Context->getObjCIdType(),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002529 SourceLocation(), SourceLocation())); // set the 'receiver'.
Mike Stump11289f42009-09-09 15:08:12 +00002530
Steve Naroff7fa2f042007-11-15 10:28:18 +00002531 llvm::SmallVector<Expr*, 8> ClsExprs;
2532 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002533 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002534 SuperDecl->getIdentifier()->getNameStart(),
2535 SuperDecl->getIdentifier()->getLength(),
2536 false, argType, SourceLocation()));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002537 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002538 &ClsExprs[0],
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002539 ClsExprs.size());
Fariborz Jahaniand5db92b2007-12-05 17:29:46 +00002540 // To turn off a warning, type-cast to 'id'
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002541 InitExprs.push_back(
Douglas Gregore200adc2008-10-27 19:41:14 +00002542 // set 'super class', using objc_getClass().
Mike Stump11289f42009-09-09 15:08:12 +00002543 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002544 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002545 Cls, Context->getObjCIdType(), SourceLocation(), SourceLocation()));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002546 // struct objc_super
2547 QualType superType = getSuperStructType();
Steve Naroff17978c42008-03-11 17:37:02 +00002548 Expr *SuperRep;
Mike Stump11289f42009-09-09 15:08:12 +00002549
Steve Naroff17978c42008-03-11 17:37:02 +00002550 if (LangOpts.Microsoft) {
2551 SynthSuperContructorFunctionDecl();
2552 // Simulate a contructor call...
Mike Stump11289f42009-09-09 15:08:12 +00002553 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff17978c42008-03-11 17:37:02 +00002554 superType, SourceLocation());
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002555 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002556 InitExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002557 superType, SourceLocation());
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002558 // The code for super is a little tricky to prevent collision with
2559 // the structure definition in the header. The rewriter has it's own
2560 // internal definition (__rw_objc_super) that is uses. This is why
2561 // we need the cast below. For example:
2562 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2563 //
Ted Kremenek5a201952009-02-07 01:47:29 +00002564 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002565 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002566 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002567 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
Anders Carlssona2615922009-07-31 00:48:10 +00002568 CastExpr::CK_Unknown,
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002569 SuperRep, Context->getPointerType(superType),
Mike Stump11289f42009-09-09 15:08:12 +00002570 SourceLocation(), SourceLocation());
Steve Naroff17978c42008-03-11 17:37:02 +00002571 } else {
2572 // (struct objc_super) { <exprs from above> }
Mike Stump11289f42009-09-09 15:08:12 +00002573 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2574 &InitExprs[0], InitExprs.size(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002575 SourceLocation());
Ted Kremenek5a201952009-02-07 01:47:29 +00002576 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
Steve Naroff17978c42008-03-11 17:37:02 +00002577 }
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002578 MsgExprs.push_back(SuperRep);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002579 } else {
Fariborz Jahanianff6a4552007-12-07 21:21:21 +00002580 // Remove all type-casts because it may contain objc-style types; e.g.
2581 // Foo<Proto> *.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002582 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanianff6a4552007-12-07 21:21:21 +00002583 recExpr = CE->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002584 recExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002585 CastExpr::CK_Unknown, recExpr,
Mike Stump11289f42009-09-09 15:08:12 +00002586 Context->getObjCIdType(),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002587 SourceLocation(), SourceLocation());
Steve Naroff7fa2f042007-11-15 10:28:18 +00002588 MsgExprs.push_back(recExpr);
2589 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002590 }
Steve Naroffa397efd2007-11-03 11:27:19 +00002591 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff574440f2007-10-24 22:48:43 +00002592 llvm::SmallVector<Expr*, 8> SelExprs;
2593 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002594 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00002595 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00002596 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00002597 false, argType, SourceLocation()));
Steve Naroff574440f2007-10-24 22:48:43 +00002598 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2599 &SelExprs[0], SelExprs.size());
2600 MsgExprs.push_back(SelExp);
Mike Stump11289f42009-09-09 15:08:12 +00002601
Steve Naroff574440f2007-10-24 22:48:43 +00002602 // Now push any user supplied arguments.
2603 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroffe7f18192007-11-14 23:54:14 +00002604 Expr *userExpr = Exp->getArg(i);
Steve Narofff60782b2007-11-15 02:58:25 +00002605 // Make all implicit casts explicit...ICE comes in handy:-)
2606 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2607 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregore200adc2008-10-27 19:41:14 +00002608 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002609 ? Context->getObjCIdType()
Douglas Gregore200adc2008-10-27 19:41:14 +00002610 : ICE->getType();
Anders Carlssona2615922009-07-31 00:48:10 +00002611 userExpr = new (Context) CStyleCastExpr(type, CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002612 userExpr, type, SourceLocation(),
Anders Carlssona2615922009-07-31 00:48:10 +00002613 SourceLocation());
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002614 }
2615 // Make id<P...> cast into an 'id' cast.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002616 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002617 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregorf19b2312008-10-28 15:36:24 +00002618 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002619 userExpr = CE->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002620 userExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002621 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002622 userExpr, Context->getObjCIdType(),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002623 SourceLocation(), SourceLocation());
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002624 }
Mike Stump11289f42009-09-09 15:08:12 +00002625 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002626 MsgExprs.push_back(userExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00002627 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2628 // out the argument in the original expression (since we aren't deleting
2629 // the ObjCMessageExpr). See RewritePropertySetter() usage for more info.
2630 //Exp->setArg(i, 0);
Steve Naroff574440f2007-10-24 22:48:43 +00002631 }
Steve Narofff36987c2007-11-04 22:37:50 +00002632 // Generate the funky cast.
2633 CastExpr *cast;
2634 llvm::SmallVector<QualType, 8> ArgTypes;
2635 QualType returnType;
Mike Stump11289f42009-09-09 15:08:12 +00002636
Steve Narofff36987c2007-11-04 22:37:50 +00002637 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff44864e42007-11-15 10:43:57 +00002638 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2639 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2640 else
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002641 ArgTypes.push_back(Context->getObjCIdType());
2642 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattnera4997152009-02-20 18:43:26 +00002643 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Narofff36987c2007-11-04 22:37:50 +00002644 // Push any user argument types.
Chris Lattnera4997152009-02-20 18:43:26 +00002645 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2646 E = OMD->param_end(); PI != E; ++PI) {
2647 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump11289f42009-09-09 15:08:12 +00002648 ? Context->getObjCIdType()
Chris Lattnera4997152009-02-20 18:43:26 +00002649 : (*PI)->getType();
Steve Naroff52c65fa2008-10-29 14:49:46 +00002650 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffa5c0db82008-12-11 21:05:33 +00002651 if (isTopLevelBlockPointerType(t)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002652 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroff52c65fa2008-10-29 14:49:46 +00002653 t = Context->getPointerType(BPT->getPointeeType());
2654 }
Steve Naroff98eb8d12007-11-05 14:36:37 +00002655 ArgTypes.push_back(t);
2656 }
Chris Lattnera4997152009-02-20 18:43:26 +00002657 returnType = OMD->getResultType()->isObjCQualifiedIdType()
2658 ? Context->getObjCIdType() : OMD->getResultType();
Steve Narofff36987c2007-11-04 22:37:50 +00002659 } else {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002660 returnType = Context->getObjCIdType();
Steve Narofff36987c2007-11-04 22:37:50 +00002661 }
2662 // Get the type, we will need to reference it in a couple spots.
Steve Naroff7fa2f042007-11-15 10:28:18 +00002663 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002664
Steve Narofff36987c2007-11-04 22:37:50 +00002665 // Create a reference to the objc_msgSend() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00002666 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002667 SourceLocation());
Steve Narofff36987c2007-11-04 22:37:50 +00002668
Mike Stump11289f42009-09-09 15:08:12 +00002669 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Narofff36987c2007-11-04 22:37:50 +00002670 // If we don't do this cast, we get the following bizarre warning/note:
2671 // xx.m:13: warning: function called through a non-compatible type
2672 // xx.m:13: note: if this code is reached, the program will abort
Mike Stump11289f42009-09-09 15:08:12 +00002673 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy),
2674 CastExpr::CK_Unknown, DRE,
Douglas Gregore200adc2008-10-27 19:41:14 +00002675 Context->getPointerType(Context->VoidTy),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002676 SourceLocation(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002677
Steve Narofff36987c2007-11-04 22:37:50 +00002678 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00002679 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00002680 &ArgTypes[0], ArgTypes.size(),
Steve Naroff327f0f42008-03-18 02:02:04 +00002681 // If we don't have a method decl, force a variadic cast.
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002682 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Narofff36987c2007-11-04 22:37:50 +00002683 castType = Context->getPointerType(castType);
Mike Stump11289f42009-09-09 15:08:12 +00002684 cast = new (Context) CStyleCastExpr(castType, CastExpr::CK_Unknown, cast,
2685 castType, SourceLocation(),
Anders Carlssona2615922009-07-31 00:48:10 +00002686 SourceLocation());
Steve Narofff36987c2007-11-04 22:37:50 +00002687
2688 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00002689 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump11289f42009-09-09 15:08:12 +00002690
John McCall9dd450b2009-09-21 23:43:11 +00002691 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002692 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002693 MsgExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002694 FT->getResultType(), SourceLocation());
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002695 Stmt *ReplacingStmt = CE;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002696 if (MsgSendStretFlavor) {
2697 // We have the method which returns a struct/union. Must also generate
2698 // call to objc_msgSend_stret and hang both varieties on a conditional
2699 // expression which dictate which one to envoke depending on size of
2700 // method's return type.
Mike Stump11289f42009-09-09 15:08:12 +00002701
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002702 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00002703 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002704 SourceLocation());
2705 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Mike Stump11289f42009-09-09 15:08:12 +00002706 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy),
2707 CastExpr::CK_Unknown, STDRE,
Douglas Gregore200adc2008-10-27 19:41:14 +00002708 Context->getPointerType(Context->VoidTy),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002709 SourceLocation(), SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002710 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00002711 castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00002712 &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002713 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002714 castType = Context->getPointerType(castType);
Anders Carlssona2615922009-07-31 00:48:10 +00002715 cast = new (Context) CStyleCastExpr(castType, CastExpr::CK_Unknown,
2716 cast, castType, SourceLocation(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002717
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002718 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00002719 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump11289f42009-09-09 15:08:12 +00002720
John McCall9dd450b2009-09-21 23:43:11 +00002721 FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002722 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002723 MsgExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002724 FT->getResultType(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002725
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002726 // Build sizeof(returnType)
Mike Stump11289f42009-09-09 15:08:12 +00002727 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
John McCallbcd03502009-12-07 02:54:59 +00002728 Context->getTrivialTypeSourceInfo(returnType),
Sebastian Redl6f282892008-11-11 17:56:53 +00002729 Context->getSizeType(),
2730 SourceLocation(), SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002731 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2732 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2733 // For X86 it is more complicated and some kind of target specific routine
2734 // is needed to decide what to do.
Mike Stump11289f42009-09-09 15:08:12 +00002735 unsigned IntSize =
Chris Lattner37e05872008-03-05 18:54:05 +00002736 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Mike Stump11289f42009-09-09 15:08:12 +00002737 IntegerLiteral *limit = new (Context) IntegerLiteral(llvm::APInt(IntSize, 8),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002738 Context->IntTy,
2739 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002740 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
2741 BinaryOperator::LE,
2742 Context->IntTy,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002743 SourceLocation());
2744 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump11289f42009-09-09 15:08:12 +00002745 ConditionalOperator *CondExpr =
Douglas Gregor7e112b02009-08-26 14:37:04 +00002746 new (Context) ConditionalOperator(lessThanExpr,
2747 SourceLocation(), CE,
2748 SourceLocation(), STCE, returnType);
Ted Kremenek5a201952009-02-07 01:47:29 +00002749 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002750 }
Mike Stump11289f42009-09-09 15:08:12 +00002751 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002752 return ReplacingStmt;
2753}
2754
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002755Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002756 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Mike Stump11289f42009-09-09 15:08:12 +00002757
Steve Naroff574440f2007-10-24 22:48:43 +00002758 // Now do the actual rewrite.
Chris Lattner2e0d2602008-01-31 19:37:57 +00002759 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00002760
2761 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002762 return ReplacingStmt;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002763}
2764
Steve Naroffd9803712009-04-29 16:37:50 +00002765// typedef struct objc_object Protocol;
2766QualType RewriteObjC::getProtocolType() {
2767 if (!ProtocolTypeDecl) {
John McCallbcd03502009-12-07 02:54:59 +00002768 TypeSourceInfo *TInfo
2769 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroffd9803712009-04-29 16:37:50 +00002770 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002771 SourceLocation(),
Steve Naroffd9803712009-04-29 16:37:50 +00002772 &Context->Idents.get("Protocol"),
John McCallbcd03502009-12-07 02:54:59 +00002773 TInfo);
Steve Naroffd9803712009-04-29 16:37:50 +00002774 }
2775 return Context->getTypeDeclType(ProtocolTypeDecl);
2776}
2777
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00002778/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroffd9803712009-04-29 16:37:50 +00002779/// a synthesized/forward data reference (to the protocol's metadata).
2780/// The forward references (and metadata) are generated in
2781/// RewriteObjC::HandleTranslationUnit().
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002782Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroffd9803712009-04-29 16:37:50 +00002783 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
2784 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump11289f42009-09-09 15:08:12 +00002785 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Douglas Gregored6c7442009-11-23 11:41:28 +00002786 ID, getProtocolType(), 0, VarDecl::Extern);
Steve Naroffd9803712009-04-29 16:37:50 +00002787 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), SourceLocation());
2788 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
2789 Context->getPointerType(DRE->getType()),
2790 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002791 CastExpr *castExpr = new (Context) CStyleCastExpr(DerefExpr->getType(),
2792 CastExpr::CK_Unknown,
2793 DerefExpr, DerefExpr->getType(),
Steve Naroffd9803712009-04-29 16:37:50 +00002794 SourceLocation(), SourceLocation());
2795 ReplaceStmt(Exp, castExpr);
2796 ProtocolExprDecls.insert(Exp->getProtocol());
Mike Stump11289f42009-09-09 15:08:12 +00002797 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffd9803712009-04-29 16:37:50 +00002798 return castExpr;
Mike Stump11289f42009-09-09 15:08:12 +00002799
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00002800}
2801
Mike Stump11289f42009-09-09 15:08:12 +00002802bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002803 const char *endBuf) {
2804 while (startBuf < endBuf) {
2805 if (*startBuf == '#') {
2806 // Skip whitespace.
2807 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2808 ;
2809 if (!strncmp(startBuf, "if", strlen("if")) ||
2810 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2811 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2812 !strncmp(startBuf, "define", strlen("define")) ||
2813 !strncmp(startBuf, "undef", strlen("undef")) ||
2814 !strncmp(startBuf, "else", strlen("else")) ||
2815 !strncmp(startBuf, "elif", strlen("elif")) ||
2816 !strncmp(startBuf, "endif", strlen("endif")) ||
2817 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2818 !strncmp(startBuf, "include", strlen("include")) ||
2819 !strncmp(startBuf, "import", strlen("import")) ||
2820 !strncmp(startBuf, "include_next", strlen("include_next")))
2821 return true;
2822 }
2823 startBuf++;
2824 }
2825 return false;
2826}
2827
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002828/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002829/// an objective-c class with ivars.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002830void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002831 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002832 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Mike Stump11289f42009-09-09 15:08:12 +00002833 assert(CDecl->getNameAsCString() &&
Douglas Gregor77324f32008-11-17 14:58:09 +00002834 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00002835 // Do not synthesize more than once.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002836 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00002837 return;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002838 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattner8d1c04f2008-03-16 21:08:55 +00002839 int NumIvars = CDecl->ivar_size();
Steve Naroffdde78982007-11-14 19:25:57 +00002840 SourceLocation LocStart = CDecl->getLocStart();
2841 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00002842
Steve Naroffdde78982007-11-14 19:25:57 +00002843 const char *startBuf = SM->getCharacterData(LocStart);
2844 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump11289f42009-09-09 15:08:12 +00002845
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00002846 // If no ivars and no root or if its root, directly or indirectly,
2847 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattner8d1c04f2008-03-16 21:08:55 +00002848 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2849 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner184e65d2009-04-14 23:22:57 +00002850 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Chris Lattner9cc55f52008-01-31 19:51:04 +00002851 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00002852 return;
2853 }
Mike Stump11289f42009-09-09 15:08:12 +00002854
2855 // FIXME: This has potential of causing problem. If
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002856 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00002857 Result += "\nstruct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002858 Result += CDecl->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +00002859 if (LangOpts.Microsoft)
2860 Result += "_IMPL";
Steve Naroffdc5b6b22008-03-12 00:25:36 +00002861
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002862 if (NumIvars > 0) {
Steve Naroffdde78982007-11-14 19:25:57 +00002863 const char *cursor = strchr(startBuf, '{');
Mike Stump11289f42009-09-09 15:08:12 +00002864 assert((cursor && endBuf)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002865 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002866 // If the buffer contains preprocessor directives, we do more fine-grained
2867 // rewrites. This is intended to fix code that looks like (which occurs in
2868 // NSURL.h, for example):
2869 //
2870 // #ifdef XYZ
2871 // @interface Foo : NSObject
2872 // #else
2873 // @interface FooBar : NSObject
2874 // #endif
2875 // {
2876 // int i;
2877 // }
2878 // @end
2879 //
2880 // This clause is segregated to avoid breaking the common case.
2881 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump11289f42009-09-09 15:08:12 +00002882 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002883 CDecl->getClassLoc();
2884 const char *endHeader = SM->getCharacterData(L);
Chris Lattner184e65d2009-04-14 23:22:57 +00002885 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002886
Chris Lattnerf5b77512009-02-20 18:18:36 +00002887 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002888 // advance to the end of the referenced protocols.
2889 while (endHeader < cursor && *endHeader != '>') endHeader++;
2890 endHeader++;
2891 }
2892 // rewrite the original header
2893 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2894 } else {
2895 // rewrite the original header *without* disturbing the '{'
Steve Naroffb0e33902009-12-04 21:36:32 +00002896 ReplaceText(LocStart, cursor-startBuf, Result.c_str(), Result.size());
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002897 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002898 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroffdde78982007-11-14 19:25:57 +00002899 Result = "\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002900 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00002901 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002902 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00002903 Result += "_IVARS;\n";
Mike Stump11289f42009-09-09 15:08:12 +00002904
Steve Naroffdde78982007-11-14 19:25:57 +00002905 // insert the super class structure definition.
Chris Lattner1780a852008-01-31 19:42:41 +00002906 SourceLocation OnePastCurly =
2907 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2908 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Naroffdde78982007-11-14 19:25:57 +00002909 }
2910 cursor++; // past '{'
Mike Stump11289f42009-09-09 15:08:12 +00002911
Steve Naroffdde78982007-11-14 19:25:57 +00002912 // Now comment out any visibility specifiers.
2913 while (cursor < endBuf) {
2914 if (*cursor == '@') {
2915 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner174a8252007-11-14 22:57:51 +00002916 // Skip whitespace.
2917 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2918 /*scan*/;
2919
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002920 // FIXME: presence of @public, etc. inside comment results in
2921 // this transformation as well, which is still correct c-code.
Steve Naroffdde78982007-11-14 19:25:57 +00002922 if (!strncmp(cursor, "public", strlen("public")) ||
2923 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffaf91b9a2008-04-04 22:34:24 +00002924 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002925 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattner1780a852008-01-31 19:42:41 +00002926 InsertText(atLoc, "// ", 3);
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002927 }
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002928 // FIXME: If there are cases where '<' is used in ivar declaration part
2929 // of user code, then scan the ivar list and use needToScanForQualifiers
2930 // for type checking.
2931 else if (*cursor == '<') {
2932 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner1780a852008-01-31 19:42:41 +00002933 InsertText(atLoc, "/* ", 3);
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002934 cursor = strchr(cursor, '>');
2935 cursor++;
2936 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner1780a852008-01-31 19:42:41 +00002937 InsertText(atLoc, " */", 3);
Steve Naroff295570a2008-10-30 12:09:33 +00002938 } else if (*cursor == '^') { // rewrite block specifier.
2939 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2940 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002941 }
Steve Naroffdde78982007-11-14 19:25:57 +00002942 cursor++;
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002943 }
Steve Naroffdde78982007-11-14 19:25:57 +00002944 // Don't forget to add a ';'!!
Chris Lattner1780a852008-01-31 19:42:41 +00002945 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Naroffdde78982007-11-14 19:25:57 +00002946 } else { // we don't have any instance variables - insert super struct.
Chris Lattner184e65d2009-04-14 23:22:57 +00002947 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Naroffdde78982007-11-14 19:25:57 +00002948 Result += " {\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002949 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00002950 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002951 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00002952 Result += "_IVARS;\n};\n";
Chris Lattner9cc55f52008-01-31 19:51:04 +00002953 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002954 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002955 // Mark this struct as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002956 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Naroff13e74872008-05-06 18:26:51 +00002957 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002958}
2959
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002960// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002961/// class methods.
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002962template<typename MethodIterator>
2963void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
2964 MethodIterator MethodEnd,
Fariborz Jahanian3df412a2007-10-25 00:14:44 +00002965 bool IsInstanceMethod,
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002966 const char *prefix,
Chris Lattner211f8b82007-10-25 17:07:24 +00002967 const char *ClassName,
2968 std::string &Result) {
Chris Lattner31bc07e2007-12-12 07:46:12 +00002969 if (MethodBegin == MethodEnd) return;
Mike Stump11289f42009-09-09 15:08:12 +00002970
Chris Lattner31bc07e2007-12-12 07:46:12 +00002971 if (!objc_impl_method) {
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002972 /* struct _objc_method {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00002973 SEL _cmd;
2974 char *method_types;
2975 void *_imp;
2976 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002977 */
Chris Lattner211f8b82007-10-25 17:07:24 +00002978 Result += "\nstruct _objc_method {\n";
2979 Result += "\tSEL _cmd;\n";
2980 Result += "\tchar *method_types;\n";
2981 Result += "\tvoid *_imp;\n";
2982 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00002983
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002984 objc_impl_method = true;
Fariborz Jahanian74a1cfa2007-10-19 00:36:46 +00002985 }
Mike Stump11289f42009-09-09 15:08:12 +00002986
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002987 // Build _objc_method_list for class's methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00002988
Steve Naroffc5b9cc72008-03-11 00:12:29 +00002989 /* struct {
2990 struct _objc_method_list *next_method;
2991 int method_count;
2992 struct _objc_method method_list[];
2993 }
2994 */
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002995 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00002996 Result += "\nstatic struct {\n";
2997 Result += "\tstruct _objc_method_list *next_method;\n";
2998 Result += "\tint method_count;\n";
2999 Result += "\tstruct _objc_method method_list[";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003000 Result += utostr(NumMethods);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003001 Result += "];\n} _OBJC_";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003002 Result += prefix;
3003 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
3004 Result += "_METHODS_";
3005 Result += ClassName;
Steve Naroffb327e492008-03-12 17:18:30 +00003006 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003007 Result += IsInstanceMethod ? "inst" : "cls";
3008 Result += "_meth\")))= ";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003009 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003010
Chris Lattner31bc07e2007-12-12 07:46:12 +00003011 Result += "\t,{{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00003012 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattner31bc07e2007-12-12 07:46:12 +00003013 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003014 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattner31bc07e2007-12-12 07:46:12 +00003015 Result += "\", \"";
3016 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003017 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003018 Result += MethodInternalNames[*MethodBegin];
3019 Result += "}\n";
3020 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3021 Result += "\t ,{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00003022 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003023 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003024 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003025 Result += "\", \"";
3026 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003027 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003028 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanian56338352007-11-13 21:02:00 +00003029 Result += "}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003030 }
Chris Lattner31bc07e2007-12-12 07:46:12 +00003031 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003032}
3033
Steve Naroffd9803712009-04-29 16:37:50 +00003034/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner390d39a2008-07-21 21:32:27 +00003035void RewriteObjC::
Steve Naroffd9803712009-04-29 16:37:50 +00003036RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, const char *prefix,
3037 const char *ClassName, std::string &Result) {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003038 static bool objc_protocol_methods = false;
Steve Naroffd9803712009-04-29 16:37:50 +00003039
3040 // Output struct protocol_methods holder of method selector and type.
3041 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3042 /* struct protocol_methods {
3043 SEL _cmd;
3044 char *method_types;
3045 }
3046 */
3047 Result += "\nstruct _protocol_methods {\n";
3048 Result += "\tstruct objc_selector *_cmd;\n";
3049 Result += "\tchar *method_types;\n";
3050 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003051
Steve Naroffd9803712009-04-29 16:37:50 +00003052 objc_protocol_methods = true;
3053 }
3054 // Do not synthesize the protocol more than once.
3055 if (ObjCSynthesizedProtocols.count(PDecl))
3056 return;
Mike Stump11289f42009-09-09 15:08:12 +00003057
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003058 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3059 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3060 PDecl->instmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003061 /* struct _objc_protocol_method_list {
3062 int protocol_method_count;
3063 struct protocol_methods protocols[];
3064 }
Steve Naroff251084d2008-03-12 01:06:30 +00003065 */
Steve Naroffd9803712009-04-29 16:37:50 +00003066 Result += "\nstatic struct {\n";
3067 Result += "\tint protocol_method_count;\n";
3068 Result += "\tstruct _protocol_methods protocol_methods[";
3069 Result += utostr(NumMethods);
3070 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3071 Result += PDecl->getNameAsString();
3072 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3073 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003074
Steve Naroffd9803712009-04-29 16:37:50 +00003075 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003076 for (ObjCProtocolDecl::instmeth_iterator
3077 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003078 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003079 if (I == PDecl->instmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003080 Result += "\t ,{{(struct objc_selector *)\"";
3081 else
3082 Result += "\t ,{(struct objc_selector *)\"";
3083 Result += (*I)->getSelector().getAsString().c_str();
3084 std::string MethodTypeString;
3085 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3086 Result += "\", \"";
3087 Result += MethodTypeString;
3088 Result += "\"}\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003089 }
Steve Naroffd9803712009-04-29 16:37:50 +00003090 Result += "\t }\n};\n";
3091 }
Mike Stump11289f42009-09-09 15:08:12 +00003092
Steve Naroffd9803712009-04-29 16:37:50 +00003093 // Output class methods declared in this protocol.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003094 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3095 PDecl->classmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003096 if (NumMethods > 0) {
3097 /* struct _objc_protocol_method_list {
3098 int protocol_method_count;
3099 struct protocol_methods protocols[];
3100 }
3101 */
3102 Result += "\nstatic struct {\n";
3103 Result += "\tint protocol_method_count;\n";
3104 Result += "\tstruct _protocol_methods protocol_methods[";
3105 Result += utostr(NumMethods);
3106 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3107 Result += PDecl->getNameAsString();
3108 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3109 "{\n\t";
3110 Result += utostr(NumMethods);
3111 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003112
Steve Naroffd9803712009-04-29 16:37:50 +00003113 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003114 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003115 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003116 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003117 if (I == PDecl->classmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003118 Result += "\t ,{{(struct objc_selector *)\"";
3119 else
3120 Result += "\t ,{(struct objc_selector *)\"";
3121 Result += (*I)->getSelector().getAsString().c_str();
3122 std::string MethodTypeString;
3123 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3124 Result += "\", \"";
3125 Result += MethodTypeString;
3126 Result += "\"}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003127 }
Steve Naroffd9803712009-04-29 16:37:50 +00003128 Result += "\t }\n};\n";
3129 }
3130
3131 // Output:
3132 /* struct _objc_protocol {
3133 // Objective-C 1.0 extensions
3134 struct _objc_protocol_extension *isa;
3135 char *protocol_name;
3136 struct _objc_protocol **protocol_list;
3137 struct _objc_protocol_method_list *instance_methods;
3138 struct _objc_protocol_method_list *class_methods;
Mike Stump11289f42009-09-09 15:08:12 +00003139 };
Steve Naroffd9803712009-04-29 16:37:50 +00003140 */
3141 static bool objc_protocol = false;
3142 if (!objc_protocol) {
3143 Result += "\nstruct _objc_protocol {\n";
3144 Result += "\tstruct _objc_protocol_extension *isa;\n";
3145 Result += "\tchar *protocol_name;\n";
3146 Result += "\tstruct _objc_protocol **protocol_list;\n";
3147 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3148 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003149 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003150
Steve Naroffd9803712009-04-29 16:37:50 +00003151 objc_protocol = true;
Chris Lattner388f6e92008-07-21 21:33:21 +00003152 }
Mike Stump11289f42009-09-09 15:08:12 +00003153
Steve Naroffd9803712009-04-29 16:37:50 +00003154 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3155 Result += PDecl->getNameAsString();
3156 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3157 "{\n\t0, \"";
3158 Result += PDecl->getNameAsString();
3159 Result += "\", 0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003160 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003161 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3162 Result += PDecl->getNameAsString();
3163 Result += ", ";
3164 }
3165 else
3166 Result += "0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003167 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003168 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3169 Result += PDecl->getNameAsString();
3170 Result += "\n";
3171 }
3172 else
3173 Result += "0\n";
3174 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003175
Steve Naroffd9803712009-04-29 16:37:50 +00003176 // Mark this protocol as having been generated.
3177 if (!ObjCSynthesizedProtocols.insert(PDecl))
3178 assert(false && "protocol already synthesized");
3179
3180}
3181
3182void RewriteObjC::
3183RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
3184 const char *prefix, const char *ClassName,
3185 std::string &Result) {
3186 if (Protocols.empty()) return;
Mike Stump11289f42009-09-09 15:08:12 +00003187
Steve Naroffd9803712009-04-29 16:37:50 +00003188 for (unsigned i = 0; i != Protocols.size(); i++)
3189 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3190
Chris Lattner388f6e92008-07-21 21:33:21 +00003191 // Output the top lovel protocol meta-data for the class.
3192 /* struct _objc_protocol_list {
3193 struct _objc_protocol_list *next;
3194 int protocol_count;
3195 struct _objc_protocol *class_protocols[];
3196 }
3197 */
3198 Result += "\nstatic struct {\n";
3199 Result += "\tstruct _objc_protocol_list *next;\n";
3200 Result += "\tint protocol_count;\n";
3201 Result += "\tstruct _objc_protocol *class_protocols[";
3202 Result += utostr(Protocols.size());
3203 Result += "];\n} _OBJC_";
3204 Result += prefix;
3205 Result += "_PROTOCOLS_";
3206 Result += ClassName;
3207 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3208 "{\n\t0, ";
3209 Result += utostr(Protocols.size());
3210 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003211
Chris Lattner388f6e92008-07-21 21:33:21 +00003212 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003213 Result += Protocols[0]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003214 Result += " \n";
Mike Stump11289f42009-09-09 15:08:12 +00003215
Chris Lattner388f6e92008-07-21 21:33:21 +00003216 for (unsigned i = 1; i != Protocols.size(); i++) {
3217 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003218 Result += Protocols[i]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003219 Result += "\n";
3220 }
3221 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003222}
3223
Steve Naroffd9803712009-04-29 16:37:50 +00003224
Mike Stump11289f42009-09-09 15:08:12 +00003225/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003226/// implementation.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003227void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003228 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003229 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003230 // Find category declaration for this implementation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003231 ObjCCategoryDecl *CDecl;
Mike Stump11289f42009-09-09 15:08:12 +00003232 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003233 CDecl = CDecl->getNextClassCategory())
3234 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3235 break;
Mike Stump11289f42009-09-09 15:08:12 +00003236
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003237 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003238 FullCategoryName += '_';
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003239 FullCategoryName += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003240
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003241 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003242 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003243 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003244
3245 // If any of our property implementations have associated getters or
3246 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003247 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3248 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003249 Prop != PropEnd; ++Prop) {
3250 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3251 continue;
3252 if (!(*Prop)->getPropertyIvarDecl())
3253 continue;
3254 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3255 if (!PD)
3256 continue;
3257 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3258 InstanceMethods.push_back(Getter);
3259 if (PD->isReadOnly())
3260 continue;
3261 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3262 InstanceMethods.push_back(Setter);
3263 }
3264 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003265 true, "CATEGORY_", FullCategoryName.c_str(),
3266 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003267
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003268 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003269 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003270 false, "CATEGORY_", FullCategoryName.c_str(),
3271 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003272
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003273 // Protocols referenced in class declaration?
Fariborz Jahanian989e0392007-11-13 22:09:49 +00003274 // Null CDecl is case of a category implementation with no category interface
3275 if (CDecl)
Steve Naroffd9803712009-04-29 16:37:50 +00003276 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
3277 FullCategoryName.c_str(), Result);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003278 /* struct _objc_category {
3279 char *category_name;
3280 char *class_name;
3281 struct _objc_method_list *instance_methods;
3282 struct _objc_method_list *class_methods;
3283 struct _objc_protocol_list *protocols;
3284 // Objective-C 1.0 extensions
3285 uint32_t size; // sizeof (struct _objc_category)
Mike Stump11289f42009-09-09 15:08:12 +00003286 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003287 // @property decl.
Mike Stump11289f42009-09-09 15:08:12 +00003288 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003289 */
Mike Stump11289f42009-09-09 15:08:12 +00003290
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003291 static bool objc_category = false;
3292 if (!objc_category) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003293 Result += "\nstruct _objc_category {\n";
3294 Result += "\tchar *category_name;\n";
3295 Result += "\tchar *class_name;\n";
3296 Result += "\tstruct _objc_method_list *instance_methods;\n";
3297 Result += "\tstruct _objc_method_list *class_methods;\n";
3298 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003299 Result += "\tunsigned int size;\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003300 Result += "\tstruct _objc_property_list *instance_properties;\n";
3301 Result += "};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003302 objc_category = true;
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003303 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003304 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3305 Result += FullCategoryName;
Steve Naroffb327e492008-03-12 17:18:30 +00003306 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003307 Result += IDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003308 Result += "\"\n\t, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003309 Result += ClassDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003310 Result += "\"\n";
Mike Stump11289f42009-09-09 15:08:12 +00003311
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003312 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003313 Result += "\t, (struct _objc_method_list *)"
3314 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3315 Result += FullCategoryName;
3316 Result += "\n";
3317 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003318 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003319 Result += "\t, 0\n";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003320 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003321 Result += "\t, (struct _objc_method_list *)"
3322 "&_OBJC_CATEGORY_CLASS_METHODS_";
3323 Result += FullCategoryName;
3324 Result += "\n";
3325 }
3326 else
3327 Result += "\t, 0\n";
Mike Stump11289f42009-09-09 15:08:12 +00003328
Chris Lattnerf5b77512009-02-20 18:18:36 +00003329 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump11289f42009-09-09 15:08:12 +00003330 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003331 Result += FullCategoryName;
3332 Result += "\n";
3333 }
3334 else
3335 Result += "\t, 0\n";
3336 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003337}
3338
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003339/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3340/// ivar offset.
Mike Stump11289f42009-09-09 15:08:12 +00003341void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
3342 ObjCIvarDecl *ivar,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003343 std::string &Result) {
Steve Naroffde7d0f62008-07-16 18:22:22 +00003344 if (ivar->isBitField()) {
3345 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3346 // place all bitfields at offset 0.
3347 Result += "0";
3348 } else {
3349 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003350 Result += IDecl->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003351 if (LangOpts.Microsoft)
3352 Result += "_IMPL";
3353 Result += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003354 Result += ivar->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003355 Result += ")";
3356 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003357}
3358
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003359//===----------------------------------------------------------------------===//
3360// Meta Data Emission
3361//===----------------------------------------------------------------------===//
3362
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003363void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003364 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003365 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump11289f42009-09-09 15:08:12 +00003366
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003367 // Explictly declared @interface's are already synthesized.
Steve Naroffaac654a2009-04-20 20:09:33 +00003368 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump11289f42009-09-09 15:08:12 +00003369 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003370 // produce correct synthesis as yet.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003371 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003372 }
Mike Stump11289f42009-09-09 15:08:12 +00003373
Chris Lattner30d23e82007-12-12 07:56:42 +00003374 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003375 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump11289f42009-09-09 15:08:12 +00003376 ? IDecl->ivar_size()
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003377 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003378 if (NumIvars > 0) {
3379 static bool objc_ivar = false;
3380 if (!objc_ivar) {
3381 /* struct _objc_ivar {
3382 char *ivar_name;
3383 char *ivar_type;
3384 int ivar_offset;
Mike Stump11289f42009-09-09 15:08:12 +00003385 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003386 */
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003387 Result += "\nstruct _objc_ivar {\n";
3388 Result += "\tchar *ivar_name;\n";
3389 Result += "\tchar *ivar_type;\n";
3390 Result += "\tint ivar_offset;\n";
3391 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003392
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003393 objc_ivar = true;
3394 }
3395
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003396 /* struct {
3397 int ivar_count;
3398 struct _objc_ivar ivar_list[nIvars];
Mike Stump11289f42009-09-09 15:08:12 +00003399 };
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003400 */
Mike Stump11289f42009-09-09 15:08:12 +00003401 Result += "\nstatic struct {\n";
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003402 Result += "\tint ivar_count;\n";
3403 Result += "\tstruct _objc_ivar ivar_list[";
3404 Result += utostr(NumIvars);
3405 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003406 Result += IDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003407 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003408 "{\n\t";
3409 Result += utostr(NumIvars);
3410 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003411
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003412 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor5f662052009-04-23 03:23:08 +00003413 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003414 if (!IDecl->ivar_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00003415 for (ObjCImplementationDecl::ivar_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003416 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor5f662052009-04-23 03:23:08 +00003417 IV != IVEnd; ++IV)
3418 IVars.push_back(*IV);
3419 IVI = IVars.begin();
3420 IVE = IVars.end();
Chris Lattner30d23e82007-12-12 07:56:42 +00003421 } else {
3422 IVI = CDecl->ivar_begin();
3423 IVE = CDecl->ivar_end();
3424 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003425 Result += "\t,{{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003426 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003427 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003428 std::string TmpString, StrEncoding;
3429 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3430 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003431 Result += StrEncoding;
3432 Result += "\", ";
Chris Lattner30d23e82007-12-12 07:56:42 +00003433 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003434 Result += "}\n";
Chris Lattner30d23e82007-12-12 07:56:42 +00003435 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003436 Result += "\t ,{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003437 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003438 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003439 std::string TmpString, StrEncoding;
3440 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3441 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003442 Result += StrEncoding;
3443 Result += "\", ";
Chris Lattner30d23e82007-12-12 07:56:42 +00003444 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003445 Result += "}\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003446 }
Mike Stump11289f42009-09-09 15:08:12 +00003447
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003448 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003449 }
Mike Stump11289f42009-09-09 15:08:12 +00003450
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003451 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003452 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003453 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003454
3455 // If any of our property implementations have associated getters or
3456 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003457 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3458 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003459 Prop != PropEnd; ++Prop) {
3460 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3461 continue;
3462 if (!(*Prop)->getPropertyIvarDecl())
3463 continue;
3464 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3465 if (!PD)
3466 continue;
3467 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3468 InstanceMethods.push_back(Getter);
3469 if (PD->isReadOnly())
3470 continue;
3471 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3472 InstanceMethods.push_back(Setter);
3473 }
3474 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattner86d7d912008-11-24 03:54:41 +00003475 true, "", IDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003476
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003477 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003478 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner86d7d912008-11-24 03:54:41 +00003479 false, "", IDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003480
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003481 // Protocols referenced in class declaration?
Steve Naroffd9803712009-04-29 16:37:50 +00003482 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
3483 "CLASS", CDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003484
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003485 // Declaration of class/meta-class metadata
3486 /* struct _objc_class {
3487 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003488 const char *super_class_name;
3489 char *name;
3490 long version;
3491 long info;
3492 long instance_size;
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003493 struct _objc_ivar_list *ivars;
3494 struct _objc_method_list *methods;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003495 struct objc_cache *cache;
3496 struct objc_protocol_list *protocols;
3497 const char *ivar_layout;
3498 struct _objc_class_ext *ext;
Mike Stump11289f42009-09-09 15:08:12 +00003499 };
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003500 */
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003501 static bool objc_class = false;
3502 if (!objc_class) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003503 Result += "\nstruct _objc_class {\n";
3504 Result += "\tstruct _objc_class *isa;\n";
3505 Result += "\tconst char *super_class_name;\n";
3506 Result += "\tchar *name;\n";
3507 Result += "\tlong version;\n";
3508 Result += "\tlong info;\n";
3509 Result += "\tlong instance_size;\n";
3510 Result += "\tstruct _objc_ivar_list *ivars;\n";
3511 Result += "\tstruct _objc_method_list *methods;\n";
3512 Result += "\tstruct objc_cache *cache;\n";
3513 Result += "\tstruct _objc_protocol_list *protocols;\n";
3514 Result += "\tconst char *ivar_layout;\n";
3515 Result += "\tstruct _objc_class_ext *ext;\n";
3516 Result += "};\n";
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003517 objc_class = true;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003518 }
Mike Stump11289f42009-09-09 15:08:12 +00003519
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003520 // Meta-class metadata generation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003521 ObjCInterfaceDecl *RootClass = 0;
3522 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003523 while (SuperClass) {
3524 RootClass = SuperClass;
3525 SuperClass = SuperClass->getSuperClass();
3526 }
3527 SuperClass = CDecl->getSuperClass();
Mike Stump11289f42009-09-09 15:08:12 +00003528
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003529 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003530 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003531 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003532 "{\n\t(struct _objc_class *)\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003533 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003534 Result += "\"";
3535
3536 if (SuperClass) {
3537 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003538 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003539 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003540 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003541 Result += "\"";
3542 }
3543 else {
3544 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003545 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003546 Result += "\"";
3547 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003548 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003549 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003550 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003551 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff0b844f02008-03-11 18:14:26 +00003552 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003553 Result += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003554 Result += "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003555 }
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003556 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003557 Result += ", 0\n";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003558 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003559 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003560 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003561 Result += ",0,0\n";
3562 }
Fariborz Jahanian486f7182007-10-24 20:54:23 +00003563 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003564 Result += "\t,0,0,0,0\n";
3565 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003566
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003567 // class metadata generation.
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003568 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003569 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003570 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003571 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003572 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003573 if (SuperClass) {
3574 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003575 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003576 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003577 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003578 Result += "\"";
3579 }
3580 else {
3581 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003582 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003583 Result += "\"";
3584 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003585 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003586 Result += ", 0,1";
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003587 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003588 Result += ",0";
3589 else {
3590 // class has size. Must synthesize its size.
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00003591 Result += ",sizeof(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003592 Result += CDecl->getNameAsString();
Steve Naroff14a07462008-03-10 23:33:22 +00003593 if (LangOpts.Microsoft)
3594 Result += "_IMPL";
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003595 Result += ")";
3596 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003597 if (NumIvars > 0) {
Steve Naroff17978c42008-03-11 17:37:02 +00003598 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003599 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003600 Result += "\n\t";
3601 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003602 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003603 Result += ",0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003604 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003605 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003606 Result += CDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003607 Result += ", 0\n\t";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003608 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003609 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003610 Result += ",0,0";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003611 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003612 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003613 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003614 Result += ", 0,0\n";
3615 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003616 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003617 Result += ",0,0,0\n";
3618 Result += "};\n";
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003619}
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003620
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003621/// RewriteImplementations - This routine rewrites all method implementations
3622/// and emits meta-data.
3623
Steve Narofff8cfd162008-11-13 20:07:04 +00003624void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003625 int ClsDefCount = ClassImplementation.size();
3626 int CatDefCount = CategoryImplementation.size();
Mike Stump11289f42009-09-09 15:08:12 +00003627
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003628 // Rewrite implemented methods
3629 for (int i = 0; i < ClsDefCount; i++)
3630 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump11289f42009-09-09 15:08:12 +00003631
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00003632 for (int i = 0; i < CatDefCount; i++)
3633 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofff8cfd162008-11-13 20:07:04 +00003634}
Mike Stump11289f42009-09-09 15:08:12 +00003635
Steve Narofff8cfd162008-11-13 20:07:04 +00003636void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3637 int ClsDefCount = ClassImplementation.size();
3638 int CatDefCount = CategoryImplementation.size();
3639
Steve Naroff30ac2222008-05-07 21:23:49 +00003640 // This is needed for determining instance variable offsets.
Fariborz Jahanian9ab63492010-01-07 18:31:42 +00003641 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003642 // For each implemented class, write out all its meta data.
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003643 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003644 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump11289f42009-09-09 15:08:12 +00003645
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003646 // For each implemented category, write out all its meta data.
3647 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003648 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroffd9803712009-04-29 16:37:50 +00003649
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003650 // Write objc_symtab metadata
3651 /*
3652 struct _objc_symtab
3653 {
3654 long sel_ref_cnt;
3655 SEL *refs;
3656 short cls_def_cnt;
3657 short cat_def_cnt;
3658 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump11289f42009-09-09 15:08:12 +00003659 };
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003660 */
Mike Stump11289f42009-09-09 15:08:12 +00003661
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003662 Result += "\nstruct _objc_symtab {\n";
3663 Result += "\tlong sel_ref_cnt;\n";
3664 Result += "\tSEL *refs;\n";
3665 Result += "\tshort cls_def_cnt;\n";
3666 Result += "\tshort cat_def_cnt;\n";
3667 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3668 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00003669
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003670 Result += "static struct _objc_symtab "
Steve Naroffb327e492008-03-12 17:18:30 +00003671 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003672 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003673 + ", " + utostr(CatDefCount) + "\n";
3674 for (int i = 0; i < ClsDefCount; i++) {
3675 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003676 Result += ClassImplementation[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 for (int i = 0; i < CatDefCount; i++) {
3681 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003682 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003683 Result += "_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003684 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003685 Result += "\n";
3686 }
Mike Stump11289f42009-09-09 15:08:12 +00003687
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003688 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00003689
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003690 // Write objc_module metadata
Mike Stump11289f42009-09-09 15:08:12 +00003691
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003692 /*
3693 struct _objc_module {
3694 long version;
3695 long size;
3696 const char *name;
3697 struct _objc_symtab *symtab;
3698 }
3699 */
Mike Stump11289f42009-09-09 15:08:12 +00003700
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003701 Result += "\nstruct _objc_module {\n";
3702 Result += "\tlong version;\n";
3703 Result += "\tlong size;\n";
3704 Result += "\tconst char *name;\n";
3705 Result += "\tstruct _objc_symtab *symtab;\n";
3706 Result += "};\n\n";
3707 Result += "static struct _objc_module "
Steve Naroffb327e492008-03-12 17:18:30 +00003708 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003709 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003710 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003711 Result += "};\n\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00003712
3713 if (LangOpts.Microsoft) {
Steve Naroffd9803712009-04-29 16:37:50 +00003714 if (ProtocolExprDecls.size()) {
3715 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
3716 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump11289f42009-09-09 15:08:12 +00003717 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00003718 E = ProtocolExprDecls.end(); I != E; ++I) {
3719 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
3720 Result += (*I)->getNameAsString();
3721 Result += " = &_OBJC_PROTOCOL_";
3722 Result += (*I)->getNameAsString();
3723 Result += ";\n";
3724 }
3725 Result += "#pragma data_seg(pop)\n\n";
3726 }
Steve Naroff945a3b12008-03-10 20:43:59 +00003727 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroffcab93d52008-05-07 00:06:16 +00003728 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00003729 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3730 Result += "&_OBJC_MODULES;\n";
3731 Result += "#pragma data_seg(pop)\n\n";
3732 }
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003733}
Chris Lattnera7c19fe2007-10-16 22:36:42 +00003734
Steve Naroff677ab3a2008-10-27 17:20:55 +00003735std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3736 const char *funcName,
3737 std::string Tag) {
3738 const FunctionType *AFT = CE->getFunctionType();
3739 QualType RT = AFT->getResultType();
3740 std::string StructRef = "struct " + Tag;
3741 std::string S = "static " + RT.getAsString() + " __" +
3742 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00003743
Steve Naroff677ab3a2008-10-27 17:20:55 +00003744 BlockDecl *BD = CE->getBlockDecl();
Mike Stump11289f42009-09-09 15:08:12 +00003745
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003746 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump11289f42009-09-09 15:08:12 +00003747 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Narofff26a1d42009-02-02 17:19:26 +00003748 // block (to reference imported block decl refs).
3749 S += "(" + StructRef + " *__cself)";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003750 } else if (BD->param_empty()) {
3751 S += "(" + StructRef + " *__cself)";
3752 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003753 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003754 assert(FT && "SynthesizeBlockFunc: No function proto");
3755 S += '(';
3756 // first add the implicit argument.
3757 S += StructRef + " *__cself, ";
3758 std::string ParamStr;
3759 for (BlockDecl::param_iterator AI = BD->param_begin(),
3760 E = BD->param_end(); AI != E; ++AI) {
3761 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003762 ParamStr = (*AI)->getNameAsString();
Douglas Gregor7de59662009-05-29 20:38:28 +00003763 (*AI)->getType().getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003764 S += ParamStr;
3765 }
3766 if (FT->isVariadic()) {
3767 if (!BD->param_empty()) S += ", ";
3768 S += "...";
3769 }
3770 S += ')';
3771 }
3772 S += " {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003773
Steve Naroff677ab3a2008-10-27 17:20:55 +00003774 // Create local declarations to avoid rewriting all closure decl ref exprs.
3775 // First, emit a declaration for all "by ref" decls.
Mike Stump11289f42009-09-09 15:08:12 +00003776 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003777 E = BlockByRefDecls.end(); I != E; ++I) {
3778 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003779 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian02e07732009-12-23 02:07:37 +00003780 std::string TypeString = "struct __Block_byref_" + Name + " *";
3781 Name = TypeString + Name;
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003782 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump11289f42009-09-09 15:08:12 +00003783 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003784 // Next, emit a declaration for all "by copy" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00003785 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003786 E = BlockByCopyDecls.end(); I != E; ++I) {
3787 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003788 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003789 // Handle nested closure invocation. For example:
3790 //
3791 // void (^myImportedClosure)(void);
3792 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003793 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003794 // void (^anotherClosure)(void);
3795 // anotherClosure = ^(void) {
3796 // myImportedClosure(); // import and invoke the closure
3797 // };
3798 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003799 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00003800 S += "struct __block_impl *";
3801 else
Douglas Gregor7de59662009-05-29 20:38:28 +00003802 (*I)->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003803 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003804 }
3805 std::string RewrittenStr = RewrittenBlockExprs[CE];
3806 const char *cstr = RewrittenStr.c_str();
3807 while (*cstr++ != '{') ;
3808 S += cstr;
3809 S += "\n";
3810 return S;
3811}
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00003812
Steve Naroff677ab3a2008-10-27 17:20:55 +00003813std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3814 const char *funcName,
3815 std::string Tag) {
3816 std::string StructRef = "struct " + Tag;
3817 std::string S = "static void __";
Mike Stump11289f42009-09-09 15:08:12 +00003818
Steve Naroff677ab3a2008-10-27 17:20:55 +00003819 S += funcName;
3820 S += "_block_copy_" + utostr(i);
3821 S += "(" + StructRef;
3822 S += "*dst, " + StructRef;
3823 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00003824 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003825 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00003826 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003827 S += (*I)->getNameAsString();
Steve Naroff5ac4eac2008-12-11 20:51:38 +00003828 S += ", (void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003829 S += (*I)->getNameAsString();
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003830 if (BlockByRefDecls.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003831 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003832 else
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003833 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003834 }
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003835 S += "}\n";
3836
Steve Naroff677ab3a2008-10-27 17:20:55 +00003837 S += "\nstatic void __";
3838 S += funcName;
3839 S += "_block_dispose_" + utostr(i);
3840 S += "(" + StructRef;
3841 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00003842 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003843 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00003844 S += "_Block_object_dispose((void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003845 S += (*I)->getNameAsString();
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003846 if (BlockByRefDecls.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003847 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003848 else
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003849 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003850 }
Mike Stump11289f42009-09-09 15:08:12 +00003851 S += "}\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003852 return S;
3853}
3854
Steve Naroff30484702009-12-06 21:14:13 +00003855std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3856 std::string Desc) {
Steve Naroff295570a2008-10-30 12:09:33 +00003857 std::string S = "\nstruct " + Tag;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003858 std::string Constructor = " " + Tag;
Mike Stump11289f42009-09-09 15:08:12 +00003859
Steve Naroff677ab3a2008-10-27 17:20:55 +00003860 S += " {\n struct __block_impl impl;\n";
Steve Naroff30484702009-12-06 21:14:13 +00003861 S += " struct " + Desc;
3862 S += "* Desc;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003863
Steve Naroff30484702009-12-06 21:14:13 +00003864 Constructor += "(void *fp, "; // Invoke function pointer.
3865 Constructor += "struct " + Desc; // Descriptor pointer.
3866 Constructor += " *desc";
Mike Stump11289f42009-09-09 15:08:12 +00003867
Steve Naroff677ab3a2008-10-27 17:20:55 +00003868 if (BlockDeclRefs.size()) {
3869 // Output all "by copy" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00003870 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003871 E = BlockByCopyDecls.end(); I != E; ++I) {
3872 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003873 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003874 std::string ArgName = "_" + FieldName;
3875 // Handle nested closure invocation. For example:
3876 //
3877 // void (^myImportedBlock)(void);
3878 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003879 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003880 // void (^anotherBlock)(void);
3881 // anotherBlock = ^(void) {
3882 // myImportedBlock(); // import and invoke the closure
3883 // };
3884 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003885 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00003886 S += "struct __block_impl *";
3887 Constructor += ", void *" + ArgName;
3888 } else {
Douglas Gregor7de59662009-05-29 20:38:28 +00003889 (*I)->getType().getAsStringInternal(FieldName, Context->PrintingPolicy);
3890 (*I)->getType().getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003891 Constructor += ", " + ArgName;
3892 }
3893 S += FieldName + ";\n";
3894 }
3895 // Output all "by ref" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00003896 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003897 E = BlockByRefDecls.end(); I != E; ++I) {
3898 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003899 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003900 std::string ArgName = "_" + FieldName;
3901 // Handle nested closure invocation. For example:
3902 //
3903 // void (^myImportedBlock)(void);
3904 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003905 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003906 // void (^anotherBlock)(void);
3907 // anotherBlock = ^(void) {
3908 // myImportedBlock(); // import and invoke the closure
3909 // };
3910 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003911 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00003912 S += "struct __block_impl *";
3913 Constructor += ", void *" + ArgName;
3914 } else {
Fariborz Jahanian02e07732009-12-23 02:07:37 +00003915 std::string TypeString = "struct __Block_byref_" + FieldName;
3916 TypeString += " *";
3917 FieldName = TypeString + FieldName;
3918 ArgName = TypeString + ArgName;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003919 Constructor += ", " + ArgName;
3920 }
3921 S += FieldName + "; // by ref\n";
3922 }
3923 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00003924 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00003925 if (GlobalVarDecl)
3926 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3927 else
3928 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00003929 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003930
Steve Naroff30484702009-12-06 21:14:13 +00003931 Constructor += " Desc = desc;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003932
Steve Naroff677ab3a2008-10-27 17:20:55 +00003933 // Initialize all "by copy" arguments.
Mike Stump11289f42009-09-09 15:08:12 +00003934 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003935 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003936 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003937 Constructor += " ";
Steve Naroffa5c0db82008-12-11 21:05:33 +00003938 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00003939 Constructor += Name + " = (struct __block_impl *)_";
3940 else
3941 Constructor += Name + " = _";
3942 Constructor += Name + ";\n";
3943 }
3944 // Initialize all "by ref" arguments.
Mike Stump11289f42009-09-09 15:08:12 +00003945 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003946 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003947 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003948 Constructor += " ";
Steve Naroffa5c0db82008-12-11 21:05:33 +00003949 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00003950 Constructor += Name + " = (struct __block_impl *)_";
3951 else
3952 Constructor += Name + " = _";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00003953 Constructor += Name + "->__forwarding;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003954 }
3955 } else {
3956 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00003957 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00003958 if (GlobalVarDecl)
3959 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3960 else
3961 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00003962 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3963 Constructor += " Desc = desc;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003964 }
3965 Constructor += " ";
3966 Constructor += "}\n";
3967 S += Constructor;
3968 S += "};\n";
3969 return S;
3970}
3971
Steve Naroff30484702009-12-06 21:14:13 +00003972std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
3973 std::string ImplTag, int i,
3974 const char *FunName,
3975 unsigned hasCopy) {
3976 std::string S = "\nstatic struct " + DescTag;
3977
3978 S += " {\n unsigned long reserved;\n";
3979 S += " unsigned long Block_size;\n";
3980 if (hasCopy) {
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00003981 S += " void (*copy)(struct ";
3982 S += ImplTag; S += "*, struct ";
3983 S += ImplTag; S += "*);\n";
3984
3985 S += " void (*dispose)(struct ";
3986 S += ImplTag; S += "*);\n";
Steve Naroff30484702009-12-06 21:14:13 +00003987 }
3988 S += "} ";
3989
3990 S += DescTag + "_DATA = { 0, sizeof(struct ";
3991 S += ImplTag + ")";
3992 if (hasCopy) {
3993 S += ", __" + std::string(FunName) + "_block_copy_" + utostr(i);
3994 S += ", __" + std::string(FunName) + "_block_dispose_" + utostr(i);
3995 }
3996 S += "};\n";
3997 return S;
3998}
3999
Steve Naroff677ab3a2008-10-27 17:20:55 +00004000void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4001 const char *FunName) {
4002 // Insert closures that were part of the function.
4003 for (unsigned i = 0; i < Blocks.size(); i++) {
4004
4005 CollectBlockDeclRefInfo(Blocks[i]);
4006
Steve Naroff30484702009-12-06 21:14:13 +00004007 std::string ImplTag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
4008 std::string DescTag = "__" + std::string(FunName) + "_block_desc_" + utostr(i);
Mike Stump11289f42009-09-09 15:08:12 +00004009
Steve Naroff30484702009-12-06 21:14:13 +00004010 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004011
4012 InsertText(FunLocStart, CI.c_str(), CI.size());
4013
Steve Naroff30484702009-12-06 21:14:13 +00004014 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump11289f42009-09-09 15:08:12 +00004015
Steve Naroff677ab3a2008-10-27 17:20:55 +00004016 InsertText(FunLocStart, CF.c_str(), CF.size());
4017
4018 if (ImportedBlockDecls.size()) {
Steve Naroff30484702009-12-06 21:14:13 +00004019 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004020 InsertText(FunLocStart, HF.c_str(), HF.size());
4021 }
Steve Naroff30484702009-12-06 21:14:13 +00004022 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4023 ImportedBlockDecls.size() > 0);
4024 InsertText(FunLocStart, BD.c_str(), BD.size());
Mike Stump11289f42009-09-09 15:08:12 +00004025
Steve Naroff677ab3a2008-10-27 17:20:55 +00004026 BlockDeclRefs.clear();
4027 BlockByRefDecls.clear();
4028 BlockByCopyDecls.clear();
4029 BlockCallExprs.clear();
4030 ImportedBlockDecls.clear();
4031 }
4032 Blocks.clear();
4033 RewrittenBlockExprs.clear();
4034}
4035
4036void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4037 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner86d7d912008-11-24 03:54:41 +00004038 const char *FuncName = FD->getNameAsCString();
Mike Stump11289f42009-09-09 15:08:12 +00004039
Steve Naroff677ab3a2008-10-27 17:20:55 +00004040 SynthesizeBlockLiterals(FunLocStart, FuncName);
4041}
4042
4043void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroff295570a2008-10-30 12:09:33 +00004044 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4045 //SourceLocation FunLocStart = MD->getLocStart();
4046 // FIXME: This hack works around a bug in Rewrite.InsertText().
4047 SourceLocation FunLocStart = MD->getLocStart().getFileLocWithOffset(-1);
Chris Lattnere4b95692008-11-24 03:33:13 +00004048 std::string FuncName = MD->getSelector().getAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004049 // Convert colons to underscores.
4050 std::string::size_type loc = 0;
4051 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4052 FuncName.replace(loc, 1, "_");
Mike Stump11289f42009-09-09 15:08:12 +00004053
Steve Naroff677ab3a2008-10-27 17:20:55 +00004054 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
4055}
4056
4057void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
4058 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4059 CI != E; ++CI)
4060 if (*CI) {
4061 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4062 GetBlockDeclRefExprs(CBE->getBody());
4063 else
4064 GetBlockDeclRefExprs(*CI);
4065 }
4066 // Handle specific things.
4067 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
4068 // FIXME: Handle enums.
4069 if (!isa<FunctionDecl>(CDRE->getDecl()))
4070 BlockDeclRefs.push_back(CDRE);
4071 return;
4072}
4073
4074void RewriteObjC::GetBlockCallExprs(Stmt *S) {
4075 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4076 CI != E; ++CI)
4077 if (*CI) {
4078 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4079 GetBlockCallExprs(CBE->getBody());
4080 else
4081 GetBlockCallExprs(*CI);
4082 }
Mike Stump11289f42009-09-09 15:08:12 +00004083
Steve Naroff677ab3a2008-10-27 17:20:55 +00004084 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
4085 if (CE->getCallee()->getType()->isBlockPointerType()) {
4086 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
4087 }
4088 }
4089 return;
4090}
4091
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004092Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004093 // Navigate to relevant type information.
Steve Naroff677ab3a2008-10-27 17:20:55 +00004094 const BlockPointerType *CPT = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004095
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004096 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004097 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004098 } else if (const BlockDeclRefExpr *CDRE =
4099 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004100 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004101 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004102 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004103 }
4104 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4105 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4106 }
4107 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4108 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4109 else if (const ConditionalOperator *CEXPR =
4110 dyn_cast<ConditionalOperator>(BlockExp)) {
4111 Expr *LHSExp = CEXPR->getLHS();
4112 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4113 Expr *RHSExp = CEXPR->getRHS();
4114 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4115 Expr *CONDExp = CEXPR->getCond();
4116 ConditionalOperator *CondExpr =
4117 new (Context) ConditionalOperator(CONDExp,
4118 SourceLocation(), cast<Expr>(LHSStmt),
4119 SourceLocation(), cast<Expr>(RHSStmt),
4120 Exp->getType());
4121 return CondExpr;
Fariborz Jahanian6ab7ed42009-12-18 01:15:21 +00004122 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4123 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004124 } else {
4125 assert(1 && "RewriteBlockClass: Bad type");
4126 }
4127 assert(CPT && "RewriteBlockClass: Bad type");
John McCall9dd450b2009-09-21 23:43:11 +00004128 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004129 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004130 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004131 // FTP will be null for closures that don't take arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004132
Steve Naroff350b6652008-10-30 10:07:53 +00004133 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
4134 SourceLocation(),
4135 &Context->Idents.get("__block_impl"));
4136 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff677ab3a2008-10-27 17:20:55 +00004137
Steve Naroff350b6652008-10-30 10:07:53 +00004138 // Generate a funky cast.
4139 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00004140
Steve Naroff350b6652008-10-30 10:07:53 +00004141 // Push the block argument type.
4142 ArgTypes.push_back(PtrBlock);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004143 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004144 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff350b6652008-10-30 10:07:53 +00004145 E = FTP->arg_type_end(); I && (I != E); ++I) {
4146 QualType t = *I;
4147 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffa5c0db82008-12-11 21:05:33 +00004148 if (isTopLevelBlockPointerType(t)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004149 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroff350b6652008-10-30 10:07:53 +00004150 t = Context->getPointerType(BPT->getPointeeType());
4151 }
4152 ArgTypes.push_back(t);
4153 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004154 }
Steve Naroff350b6652008-10-30 10:07:53 +00004155 // Now do the pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00004156 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
Steve Naroff350b6652008-10-30 10:07:53 +00004157 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004158
Steve Naroff350b6652008-10-30 10:07:53 +00004159 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump11289f42009-09-09 15:08:12 +00004160
4161 CastExpr *BlkCast = new (Context) CStyleCastExpr(PtrBlock,
Anders Carlssona2615922009-07-31 00:48:10 +00004162 CastExpr::CK_Unknown,
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004163 const_cast<Expr*>(BlockExp),
Ted Kremenek5a201952009-02-07 01:47:29 +00004164 PtrBlock, SourceLocation(),
4165 SourceLocation());
Steve Naroff350b6652008-10-30 10:07:53 +00004166 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00004167 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4168 BlkCast);
Steve Naroff350b6652008-10-30 10:07:53 +00004169 //PE->dump();
Mike Stump11289f42009-09-09 15:08:12 +00004170
Douglas Gregor91f84212008-12-11 16:49:14 +00004171 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00004172 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004173 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek5a201952009-02-07 01:47:29 +00004174 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4175 FD->getType());
Mike Stump11289f42009-09-09 15:08:12 +00004176
Anders Carlssona2615922009-07-31 00:48:10 +00004177 CastExpr *FunkCast = new (Context) CStyleCastExpr(PtrToFuncCastType,
4178 CastExpr::CK_Unknown, ME,
Ted Kremenek5a201952009-02-07 01:47:29 +00004179 PtrToFuncCastType,
4180 SourceLocation(),
4181 SourceLocation());
4182 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump11289f42009-09-09 15:08:12 +00004183
Steve Naroff350b6652008-10-30 10:07:53 +00004184 llvm::SmallVector<Expr*, 8> BlkExprs;
4185 // Add the implicit argument.
4186 BlkExprs.push_back(BlkCast);
4187 // Add the user arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004188 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004189 E = Exp->arg_end(); I != E; ++I) {
Steve Naroff350b6652008-10-30 10:07:53 +00004190 BlkExprs.push_back(*I);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004191 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004192 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4193 BlkExprs.size(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004194 Exp->getType(), SourceLocation());
Steve Naroff350b6652008-10-30 10:07:53 +00004195 return CE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004196}
4197
4198void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004199 Stmt *BlockCall = SynthesizeBlockCall(Exp, Exp->getCallee());
Steve Naroff350b6652008-10-30 10:07:53 +00004200 ReplaceStmt(Exp, BlockCall);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004201}
4202
Steve Naroffd9803712009-04-29 16:37:50 +00004203// We need to return the rewritten expression to handle cases where the
4204// BlockDeclRefExpr is embedded in another expression being rewritten.
4205// For example:
4206//
4207// int main() {
4208// __block Foo *f;
4209// __block int i;
Mike Stump11289f42009-09-09 15:08:12 +00004210//
Steve Naroffd9803712009-04-29 16:37:50 +00004211// void (^myblock)() = ^() {
4212// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4213// i = 77;
4214// };
4215//}
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004216Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanian25c07fa2009-12-23 19:26:34 +00004217 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004218 // for each DeclRefExp where BYREFVAR is name of the variable.
4219 ValueDecl *VD;
4220 bool isArrow = true;
4221 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4222 VD = BDRE->getDecl();
4223 else {
4224 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4225 isArrow = false;
4226 }
4227
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004228 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4229 &Context->Idents.get("__forwarding"),
4230 Context->VoidPtrTy, 0,
4231 /*BitWidth=*/0, /*Mutable=*/true);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004232 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4233 FD, SourceLocation(),
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004234 FD->getType());
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004235
4236 const char *Name = VD->getNameAsCString();
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004237 FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4238 &Context->Idents.get(Name),
4239 Context->VoidPtrTy, 0,
4240 /*BitWidth=*/0, /*Mutable=*/true);
4241 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004242 DeclRefExp->getType());
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004243
4244
4245
Steve Narofff26a1d42009-02-02 17:19:26 +00004246 // Need parens to enforce precedence.
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004247 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4248 ME);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004249 ReplaceStmt(DeclRefExp, PE);
Steve Naroffd9803712009-04-29 16:37:50 +00004250 return PE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004251}
4252
Steve Naroffc989a7b2008-11-03 23:29:32 +00004253void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4254 SourceLocation LocStart = CE->getLParenLoc();
4255 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofff4b992a2008-10-28 20:29:00 +00004256
4257 // Need to avoid trying to rewrite synthesized casts.
4258 if (LocStart.isInvalid())
4259 return;
Steve Naroff3e7ced12008-11-03 11:20:24 +00004260 // Need to avoid trying to rewrite casts contained in macros.
4261 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4262 return;
Mike Stump11289f42009-09-09 15:08:12 +00004263
Steve Naroff677ab3a2008-10-27 17:20:55 +00004264 const char *startBuf = SM->getCharacterData(LocStart);
4265 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump11289f42009-09-09 15:08:12 +00004266
Steve Naroff677ab3a2008-10-27 17:20:55 +00004267 // advance the location to startArgList.
4268 const char *argPtr = startBuf;
Mike Stump11289f42009-09-09 15:08:12 +00004269
Steve Naroff677ab3a2008-10-27 17:20:55 +00004270 while (*argPtr++ && (argPtr < endBuf)) {
4271 switch (*argPtr) {
Mike Stump11289f42009-09-09 15:08:12 +00004272 case '^':
Steve Naroff677ab3a2008-10-27 17:20:55 +00004273 // Replace the '^' with '*'.
4274 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
4275 ReplaceText(LocStart, 1, "*", 1);
4276 break;
4277 }
4278 }
4279 return;
4280}
4281
4282void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4283 SourceLocation DeclLoc = FD->getLocation();
4284 unsigned parenCount = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004285
Steve Naroff677ab3a2008-10-27 17:20:55 +00004286 // We have 1 or more arguments that have closure pointers.
4287 const char *startBuf = SM->getCharacterData(DeclLoc);
4288 const char *startArgList = strchr(startBuf, '(');
Mike Stump11289f42009-09-09 15:08:12 +00004289
Steve Naroff677ab3a2008-10-27 17:20:55 +00004290 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004291
Steve Naroff677ab3a2008-10-27 17:20:55 +00004292 parenCount++;
4293 // advance the location to startArgList.
4294 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4295 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump11289f42009-09-09 15:08:12 +00004296
Steve Naroff677ab3a2008-10-27 17:20:55 +00004297 const char *argPtr = startArgList;
Mike Stump11289f42009-09-09 15:08:12 +00004298
Steve Naroff677ab3a2008-10-27 17:20:55 +00004299 while (*argPtr++ && parenCount) {
4300 switch (*argPtr) {
Mike Stump11289f42009-09-09 15:08:12 +00004301 case '^':
Steve Naroff677ab3a2008-10-27 17:20:55 +00004302 // Replace the '^' with '*'.
4303 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
4304 ReplaceText(DeclLoc, 1, "*", 1);
4305 break;
Mike Stump11289f42009-09-09 15:08:12 +00004306 case '(':
4307 parenCount++;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004308 break;
Mike Stump11289f42009-09-09 15:08:12 +00004309 case ')':
Steve Naroff677ab3a2008-10-27 17:20:55 +00004310 parenCount--;
4311 break;
4312 }
4313 }
4314 return;
4315}
4316
4317bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004318 const FunctionProtoType *FTP;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004319 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004320 if (PT) {
John McCall9dd450b2009-09-21 23:43:11 +00004321 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004322 } else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004323 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004324 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall9dd450b2009-09-21 23:43:11 +00004325 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004326 }
4327 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004328 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004329 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +00004330 if (isTopLevelBlockPointerType(*I))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004331 return true;
4332 }
4333 return false;
4334}
4335
Ted Kremenek5a201952009-02-07 01:47:29 +00004336void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4337 const char *&RParen) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004338 const char *argPtr = strchr(Name, '(');
4339 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004340
Steve Naroff677ab3a2008-10-27 17:20:55 +00004341 LParen = argPtr; // output the start.
4342 argPtr++; // skip past the left paren.
4343 unsigned parenCount = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004344
Steve Naroff677ab3a2008-10-27 17:20:55 +00004345 while (*argPtr && parenCount) {
4346 switch (*argPtr) {
4347 case '(': parenCount++; break;
4348 case ')': parenCount--; break;
4349 default: break;
4350 }
4351 if (parenCount) argPtr++;
4352 }
4353 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4354 RParen = argPtr; // output the end
4355}
4356
4357void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4358 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4359 RewriteBlockPointerFunctionArgs(FD);
4360 return;
Mike Stump11289f42009-09-09 15:08:12 +00004361 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004362 // Handle Variables and Typedefs.
4363 SourceLocation DeclLoc = ND->getLocation();
4364 QualType DeclT;
4365 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4366 DeclT = VD->getType();
4367 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4368 DeclT = TDD->getUnderlyingType();
4369 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4370 DeclT = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00004371 else
Steve Naroff677ab3a2008-10-27 17:20:55 +00004372 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump11289f42009-09-09 15:08:12 +00004373
Steve Naroff677ab3a2008-10-27 17:20:55 +00004374 const char *startBuf = SM->getCharacterData(DeclLoc);
4375 const char *endBuf = startBuf;
4376 // scan backward (from the decl location) for the end of the previous decl.
4377 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4378 startBuf--;
Mike Stump11289f42009-09-09 15:08:12 +00004379
Steve Naroff677ab3a2008-10-27 17:20:55 +00004380 // *startBuf != '^' if we are dealing with a pointer to function that
4381 // may take block argument types (which will be handled below).
4382 if (*startBuf == '^') {
4383 // Replace the '^' with '*', computing a negative offset.
4384 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
4385 ReplaceText(DeclLoc, 1, "*", 1);
4386 }
4387 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4388 // Replace the '^' with '*' for arguments.
4389 DeclLoc = ND->getLocation();
4390 startBuf = SM->getCharacterData(DeclLoc);
4391 const char *argListBegin, *argListEnd;
4392 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4393 while (argListBegin < argListEnd) {
4394 if (*argListBegin == '^') {
4395 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
4396 ReplaceText(CaretLoc, 1, "*", 1);
4397 }
4398 argListBegin++;
4399 }
4400 }
4401 return;
4402}
4403
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004404
4405/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4406/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4407/// struct Block_byref_id_object *src) {
4408/// _Block_object_assign (&_dest->object, _src->object,
4409/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4410/// [|BLOCK_FIELD_IS_WEAK]) // object
4411/// _Block_object_assign(&_dest->object, _src->object,
4412/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4413/// [|BLOCK_FIELD_IS_WEAK]) // block
4414/// }
4415/// And:
4416/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4417/// _Block_object_dispose(_src->object,
4418/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4419/// [|BLOCK_FIELD_IS_WEAK]) // object
4420/// _Block_object_dispose(_src->object,
4421/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4422/// [|BLOCK_FIELD_IS_WEAK]) // block
4423/// }
4424
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004425std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4426 int flag) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004427 std::string S;
Benjamin Kramere056cea2010-01-10 19:57:50 +00004428 if (CopyDestroyCache.count(flag))
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004429 return S;
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004430 CopyDestroyCache.insert(flag);
4431 S = "static void __Block_byref_id_object_copy_";
4432 S += utostr(flag);
4433 S += "(void *dst, void *src) {\n";
4434
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004435 // offset into the object pointer is computed as:
4436 // void * + void* + int + int + void* + void *
4437 unsigned IntSize =
4438 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4439 unsigned VoidPtrSize =
4440 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4441
4442 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/8;
4443 S += " _Block_object_assign((char*)dst + ";
4444 S += utostr(offset);
4445 S += ", *(void * *) ((char*)src + ";
4446 S += utostr(offset);
4447 S += "), ";
4448 S += utostr(flag);
4449 S += ");\n}\n";
4450
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004451 S += "static void __Block_byref_id_object_dispose_";
4452 S += utostr(flag);
4453 S += "(void *src) {\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004454 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4455 S += utostr(offset);
4456 S += "), ";
4457 S += utostr(flag);
4458 S += ");\n}\n";
4459 return S;
4460}
4461
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004462/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4463/// the declaration into:
4464/// struct __Block_byref_ND {
4465/// void *__isa; // NULL for everything except __weak pointers
4466/// struct __Block_byref_ND *__forwarding;
4467/// int32_t __flags;
4468/// int32_t __size;
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004469/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4470/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004471/// typex ND;
4472/// };
4473///
4474/// It then replaces declaration of ND variable with:
4475/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4476/// __size=sizeof(struct __Block_byref_ND),
4477/// ND=initializer-if-any};
4478///
4479///
4480void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004481 int flag = 0;
4482 int isa = 0;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004483 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4484 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian92368a12009-12-30 20:38:08 +00004485 SourceLocation X = ND->getLocEnd();
4486 X = SM->getInstantiationLoc(X);
4487 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004488 std::string Name(ND->getNameAsString());
4489 std::string ByrefType = "struct __Block_byref_";
4490 ByrefType += Name;
4491 ByrefType += " {\n";
4492 ByrefType += " void *__isa;\n";
4493 ByrefType += " struct __Block_byref_" + Name + " *__forwarding;\n";
4494 ByrefType += " int __flags;\n";
4495 ByrefType += " int __size;\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004496 // Add void *__Block_byref_id_object_copy;
4497 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004498 QualType Ty = ND->getType();
4499 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4500 if (HasCopyAndDispose) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004501 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4502 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004503 }
4504
4505 Ty.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004506 ByrefType += " " + Name + ";\n";
4507 ByrefType += "};\n";
4508 // Insert this type in global scope. It is needed by helper function.
4509 assert(CurFunctionDef && "RewriteByRefVar - CurFunctionDef is null");
4510 SourceLocation FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4511 InsertText(FunLocStart, ByrefType.c_str(), ByrefType.size());
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004512 if (Ty.isObjCGCWeak()) {
4513 flag |= BLOCK_FIELD_IS_WEAK;
4514 isa = 1;
4515 }
4516
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004517 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004518 flag = BLOCK_BYREF_CALLER;
4519 QualType Ty = ND->getType();
4520 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4521 if (Ty->isBlockPointerType())
4522 flag |= BLOCK_FIELD_IS_BLOCK;
4523 else
4524 flag |= BLOCK_FIELD_IS_OBJECT;
4525 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004526 if (!HF.empty())
4527 InsertText(FunLocStart, HF.c_str(), HF.size());
4528 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004529
4530 // struct __Block_byref_ND ND =
4531 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4532 // initializer-if-any};
4533 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanianf7945432010-01-05 18:15:57 +00004534 unsigned flags = 0;
4535 if (HasCopyAndDispose)
4536 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004537 Name = ND->getNameAsString();
4538 ByrefType = "struct __Block_byref_" + Name;
4539 if (!hasInit) {
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004540 ByrefType += " " + Name + " = {(void*)";
4541 ByrefType += utostr(isa);
4542 ByrefType += ", &" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004543 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004544 ByrefType += ", ";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004545 ByrefType += "sizeof(struct __Block_byref_" + Name + ")";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004546 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004547 ByrefType += ", __Block_byref_id_object_copy_";
4548 ByrefType += utostr(flag);
4549 ByrefType += ", __Block_byref_id_object_dispose_";
4550 ByrefType += utostr(flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004551 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004552 ByrefType += "};\n";
4553 ReplaceText(DeclLoc, endBuf-startBuf+Name.size(),
4554 ByrefType.c_str(), ByrefType.size());
4555 }
4556 else {
4557 SourceLocation startLoc = ND->getInit()->getLocStart();
Fariborz Jahanianb8646ed2010-01-05 23:06:29 +00004558 startLoc = SM->getInstantiationLoc(startLoc);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004559 ByrefType += " " + Name;
4560 ReplaceText(DeclLoc, endBuf-startBuf,
4561 ByrefType.c_str(), ByrefType.size());
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004562 ByrefType = " = {(void*)";
4563 ByrefType += utostr(isa);
4564 ByrefType += ", &" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004565 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004566 ByrefType += ", ";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004567 ByrefType += "sizeof(struct __Block_byref_" + Name + "), ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004568 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004569 ByrefType += "__Block_byref_id_object_copy_";
4570 ByrefType += utostr(flag);
4571 ByrefType += ", __Block_byref_id_object_dispose_";
4572 ByrefType += utostr(flag);
4573 ByrefType += ", ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004574 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004575 InsertText(startLoc, ByrefType.c_str(), ByrefType.size());
Steve Naroff13468372009-12-23 17:24:33 +00004576
4577 // Complete the newly synthesized compound expression by inserting a right
4578 // curly brace before the end of the declaration.
4579 // FIXME: This approach avoids rewriting the initializer expression. It
4580 // also assumes there is only one declarator. For example, the following
4581 // isn't currently supported by this routine (in general):
4582 //
4583 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4584 //
4585 const char *startBuf = SM->getCharacterData(startLoc);
4586 const char *semiBuf = strchr(startBuf, ';');
4587 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4588 SourceLocation semiLoc =
4589 startLoc.getFileLocWithOffset(semiBuf-startBuf);
4590
4591 InsertText(semiLoc, "}", 1);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004592 }
Fariborz Jahanian81203462009-12-22 00:48:54 +00004593 return;
4594}
4595
Mike Stump11289f42009-09-09 15:08:12 +00004596void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004597 // Add initializers for any closure decl refs.
4598 GetBlockDeclRefExprs(Exp->getBody());
4599 if (BlockDeclRefs.size()) {
4600 // Unique all "by copy" declarations.
4601 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4602 if (!BlockDeclRefs[i]->isByRef())
4603 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
4604 // Unique all "by ref" declarations.
4605 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4606 if (BlockDeclRefs[i]->isByRef()) {
4607 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
4608 }
4609 // Find any imported blocks...they will need special attention.
4610 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00004611 if (BlockDeclRefs[i]->isByRef() ||
4612 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4613 BlockDeclRefs[i]->getType()->isBlockPointerType()) {
Steve Naroff832d8902008-11-13 17:40:07 +00004614 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004615 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4616 }
4617 }
4618}
4619
Steve Narofff4b992a2008-10-28 20:29:00 +00004620FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
4621 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004622 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Mike Stump11289f42009-09-09 15:08:12 +00004623 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00004624 ID, FType, 0, FunctionDecl::Extern, false,
Douglas Gregor739ef0c2009-02-25 16:33:18 +00004625 false);
Steve Narofff4b992a2008-10-28 20:29:00 +00004626}
4627
Steve Naroffd8907b72008-10-29 18:15:37 +00004628Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004629 Blocks.push_back(Exp);
4630
4631 CollectBlockDeclRefInfo(Exp);
4632 std::string FuncName;
Mike Stump11289f42009-09-09 15:08:12 +00004633
Steve Narofff4b992a2008-10-28 20:29:00 +00004634 if (CurFunctionDef)
Chris Lattnere4b95692008-11-24 03:33:13 +00004635 FuncName = CurFunctionDef->getNameAsString();
Steve Narofff4b992a2008-10-28 20:29:00 +00004636 else if (CurMethodDef) {
Chris Lattnere4b95692008-11-24 03:33:13 +00004637 FuncName = CurMethodDef->getSelector().getAsString();
Steve Narofff4b992a2008-10-28 20:29:00 +00004638 // Convert colons to underscores.
4639 std::string::size_type loc = 0;
4640 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4641 FuncName.replace(loc, 1, "_");
Steve Naroffd8907b72008-10-29 18:15:37 +00004642 } else if (GlobalVarDecl)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004643 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump11289f42009-09-09 15:08:12 +00004644
Steve Narofff4b992a2008-10-28 20:29:00 +00004645 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump11289f42009-09-09 15:08:12 +00004646
Steve Narofff4b992a2008-10-28 20:29:00 +00004647 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4648 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump11289f42009-09-09 15:08:12 +00004649
Steve Narofff4b992a2008-10-28 20:29:00 +00004650 // Get a pointer to the function type so we can cast appropriately.
4651 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
4652
4653 FunctionDecl *FD;
4654 Expr *NewRep;
Mike Stump11289f42009-09-09 15:08:12 +00004655
Steve Narofff4b992a2008-10-28 20:29:00 +00004656 // Simulate a contructor call...
4657 FD = SynthBlockInitFunctionDecl(Tag.c_str());
Ted Kremenek5a201952009-02-07 01:47:29 +00004658 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004659
Steve Narofff4b992a2008-10-28 20:29:00 +00004660 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00004661
Steve Naroffe2514232008-10-29 21:23:59 +00004662 // Initialize the block function.
Steve Narofff4b992a2008-10-28 20:29:00 +00004663 FD = SynthBlockInitFunctionDecl(Func.c_str());
Ted Kremenek5a201952009-02-07 01:47:29 +00004664 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
4665 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004666 CastExpr *castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy,
4667 CastExpr::CK_Unknown, Arg,
Ted Kremenek5a201952009-02-07 01:47:29 +00004668 Context->VoidPtrTy, SourceLocation(),
4669 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004670 InitExprs.push_back(castExpr);
4671
Steve Naroff30484702009-12-06 21:14:13 +00004672 // Initialize the block descriptor.
4673 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump11289f42009-09-09 15:08:12 +00004674
Steve Naroff30484702009-12-06 21:14:13 +00004675 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
4676 &Context->Idents.get(DescData.c_str()),
4677 Context->VoidPtrTy, 0,
4678 VarDecl::Static);
4679 UnaryOperator *DescRefExpr = new (Context) UnaryOperator(
4680 new (Context) DeclRefExpr(NewVD,
4681 Context->VoidPtrTy, SourceLocation()),
4682 UnaryOperator::AddrOf,
4683 Context->getPointerType(Context->VoidPtrTy),
4684 SourceLocation());
4685 InitExprs.push_back(DescRefExpr);
4686
Steve Narofff4b992a2008-10-28 20:29:00 +00004687 // Add initializers for any closure decl refs.
4688 if (BlockDeclRefs.size()) {
Steve Naroffe2514232008-10-29 21:23:59 +00004689 Expr *Exp;
Steve Narofff4b992a2008-10-28 20:29:00 +00004690 // Output all "by copy" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00004691 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00004692 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004693 if (isObjCType((*I)->getType())) {
Steve Naroffe2514232008-10-29 21:23:59 +00004694 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner86d7d912008-11-24 03:54:41 +00004695 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004696 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroffa5c0db82008-12-11 21:05:33 +00004697 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Chris Lattner86d7d912008-11-24 03:54:41 +00004698 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004699 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004700 Exp = new (Context) CStyleCastExpr(Context->VoidPtrTy,
4701 CastExpr::CK_Unknown, Arg,
4702 Context->VoidPtrTy,
Anders Carlssona2615922009-07-31 00:48:10 +00004703 SourceLocation(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004704 SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004705 } else {
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());
Steve Narofff4b992a2008-10-28 20:29:00 +00004708 }
Mike Stump11289f42009-09-09 15:08:12 +00004709 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00004710 }
4711 // Output all "by ref" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00004712 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00004713 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattner86d7d912008-11-24 03:54:41 +00004714 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004715 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4716 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00004717 Context->getPointerType(Exp->getType()),
Steve Naroffe2514232008-10-29 21:23:59 +00004718 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004719 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00004720 }
4721 }
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00004722 if (ImportedBlockDecls.size()) {
4723 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4724 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff30484702009-12-06 21:14:13 +00004725 unsigned IntSize =
4726 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00004727 Expr *FlagExp = new (Context) IntegerLiteral(llvm::APInt(IntSize, flag),
4728 Context->IntTy, SourceLocation());
4729 InitExprs.push_back(FlagExp);
Steve Naroff30484702009-12-06 21:14:13 +00004730 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004731 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4732 FType, SourceLocation());
Ted Kremenek5a201952009-02-07 01:47:29 +00004733 NewRep = new (Context) UnaryOperator(NewRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00004734 Context->getPointerType(NewRep->getType()),
Steve Narofff4b992a2008-10-28 20:29:00 +00004735 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004736 NewRep = new (Context) CStyleCastExpr(FType, CastExpr::CK_Unknown, NewRep,
Anders Carlssona2615922009-07-31 00:48:10 +00004737 FType, SourceLocation(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004738 SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004739 BlockDeclRefs.clear();
4740 BlockByRefDecls.clear();
4741 BlockByCopyDecls.clear();
4742 ImportedBlockDecls.clear();
4743 return NewRep;
4744}
4745
4746//===----------------------------------------------------------------------===//
4747// Function Body / Expression rewriting
4748//===----------------------------------------------------------------------===//
4749
Steve Naroff4588d0f2008-12-04 16:24:46 +00004750// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
4751// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
4752// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
4753// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
4754// Since the rewriter isn't capable of rewriting rewritten code, it's important
4755// we get this right.
4756void RewriteObjC::CollectPropertySetters(Stmt *S) {
4757 // Perform a bottom up traversal of all children.
4758 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4759 CI != E; ++CI)
4760 if (*CI)
4761 CollectPropertySetters(*CI);
4762
4763 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
4764 if (BinOp->isAssignmentOp()) {
4765 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
4766 PropSetters[PRE] = BinOp;
4767 }
4768 }
4769}
4770
Steve Narofff4b992a2008-10-28 20:29:00 +00004771Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump11289f42009-09-09 15:08:12 +00004772 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00004773 isa<DoStmt>(S) || isa<ForStmt>(S))
4774 Stmts.push_back(S);
4775 else if (isa<ObjCForCollectionStmt>(S)) {
4776 Stmts.push_back(S);
Chris Lattnerb71980f2010-01-09 21:45:57 +00004777 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofff4b992a2008-10-28 20:29:00 +00004778 }
Mike Stump11289f42009-09-09 15:08:12 +00004779
Steve Narofff4b992a2008-10-28 20:29:00 +00004780 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004781
Steve Narofff4b992a2008-10-28 20:29:00 +00004782 // Perform a bottom up rewrite of all children.
4783 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4784 CI != E; ++CI)
4785 if (*CI) {
4786 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Mike Stump11289f42009-09-09 15:08:12 +00004787 if (newStmt)
Steve Narofff4b992a2008-10-28 20:29:00 +00004788 *CI = newStmt;
4789 }
Mike Stump11289f42009-09-09 15:08:12 +00004790
Steve Narofff4b992a2008-10-28 20:29:00 +00004791 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4792 // Rewrite the block body in place.
4793 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Mike Stump11289f42009-09-09 15:08:12 +00004794
Steve Narofff4b992a2008-10-28 20:29:00 +00004795 // Now we snarf the rewritten text and stash it away for later use.
Ted Kremenekdb2ef372010-01-07 18:00:35 +00004796 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroffd8907b72008-10-29 18:15:37 +00004797 RewrittenBlockExprs[BE] = Str;
Mike Stump11289f42009-09-09 15:08:12 +00004798
Steve Narofff4b992a2008-10-28 20:29:00 +00004799 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
4800 //blockTranscribed->dump();
Steve Naroffd8907b72008-10-29 18:15:37 +00004801 ReplaceStmt(S, blockTranscribed);
Steve Narofff4b992a2008-10-28 20:29:00 +00004802 return blockTranscribed;
4803 }
4804 // Handle specific things.
4805 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4806 return RewriteAtEncode(AtEncode);
Mike Stump11289f42009-09-09 15:08:12 +00004807
Steve Narofff4b992a2008-10-28 20:29:00 +00004808 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
4809 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
4810
Steve Naroff4588d0f2008-12-04 16:24:46 +00004811 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
4812 BinaryOperator *BinOp = PropSetters[PropRefExpr];
4813 if (BinOp) {
4814 // Because the rewriter doesn't allow us to rewrite rewritten code,
4815 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroff08628db2008-12-09 12:56:34 +00004816 DisableReplaceStmt = true;
4817 // Save the source range. Even if we disable the replacement, the
4818 // rewritten node will have been inserted into the tree. If the synthesized
4819 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump11289f42009-09-09 15:08:12 +00004820 // self.errorHandler = handler ? handler :
Steve Naroff08628db2008-12-09 12:56:34 +00004821 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
4822 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroff4588d0f2008-12-04 16:24:46 +00004823 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroff08628db2008-12-09 12:56:34 +00004824 DisableReplaceStmt = false;
Steve Naroff22216db2008-12-04 23:50:32 +00004825 //
4826 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
4827 // we changed the RHS of BinOp, the rewriter would fail (since it needs
4828 // to see the original expression). Consider this example:
4829 //
4830 // Foo *obj1, *obj2;
4831 //
4832 // obj1.i = [obj2 rrrr];
4833 //
4834 // 'BinOp' for the previous expression looks like:
4835 //
4836 // (BinaryOperator 0x231ccf0 'int' '='
4837 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
4838 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
4839 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
4840 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
4841 //
4842 // 'newStmt' represents the rewritten message expression. For example:
4843 //
4844 // (CallExpr 0x231d300 'id':'struct objc_object *'
4845 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
4846 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
4847 // (CStyleCastExpr 0x231d220 'void *'
4848 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
4849 //
4850 // Note that 'newStmt' is passed to RewritePropertySetter so that it
4851 // can be used as the setter argument. ReplaceStmt() will still 'see'
4852 // the original RHS (since we haven't altered BinOp).
4853 //
Mike Stump11289f42009-09-09 15:08:12 +00004854 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff22216db2008-12-04 23:50:32 +00004855 // node. As a result, we now leak the original AST nodes.
4856 //
Steve Naroff08628db2008-12-09 12:56:34 +00004857 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroff4588d0f2008-12-04 16:24:46 +00004858 } else {
4859 return RewritePropertyGetter(PropRefExpr);
Steve Narofff326f402008-12-03 00:56:33 +00004860 }
4861 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004862 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4863 return RewriteAtSelector(AtSelector);
Mike Stump11289f42009-09-09 15:08:12 +00004864
Steve Narofff4b992a2008-10-28 20:29:00 +00004865 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4866 return RewriteObjCStringLiteral(AtString);
Mike Stump11289f42009-09-09 15:08:12 +00004867
Steve Narofff4b992a2008-10-28 20:29:00 +00004868 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00004869#if 0
Steve Narofff4b992a2008-10-28 20:29:00 +00004870 // Before we rewrite it, put the original message expression in a comment.
4871 SourceLocation startLoc = MessExpr->getLocStart();
4872 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00004873
Steve Narofff4b992a2008-10-28 20:29:00 +00004874 const char *startBuf = SM->getCharacterData(startLoc);
4875 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump11289f42009-09-09 15:08:12 +00004876
Steve Narofff4b992a2008-10-28 20:29:00 +00004877 std::string messString;
4878 messString += "// ";
4879 messString.append(startBuf, endBuf-startBuf+1);
4880 messString += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00004881
4882 // FIXME: Missing definition of
Steve Narofff4b992a2008-10-28 20:29:00 +00004883 // InsertText(clang::SourceLocation, char const*, unsigned int).
4884 // InsertText(startLoc, messString.c_str(), messString.size());
4885 // Tried this, but it didn't work either...
4886 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroff4588d0f2008-12-04 16:24:46 +00004887#endif
Steve Narofff4b992a2008-10-28 20:29:00 +00004888 return RewriteMessageExpr(MessExpr);
4889 }
Mike Stump11289f42009-09-09 15:08:12 +00004890
Steve Narofff4b992a2008-10-28 20:29:00 +00004891 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4892 return RewriteObjCTryStmt(StmtTry);
4893
4894 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4895 return RewriteObjCSynchronizedStmt(StmtTry);
4896
4897 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4898 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump11289f42009-09-09 15:08:12 +00004899
Steve Narofff4b992a2008-10-28 20:29:00 +00004900 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4901 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump11289f42009-09-09 15:08:12 +00004902
4903 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofff4b992a2008-10-28 20:29:00 +00004904 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump11289f42009-09-09 15:08:12 +00004905 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofff4b992a2008-10-28 20:29:00 +00004906 OrigStmtRange.getEnd());
4907 if (BreakStmt *StmtBreakStmt =
4908 dyn_cast<BreakStmt>(S))
4909 return RewriteBreakStmt(StmtBreakStmt);
4910 if (ContinueStmt *StmtContinueStmt =
4911 dyn_cast<ContinueStmt>(S))
4912 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump11289f42009-09-09 15:08:12 +00004913
4914 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofff4b992a2008-10-28 20:29:00 +00004915 // and cast exprs.
4916 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4917 // FIXME: What we're doing here is modifying the type-specifier that
4918 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump11289f42009-09-09 15:08:12 +00004919 // a separate type-specifier that we can rewrite.
Steve Naroffe70a52a2009-12-05 15:55:59 +00004920 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4921 // the context of an ObjCForCollectionStmt. For example:
4922 // NSArray *someArray;
4923 // for (id <FooProtocol> index in someArray) ;
4924 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4925 // and it depends on the original text locations/positions.
Benjamin Krameracc5fa12009-12-05 22:16:51 +00004926 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
Steve Naroffe70a52a2009-12-05 15:55:59 +00004927 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump11289f42009-09-09 15:08:12 +00004928
Steve Narofff4b992a2008-10-28 20:29:00 +00004929 // Blocks rewrite rules.
4930 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4931 DI != DE; ++DI) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004932 Decl *SD = *DI;
Steve Narofff4b992a2008-10-28 20:29:00 +00004933 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00004934 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004935 RewriteBlockPointerDecl(ND);
Mike Stump11289f42009-09-09 15:08:12 +00004936 else if (ND->getType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00004937 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004938 if (VarDecl *VD = dyn_cast<VarDecl>(SD))
4939 if (VD->hasAttr<BlocksAttr>())
4940 RewriteByRefVar(VD);
Steve Narofff4b992a2008-10-28 20:29:00 +00004941 }
4942 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00004943 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004944 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00004945 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00004946 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4947 }
4948 }
4949 }
Mike Stump11289f42009-09-09 15:08:12 +00004950
Steve Narofff4b992a2008-10-28 20:29:00 +00004951 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4952 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump11289f42009-09-09 15:08:12 +00004953
4954 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00004955 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4956 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump11289f42009-09-09 15:08:12 +00004957 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4958 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004959 && "Statement stack mismatch");
4960 Stmts.pop_back();
4961 }
4962 // Handle blocks rewriting.
4963 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4964 if (BDRE->isByRef())
Steve Naroffd9803712009-04-29 16:37:50 +00004965 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofff4b992a2008-10-28 20:29:00 +00004966 }
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004967 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4968 ValueDecl *VD = DRE->getDecl();
4969 if (VD->hasAttr<BlocksAttr>())
4970 return RewriteBlockDeclRefExpr(DRE);
4971 }
4972
Steve Narofff4b992a2008-10-28 20:29:00 +00004973 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroff350b6652008-10-30 10:07:53 +00004974 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004975 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroff350b6652008-10-30 10:07:53 +00004976 ReplaceStmt(S, BlockCall);
4977 return BlockCall;
4978 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004979 }
Steve Naroffc989a7b2008-11-03 23:29:32 +00004980 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004981 RewriteCastExpr(CE);
4982 }
4983#if 0
4984 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Ted Kremenek5a201952009-02-07 01:47:29 +00004985 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004986 // Get the new text.
4987 std::string SStr;
4988 llvm::raw_string_ostream Buf(SStr);
Eli Friedman0905f142009-05-30 05:19:26 +00004989 Replacement->printPretty(Buf, *Context);
Steve Narofff4b992a2008-10-28 20:29:00 +00004990 const std::string &Str = Buf.str();
4991
4992 printf("CAST = %s\n", &Str[0]);
4993 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4994 delete S;
4995 return Replacement;
4996 }
4997#endif
4998 // Return this stmt unmodified.
4999 return S;
5000}
5001
Steve Naroffe70a52a2009-12-05 15:55:59 +00005002void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
5003 for (RecordDecl::field_iterator i = RD->field_begin(),
5004 e = RD->field_end(); i != e; ++i) {
5005 FieldDecl *FD = *i;
5006 if (isTopLevelBlockPointerType(FD->getType()))
5007 RewriteBlockPointerDecl(FD);
5008 if (FD->getType()->isObjCQualifiedIdType() ||
5009 FD->getType()->isObjCQualifiedInterfaceType())
5010 RewriteObjCQualifiedInterfaceTypes(FD);
5011 }
5012}
5013
Steve Narofff4b992a2008-10-28 20:29:00 +00005014/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5015/// main file of the input.
5016void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5017 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffb1368882008-12-17 00:20:22 +00005018 if (FD->isOverloadedOperator())
5019 return;
Mike Stump11289f42009-09-09 15:08:12 +00005020
Steve Narofff4b992a2008-10-28 20:29:00 +00005021 // Since function prototypes don't have ParmDecl's, we check the function
5022 // prototype. This enables us to rewrite function declarations and
5023 // definitions using the same code.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005024 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005025
Sebastian Redla7b98a72009-04-26 20:35:05 +00005026 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00005027 if (CompoundStmt *Body = FD->getCompoundBody()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005028 CurFunctionDef = FD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005029 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005030 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00005031 Body =
5032 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5033 FD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005034 CurrentBody = 0;
5035 if (PropParentMap) {
5036 delete PropParentMap;
5037 PropParentMap = 0;
5038 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005039 // This synthesizes and inserts the block "impl" struct, invoke function,
5040 // and any copy/dispose helper functions.
5041 InsertBlockLiteralsWithinFunction(FD);
5042 CurFunctionDef = 0;
Mike Stump11289f42009-09-09 15:08:12 +00005043 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005044 return;
5045 }
5046 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00005047 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005048 CurMethodDef = MD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005049 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005050 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00005051 Body =
5052 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5053 MD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005054 CurrentBody = 0;
5055 if (PropParentMap) {
5056 delete PropParentMap;
5057 PropParentMap = 0;
5058 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005059 InsertBlockLiteralsWithinMethod(MD);
5060 CurMethodDef = 0;
5061 }
5062 }
5063 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5064 ClassImplementation.push_back(CI);
5065 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5066 CategoryImplementation.push_back(CI);
5067 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
5068 RewriteForwardClassDecl(CD);
5069 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5070 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroffa5c0db82008-12-11 21:05:33 +00005071 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005072 RewriteBlockPointerDecl(VD);
Steve Naroffd8907b72008-10-29 18:15:37 +00005073 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005074 CheckFunctionPointerDecl(VD->getType(), VD);
5075 if (VD->getInit()) {
Steve Naroffc989a7b2008-11-03 23:29:32 +00005076 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005077 RewriteCastExpr(CE);
5078 }
5079 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00005080 } else if (VD->getType()->isRecordType()) {
5081 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5082 if (RD->isDefinition())
5083 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005084 }
Steve Naroffd8907b72008-10-29 18:15:37 +00005085 if (VD->getInit()) {
5086 GlobalVarDecl = VD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005087 CollectPropertySetters(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00005088 CurrentBody = VD->getInit();
Steve Naroffd8907b72008-10-29 18:15:37 +00005089 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00005090 CurrentBody = 0;
5091 if (PropParentMap) {
5092 delete PropParentMap;
5093 PropParentMap = 0;
5094 }
Mike Stump11289f42009-09-09 15:08:12 +00005095 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner86d7d912008-11-24 03:54:41 +00005096 VD->getNameAsCString());
Steve Naroffd8907b72008-10-29 18:15:37 +00005097 GlobalVarDecl = 0;
5098
5099 // This is needed for blocks.
Steve Naroffc989a7b2008-11-03 23:29:32 +00005100 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroffd8907b72008-10-29 18:15:37 +00005101 RewriteCastExpr(CE);
5102 }
5103 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005104 return;
5105 }
5106 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005107 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005108 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00005109 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005110 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
Steve Naroffe70a52a2009-12-05 15:55:59 +00005111 else if (TD->getUnderlyingType()->isRecordType()) {
5112 RecordDecl *RD = TD->getUnderlyingType()->getAs<RecordType>()->getDecl();
5113 if (RD->isDefinition())
5114 RewriteRecordBody(RD);
5115 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005116 return;
5117 }
5118 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroffe70a52a2009-12-05 15:55:59 +00005119 if (RD->isDefinition())
5120 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005121 return;
5122 }
5123 // Nothing yet.
5124}
5125
Chris Lattnercf169832009-03-28 04:11:33 +00005126void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005127 // Get the top-level buffer that this corresponds to.
Mike Stump11289f42009-09-09 15:08:12 +00005128
Steve Narofff4b992a2008-10-28 20:29:00 +00005129 // Rewrite tabs if we care.
5130 //RewriteTabs();
Mike Stump11289f42009-09-09 15:08:12 +00005131
Steve Narofff4b992a2008-10-28 20:29:00 +00005132 if (Diags.hasErrorOccurred())
5133 return;
Mike Stump11289f42009-09-09 15:08:12 +00005134
Steve Narofff4b992a2008-10-28 20:29:00 +00005135 RewriteInclude();
Mike Stump11289f42009-09-09 15:08:12 +00005136
Steve Naroffd9803712009-04-29 16:37:50 +00005137 // Here's a great place to add any extra declarations that may be needed.
5138 // Write out meta data for each @protocol(<expr>).
Mike Stump11289f42009-09-09 15:08:12 +00005139 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00005140 E = ProtocolExprDecls.end(); I != E; ++I)
5141 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5142
Mike Stump11289f42009-09-09 15:08:12 +00005143 InsertText(SM->getLocForStartOfFile(MainFileID),
Steve Narofff4b992a2008-10-28 20:29:00 +00005144 Preamble.c_str(), Preamble.size(), false);
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005145 if (ClassImplementation.size() || CategoryImplementation.size())
5146 RewriteImplementations();
Steve Naroffd9803712009-04-29 16:37:50 +00005147
Steve Narofff4b992a2008-10-28 20:29:00 +00005148 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5149 // we are done.
Mike Stump11289f42009-09-09 15:08:12 +00005150 if (const RewriteBuffer *RewriteBuf =
Steve Narofff4b992a2008-10-28 20:29:00 +00005151 Rewrite.getRewriteBufferFor(MainFileID)) {
5152 //printf("Changed:\n");
5153 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5154 } else {
5155 fprintf(stderr, "No changes\n");
5156 }
Steve Narofff8cfd162008-11-13 20:07:04 +00005157
Steve Naroffd9803712009-04-29 16:37:50 +00005158 if (ClassImplementation.size() || CategoryImplementation.size() ||
5159 ProtocolExprDecls.size()) {
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005160 // Rewrite Objective-c meta data*
5161 std::string ResultStr;
5162 SynthesizeMetaDataIntoBuffer(ResultStr);
5163 // Emit metadata.
5164 *OutFile << ResultStr;
5165 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005166 OutFile->flush();
5167}
5168