blob: cfb6fbf544fec48fd520d323cdcf04f3da653369 [file] [log] [blame]
Steve Naroffb29b4272008-04-14 22:03:09 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
Chris Lattner77cd2a02007-10-11 00:43:27 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-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 Lattner77cd2a02007-10-11 00:43:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
Eli Friedman39d7c4d2009-05-18 22:50:54 +000014#include "clang/Frontend/ASTConsumers.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Steve Naroff8599e7a2008-12-08 16:43:47 +000018#include "clang/AST/ParentMap.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000019#include "clang/Basic/SourceManager.h"
Steve Naroffebf2b562007-10-23 23:50:29 +000020#include "clang/Basic/IdentifierTable.h"
Chris Lattner07506182007-11-30 22:53:43 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattner26de4652007-12-02 01:13:47 +000022#include "clang/Lex/Lexer.h"
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +000023#include "llvm/Support/MemoryBuffer.h"
24#include "llvm/Support/raw_ostream.h"
Chris Lattner158ecb92007-10-25 17:07:24 +000025#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000026#include "llvm/ADT/SmallPtrSet.h"
Ted Kremeneka95d3752008-09-13 05:16:45 +000027#include "llvm/ADT/OwningPtr.h"
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +000028#include "llvm/ADT/DenseSet.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000029using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000030using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000031
Chris Lattner77cd2a02007-10-11 00:43:27 +000032namespace {
Steve Naroffb29b4272008-04-14 22:03:09 +000033 class RewriteObjC : public ASTConsumer {
Fariborz Jahanian73e437b2009-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 Lattner2c64b7b2007-10-16 21:07:07 +000056 Rewriter Rewrite;
Chris Lattnere365c502007-11-30 22:25:36 +000057 Diagnostic &Diags;
Steve Naroff4f943c22008-03-10 20:43:59 +000058 const LangOptions &LangOpts;
Steve Narofff69cc5d2008-01-30 19:17:43 +000059 unsigned RewriteFailedDiag;
Steve Naroff8c565152008-12-05 17:03:39 +000060 unsigned TryFinallyContainsReturnDiag;
Mike Stump1eb44332009-09-09 15:08:12 +000061
Chris Lattner01c57482007-10-17 22:35:30 +000062 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000063 SourceManager *SM;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000064 TranslationUnitDecl *TUDecl;
Chris Lattner2b2453a2009-01-17 06:22:33 +000065 FileID MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000066 const char *MainFileStart, *MainFileEnd;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000067 SourceLocation LastIncLoc;
Mike Stump1eb44332009-09-09 15:08:12 +000068
Ted Kremeneka526c5c2008-01-07 19:49:32 +000069 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
70 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
71 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Narofffbfe8252008-05-06 18:26:51 +000072 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000073 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
74 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000075 llvm::SmallVector<Stmt *, 32> Stmts;
76 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroff621edce2009-04-29 16:37:50 +000077 // Remember all the @protocol(<expr>) expressions.
78 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +000079
80 llvm::DenseSet<uint64_t> CopyDestroyCache;
81
Steve Naroffd82a9ab2008-03-15 00:55:56 +000082 unsigned NumObjCStringLiterals;
Mike Stump1eb44332009-09-09 15:08:12 +000083
Steve Naroffebf2b562007-10-23 23:50:29 +000084 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000085 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000086 FunctionDecl *MsgSendStretFunctionDecl;
87 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000088 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000089 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000090 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000091 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000092 FunctionDecl *CFStringFunctionDecl;
Steve Naroffc0a123c2008-03-11 17:37:02 +000093 FunctionDecl *SuperContructorFunctionDecl;
Mike Stump1eb44332009-09-09 15:08:12 +000094
Steve Naroffbeaf2992007-11-03 11:27:19 +000095 // ObjC string constant support.
Steve Naroff248a7532008-04-15 22:42:06 +000096 VarDecl *ConstantStringClassReference;
Steve Naroffbeaf2992007-11-03 11:27:19 +000097 RecordDecl *NSStringRecord;
Mike Stump1eb44332009-09-09 15:08:12 +000098
Fariborz Jahanianb586cce2008-01-16 00:09:11 +000099 // ObjC foreach break/continue generation support.
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000100 int BcLabelCount;
Mike Stump1eb44332009-09-09 15:08:12 +0000101
Steve Naroff874e2322007-11-15 10:28:18 +0000102 // Needed for super.
Steve Naroff54055232008-10-27 17:20:55 +0000103 ObjCMethodDecl *CurMethodDef;
Steve Naroff874e2322007-11-15 10:28:18 +0000104 RecordDecl *SuperStructDecl;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000105 RecordDecl *ConstantStringDecl;
Mike Stump1eb44332009-09-09 15:08:12 +0000106
Steve Naroff621edce2009-04-29 16:37:50 +0000107 TypeDecl *ProtocolTypeDecl;
108 QualType getProtocolType();
Mike Stump1eb44332009-09-09 15:08:12 +0000109
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000110 // Needed for header files being rewritten
111 bool IsHeader;
Mike Stump1eb44332009-09-09 15:08:12 +0000112
Steve Naroffa7b402d2008-03-28 22:26:09 +0000113 std::string InFileName;
Eli Friedman66d6f042009-05-18 22:20:00 +0000114 llvm::raw_ostream* OutFile;
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000115
116 bool SilenceRewriteMacroWarning;
117
Steve Naroffba92b2e2008-03-27 22:29:16 +0000118 std::string Preamble;
Steve Naroff54055232008-10-27 17:20:55 +0000119
120 // Block expressions.
121 llvm::SmallVector<BlockExpr *, 32> Blocks;
122 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
123 llvm::DenseMap<BlockDeclRefExpr *, CallExpr *> BlockCallExprs;
Mike Stump1eb44332009-09-09 15:08:12 +0000124
Steve Naroff54055232008-10-27 17:20:55 +0000125 // Block related declarations.
126 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDecls;
127 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDecls;
128 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
129
130 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
131
Steve Naroffc77a6362008-12-04 16:24:46 +0000132 // This maps a property to it's assignment statement.
133 llvm::DenseMap<ObjCPropertyRefExpr *, BinaryOperator *> PropSetters;
Steve Naroff8599e7a2008-12-08 16:43:47 +0000134 // This maps a property to it's synthesied message expression.
135 // This allows us to rewrite chained getters (e.g. o.a.b.c).
136 llvm::DenseMap<ObjCPropertyRefExpr *, Stmt *> PropGetters;
Mike Stump1eb44332009-09-09 15:08:12 +0000137
Steve Naroff4c3580e2008-12-04 23:50:32 +0000138 // This maps an original source AST to it's rewritten form. This allows
139 // us to avoid rewriting the same node twice (which is very uncommon).
140 // This is needed to support some of the exotic property rewriting.
141 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Naroff15f081d2008-12-03 00:56:33 +0000142
Steve Naroff54055232008-10-27 17:20:55 +0000143 FunctionDecl *CurFunctionDef;
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000144 VarDecl *GlobalVarDecl;
Mike Stump1eb44332009-09-09 15:08:12 +0000145
Steve Naroffb619d952008-12-09 12:56:34 +0000146 bool DisableReplaceStmt;
Mike Stump1eb44332009-09-09 15:08:12 +0000147
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000148 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +0000149 public:
Ted Kremeneke3a61982008-05-31 20:11:04 +0000150 virtual void Initialize(ASTContext &context);
151
Chris Lattnerf04da132007-10-24 17:06:59 +0000152 // Top Level Driver code.
Chris Lattner682bf922009-03-29 16:50:03 +0000153 virtual void HandleTopLevelDecl(DeclGroupRef D) {
154 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I)
155 HandleTopLevelSingleDecl(*I);
156 }
157 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000158 void HandleDeclInMainFile(Decl *D);
Eli Friedman66d6f042009-05-18 22:20:00 +0000159 RewriteObjC(std::string inFile, llvm::raw_ostream *OS,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000160 Diagnostic &D, const LangOptions &LOpts,
161 bool silenceMacroWarn);
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000162
163 ~RewriteObjC() {}
Mike Stump1eb44332009-09-09 15:08:12 +0000164
Chris Lattnerdacbc5d2009-03-28 04:11:33 +0000165 virtual void HandleTranslationUnit(ASTContext &C);
Mike Stump1eb44332009-09-09 15:08:12 +0000166
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000167 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000168 Stmt *ReplacingStmt = ReplacedNodes[Old];
Mike Stump1eb44332009-09-09 15:08:12 +0000169
Steve Naroff4c3580e2008-12-04 23:50:32 +0000170 if (ReplacingStmt)
171 return; // We can't rewrite the same node twice.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000172
Steve Naroffb619d952008-12-09 12:56:34 +0000173 if (DisableReplaceStmt)
174 return; // Used when rewriting the assignment of a property setter.
175
Steve Naroff4c3580e2008-12-04 23:50:32 +0000176 // If replacement succeeded or warning disabled return with no warning.
177 if (!Rewrite.ReplaceStmt(Old, New)) {
178 ReplacedNodes[Old] = New;
179 return;
180 }
181 if (SilenceRewriteMacroWarning)
182 return;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000183 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
184 << Old->getSourceRange();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000185 }
Steve Naroffb619d952008-12-09 12:56:34 +0000186
187 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
188 // Measaure the old text.
189 int Size = Rewrite.getRangeSize(SrcRange);
190 if (Size == -1) {
191 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
192 << Old->getSourceRange();
193 return;
194 }
195 // Get the new text.
196 std::string SStr;
197 llvm::raw_string_ostream S(SStr);
Chris Lattnere4f21422009-06-30 01:26:17 +0000198 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
Steve Naroffb619d952008-12-09 12:56:34 +0000199 const std::string &Str = S.str();
200
201 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbard7407dc2009-08-19 19:10:30 +0000202 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroffb619d952008-12-09 12:56:34 +0000203 ReplacedNodes[Old] = New;
204 return;
205 }
206 if (SilenceRewriteMacroWarning)
207 return;
208 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
209 << Old->getSourceRange();
210 }
211
Steve Naroffba92b2e2008-03-27 22:29:16 +0000212 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
213 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000214 // If insertion succeeded or warning disabled return with no warning.
Daniel Dunbard7407dc2009-08-19 19:10:30 +0000215 if (!Rewrite.InsertText(Loc, llvm::StringRef(StrData, StrLen),
216 InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000217 SilenceRewriteMacroWarning)
218 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000219
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000220 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
221 }
Mike Stump1eb44332009-09-09 15:08:12 +0000222
Chris Lattneraadaf782008-01-31 19:51:04 +0000223 void RemoveText(SourceLocation Loc, unsigned StrLen) {
224 // If removal succeeded or warning disabled return with no warning.
225 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
226 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000227
Chris Lattneraadaf782008-01-31 19:51:04 +0000228 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
229 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000230
Chris Lattneraadaf782008-01-31 19:51:04 +0000231 void ReplaceText(SourceLocation Start, unsigned OrigLength,
232 const char *NewStr, unsigned NewLength) {
233 // If removal succeeded or warning disabled return with no warning.
Daniel Dunbard7407dc2009-08-19 19:10:30 +0000234 if (!Rewrite.ReplaceText(Start, OrigLength,
235 llvm::StringRef(NewStr, NewLength)) ||
Chris Lattneraadaf782008-01-31 19:51:04 +0000236 SilenceRewriteMacroWarning)
237 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000238
Chris Lattneraadaf782008-01-31 19:51:04 +0000239 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
240 }
Mike Stump1eb44332009-09-09 15:08:12 +0000241
Chris Lattnerf04da132007-10-24 17:06:59 +0000242 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000243 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000244 void RewriteInclude();
Chris Lattnerf04da132007-10-24 17:06:59 +0000245 void RewriteTabs();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000246 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffa0876e82008-12-02 17:36:43 +0000247 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
248 ObjCImplementationDecl *IMD,
249 ObjCCategoryImplDecl *CID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000250 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000251 void RewriteImplementationDecl(Decl *Dcl);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000252 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
253 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
254 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
255 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
256 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff6327e0d2009-01-11 01:06:09 +0000257 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff09b266e2007-10-30 23:14:51 +0000258 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000259 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroff4f95b752008-07-29 18:15:38 +0000260 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffd5255f52007-11-01 13:24:47 +0000261 bool needToScanForQualifiers(QualType T);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000262 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000263 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000264 QualType getConstantStringStructType();
Steve Naroffbaf58c32008-05-31 14:15:04 +0000265 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Mike Stump1eb44332009-09-09 15:08:12 +0000266
Chris Lattnerf04da132007-10-24 17:06:59 +0000267 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000268 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroffc77a6362008-12-04 16:24:46 +0000269 void CollectPropertySetters(Stmt *S);
Mike Stump1eb44332009-09-09 15:08:12 +0000270
Steve Naroff8599e7a2008-12-08 16:43:47 +0000271 Stmt *CurrentBody;
272 ParentMap *PropParentMap; // created lazily.
Mike Stump1eb44332009-09-09 15:08:12 +0000273
Chris Lattnere64b7772007-10-24 16:57:36 +0000274 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000275 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart);
Steve Naroffc77a6362008-12-04 16:24:46 +0000276 Stmt *RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr);
Mike Stump1eb44332009-09-09 15:08:12 +0000277 Stmt *RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroffb619d952008-12-09 12:56:34 +0000278 SourceRange SrcRange);
Steve Naroffb42f8412007-11-05 14:50:49 +0000279 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000280 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000281 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000282 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffb85e77a2009-12-05 21:43:12 +0000283 void WarnAboutReturnGotoStmts(Stmt *S);
284 void HasReturnStmts(Stmt *S, bool &hasReturns);
285 void RewriteTryReturnStmts(Stmt *S);
286 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000287 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000288 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000289 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
290 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
291 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000292 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
293 SourceLocation OrigEnd);
Mike Stump1eb44332009-09-09 15:08:12 +0000294 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
Steve Naroff934f2762007-10-24 22:48:43 +0000295 Expr **args, unsigned nargs);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000296 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000297 Stmt *RewriteBreakStmt(BreakStmt *S);
298 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000299 void SynthCountByEnumWithState(std::string &buf);
Mike Stump1eb44332009-09-09 15:08:12 +0000300
Steve Naroff09b266e2007-10-30 23:14:51 +0000301 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000302 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000303 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000304 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000305 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000306 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000307 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000308 void SynthSelGetUidFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000309 void SynthSuperContructorFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000310
Chris Lattnerf04da132007-10-24 17:06:59 +0000311 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000312 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000313 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000314
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000315 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000316 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000317
Douglas Gregor653f1b12009-04-23 01:02:12 +0000318 template<typename MethodIterator>
319 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
320 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000321 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000322 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000323 const char *ClassName,
324 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000325
Steve Naroff621edce2009-04-29 16:37:50 +0000326 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
327 const char *prefix,
328 const char *ClassName,
329 std::string &Result);
330 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
Mike Stump1eb44332009-09-09 15:08:12 +0000331 const char *prefix,
Steve Naroff621edce2009-04-29 16:37:50 +0000332 const char *ClassName,
333 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000334 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000335 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000336 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
337 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000338 std::string &Result);
Steve Narofface66252008-11-13 20:07:04 +0000339 void RewriteImplementations();
340 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000341
Steve Naroff54055232008-10-27 17:20:55 +0000342 // Block rewriting.
Mike Stump1eb44332009-09-09 15:08:12 +0000343 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff54055232008-10-27 17:20:55 +0000344 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
Mike Stump1eb44332009-09-09 15:08:12 +0000345
Steve Naroff54055232008-10-27 17:20:55 +0000346 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
347 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
Mike Stump1eb44332009-09-09 15:08:12 +0000348
349 // Block specific rewrite rules.
Steve Naroff54055232008-10-27 17:20:55 +0000350 void RewriteBlockCall(CallExpr *Exp);
351 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000352 void RewriteByRefVar(VarDecl *VD);
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +0000353 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +0000354 Stmt *RewriteBlockDeclRefExpr(Expr *VD);
Steve Naroff54055232008-10-27 17:20:55 +0000355 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Mike Stump1eb44332009-09-09 15:08:12 +0000356
357 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Steve Naroff54055232008-10-27 17:20:55 +0000358 const char *funcName, std::string Tag);
Mike Stump1eb44332009-09-09 15:08:12 +0000359 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Steve Naroff54055232008-10-27 17:20:55 +0000360 const char *funcName, std::string Tag);
Steve Naroff01aec112009-12-06 21:14:13 +0000361 std::string SynthesizeBlockImpl(BlockExpr *CE,
362 std::string Tag, std::string Desc);
363 std::string SynthesizeBlockDescriptor(std::string DescTag,
364 std::string ImplTag,
365 int i, const char *funcName,
366 unsigned hasCopy);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +0000367 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff54055232008-10-27 17:20:55 +0000368 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
369 const char *FunName);
Steve Naroff3d7e7862009-12-05 15:55:59 +0000370 void RewriteRecordBody(RecordDecl *RD);
Mike Stump1eb44332009-09-09 15:08:12 +0000371
Steve Naroff54055232008-10-27 17:20:55 +0000372 void CollectBlockDeclRefInfo(BlockExpr *Exp);
373 void GetBlockCallExprs(Stmt *S);
374 void GetBlockDeclRefExprs(Stmt *S);
Mike Stump1eb44332009-09-09 15:08:12 +0000375
Steve Naroff54055232008-10-27 17:20:55 +0000376 // We avoid calling Type::isBlockPointerType(), since it operates on the
377 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000378 bool isTopLevelBlockPointerType(QualType T) {
379 return isa<BlockPointerType>(T);
380 }
Mike Stump1eb44332009-09-09 15:08:12 +0000381
Steve Naroff54055232008-10-27 17:20:55 +0000382 // FIXME: This predicate seems like it would be useful to add to ASTContext.
383 bool isObjCType(QualType T) {
384 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
385 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000386
Steve Naroff54055232008-10-27 17:20:55 +0000387 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000388
Steve Naroff54055232008-10-27 17:20:55 +0000389 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
390 OCT == Context->getCanonicalType(Context->getObjCClassType()))
391 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000392
Ted Kremenek6217b802009-07-29 21:53:49 +0000393 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000394 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000395 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff54055232008-10-27 17:20:55 +0000396 return true;
397 }
398 return false;
399 }
400 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Ted Kremenek8189cde2009-02-07 01:47:29 +0000401 void GetExtentOfArgList(const char *Name, const char *&LParen,
402 const char *&RParen);
Steve Naroffb2f9e512008-11-03 23:29:32 +0000403 void RewriteCastExpr(CStyleCastExpr *CE);
Mike Stump1eb44332009-09-09 15:08:12 +0000404
Steve Narofffa15fd92008-10-28 20:29:00 +0000405 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000406 Stmt *SynthBlockInitExpr(BlockExpr *Exp);
Mike Stump1eb44332009-09-09 15:08:12 +0000407
Steve Naroff621edce2009-04-29 16:37:50 +0000408 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump1eb44332009-09-09 15:08:12 +0000409 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroff621edce2009-04-29 16:37:50 +0000410 if (From[i] == '"')
411 To += "\\\"";
412 else
413 To += From[i];
414 }
415 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000416 };
417}
418
Mike Stump1eb44332009-09-09 15:08:12 +0000419void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
420 NamedDecl *D) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000421 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000422 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +0000423 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000424 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff54055232008-10-27 17:20:55 +0000425 // All the args are checked/rewritten. Don't call twice!
426 RewriteBlockPointerDecl(D);
427 break;
428 }
429 }
430}
431
432void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000433 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +0000434 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor72564e72009-02-26 23:50:07 +0000435 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff54055232008-10-27 17:20:55 +0000436}
437
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000438static bool IsHeaderFile(const std::string &Filename) {
439 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump1eb44332009-09-09 15:08:12 +0000440
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000441 if (DotPos == std::string::npos) {
442 // no file extension
Mike Stump1eb44332009-09-09 15:08:12 +0000443 return false;
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000444 }
Mike Stump1eb44332009-09-09 15:08:12 +0000445
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000446 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
447 // C header: .h
448 // C++ header: .hh or .H;
449 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump1eb44332009-09-09 15:08:12 +0000450}
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000451
Eli Friedman66d6f042009-05-18 22:20:00 +0000452RewriteObjC::RewriteObjC(std::string inFile, llvm::raw_ostream* OS,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000453 Diagnostic &D, const LangOptions &LOpts,
454 bool silenceMacroWarn)
455 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
456 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Naroffa7b402d2008-03-28 22:26:09 +0000457 IsHeader = IsHeaderFile(inFile);
Mike Stump1eb44332009-09-09 15:08:12 +0000458 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000459 "rewriting sub-expression within a macro (may not be correct)");
Mike Stump1eb44332009-09-09 15:08:12 +0000460 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000461 "rewriter doesn't support user-specified control flow semantics "
462 "for @try/@finally (code may not execute properly)");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000463}
464
Eli Friedmanbce831b2009-05-18 22:29:17 +0000465ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
466 llvm::raw_ostream* OS,
Mike Stump1eb44332009-09-09 15:08:12 +0000467 Diagnostic &Diags,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000468 const LangOptions &LOpts,
469 bool SilenceRewriteMacroWarning) {
470 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere365c502007-11-30 22:25:36 +0000471}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000472
Steve Naroffb29b4272008-04-14 22:03:09 +0000473void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000474 Context = &context;
475 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000476 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000477 MsgSendFunctionDecl = 0;
478 MsgSendSuperFunctionDecl = 0;
479 MsgSendStretFunctionDecl = 0;
480 MsgSendSuperStretFunctionDecl = 0;
481 MsgSendFpretFunctionDecl = 0;
482 GetClassFunctionDecl = 0;
483 GetMetaClassFunctionDecl = 0;
484 SelGetUidFunctionDecl = 0;
485 CFStringFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000486 ConstantStringClassReference = 0;
487 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000488 CurMethodDef = 0;
489 CurFunctionDef = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000490 GlobalVarDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000491 SuperStructDecl = 0;
Steve Naroff621edce2009-04-29 16:37:50 +0000492 ProtocolTypeDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000493 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000494 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000495 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000496 NumObjCStringLiterals = 0;
Steve Naroff68272b82008-12-08 20:01:41 +0000497 PropParentMap = 0;
498 CurrentBody = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000499 DisableReplaceStmt = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000500
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000501 // Get the ID and start/end of the main file.
502 MainFileID = SM->getMainFileID();
503 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
504 MainFileStart = MainBuf->getBufferStart();
505 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000506
Chris Lattner2c78b872009-04-14 23:22:57 +0000507 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump1eb44332009-09-09 15:08:12 +0000508
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000509 // declaring objc_selector outside the parameter list removes a silly
510 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000511 if (IsHeader)
Steve Naroff62c26322009-02-03 20:39:18 +0000512 Preamble = "#pragma once\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000513 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff46a98a72008-12-23 20:11:22 +0000514 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000515 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000516 if (LangOpts.Microsoft) {
517 // Add a constructor for creating temporary objects.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000518 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
519 ": ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000520 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000521 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000522 Preamble += "};\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000523 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
524 Preamble += "typedef struct objc_object Protocol;\n";
525 Preamble += "#define _REWRITER_typedef_Protocol\n";
526 Preamble += "#endif\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000527 if (LangOpts.Microsoft) {
528 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
529 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
530 } else
531 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
532 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000533 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000534 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000535 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000536 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000537 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000538 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000539 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000540 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000541 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000542 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000543 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000544 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000545 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000546 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
547 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
548 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
549 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
550 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000551 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000552 // @synchronized hooks.
Steve Naroff4ebd7162008-12-08 17:30:33 +0000553 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
554 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
555 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000556 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
557 Preamble += "struct __objcFastEnumerationState {\n\t";
558 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000559 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000560 Preamble += "unsigned long *mutationsPtr;\n\t";
561 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000562 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000563 Preamble += "#define __FASTENUMERATIONSTATE\n";
564 Preamble += "#endif\n";
565 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
566 Preamble += "struct __NSConstantStringImpl {\n";
567 Preamble += " int *isa;\n";
568 Preamble += " int flags;\n";
569 Preamble += " char *str;\n";
570 Preamble += " long length;\n";
571 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000572 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
573 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
574 Preamble += "#else\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000575 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000576 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000577 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
578 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000579 // Blocks preamble.
580 Preamble += "#ifndef BLOCK_IMPL\n";
581 Preamble += "#define BLOCK_IMPL\n";
582 Preamble += "struct __block_impl {\n";
583 Preamble += " void *isa;\n";
584 Preamble += " int Flags;\n";
Steve Naroff01aec112009-12-06 21:14:13 +0000585 Preamble += " int Reserved;\n";
Steve Naroff54055232008-10-27 17:20:55 +0000586 Preamble += " void *FuncPtr;\n";
587 Preamble += "};\n";
Steve Naroff5bc60d02008-12-16 15:50:30 +0000588 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
Steve Naroffc9c1e9c2009-12-06 01:52:22 +0000589 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000590 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_assign(void *, const void *, const int);\n";
591 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
592 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
593 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
594 Preamble += "#else\n";
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +0000595 Preamble += "__OBJC_RW_DLLIMPORT \"C\" void _Block_object_assign(void *, const void *, const int);\n";
596 Preamble += "__OBJC_RW_DLLIMPORT \"C\" void _Block_object_dispose(const void *, const int);\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000597 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
598 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
599 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000600 Preamble += "#endif\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000601 if (LangOpts.Microsoft) {
Steve Naroff4ebd7162008-12-08 17:30:33 +0000602 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
603 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000604 Preamble += "#define __attribute__(X)\n";
605 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000606 else
607 Preamble += "#define __block\n";
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000608}
609
610
Chris Lattnerf04da132007-10-24 17:06:59 +0000611//===----------------------------------------------------------------------===//
612// Top Level Driver Code
613//===----------------------------------------------------------------------===//
614
Chris Lattner682bf922009-03-29 16:50:03 +0000615void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000616 // Two cases: either the decl could be in the main file, or it could be in a
617 // #included file. If the former, rewrite it now. If the later, check to see
618 // if we rewrote the #include/#import.
619 SourceLocation Loc = D->getLocation();
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000620 Loc = SM->getInstantiationLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000621
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000622 // If this is for a builtin, ignore it.
623 if (Loc.isInvalid()) return;
624
Steve Naroffebf2b562007-10-23 23:50:29 +0000625 // Look for built-in declarations that we need to refer during the rewrite.
626 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000627 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000628 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000629 // declared in <Foundation/NSString.h>
Chris Lattner8ec03f52008-11-24 03:54:41 +0000630 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000631 ConstantStringClassReference = FVD;
632 return;
633 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000634 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000635 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000636 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000637 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000638 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000639 RewriteProtocolDecl(PD);
Mike Stump1eb44332009-09-09 15:08:12 +0000640 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000641 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000642 RewriteForwardProtocolDecl(FP);
Douglas Gregord0434102009-01-09 00:49:46 +0000643 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
644 // Recurse into linkage specifications
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000645 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
646 DIEnd = LSD->decls_end();
Douglas Gregord0434102009-01-09 00:49:46 +0000647 DI != DIEnd; ++DI)
Chris Lattner682bf922009-03-29 16:50:03 +0000648 HandleTopLevelSingleDecl(*DI);
Steve Naroffebf2b562007-10-23 23:50:29 +0000649 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000650 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000651 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000652 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000653}
654
Chris Lattnerf04da132007-10-24 17:06:59 +0000655//===----------------------------------------------------------------------===//
656// Syntactic (non-AST) Rewriting Code
657//===----------------------------------------------------------------------===//
658
Steve Naroffb29b4272008-04-14 22:03:09 +0000659void RewriteObjC::RewriteInclude() {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000660 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000661 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
662 const char *MainBufStart = MainBuf.first;
663 const char *MainBufEnd = MainBuf.second;
664 size_t ImportLen = strlen("import");
665 size_t IncludeLen = strlen("include");
Mike Stump1eb44332009-09-09 15:08:12 +0000666
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000667 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000668 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
669 if (*BufPtr == '#') {
670 if (++BufPtr == MainBufEnd)
671 return;
672 while (*BufPtr == ' ' || *BufPtr == '\t')
673 if (++BufPtr == MainBufEnd)
674 return;
675 if (!strncmp(BufPtr, "import", ImportLen)) {
676 // replace import with include
Mike Stump1eb44332009-09-09 15:08:12 +0000677 SourceLocation ImportLoc =
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000678 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattneraadaf782008-01-31 19:51:04 +0000679 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000680 BufPtr += ImportLen;
681 }
682 }
683 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000684}
685
Steve Naroffb29b4272008-04-14 22:03:09 +0000686void RewriteObjC::RewriteTabs() {
Chris Lattnerf04da132007-10-24 17:06:59 +0000687 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
688 const char *MainBufStart = MainBuf.first;
689 const char *MainBufEnd = MainBuf.second;
Mike Stump1eb44332009-09-09 15:08:12 +0000690
Chris Lattnerf04da132007-10-24 17:06:59 +0000691 // Loop over the whole file, looking for tabs.
692 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
693 if (*BufPtr != '\t')
694 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000695
Chris Lattnerf04da132007-10-24 17:06:59 +0000696 // Okay, we found a tab. This tab will turn into at least one character,
697 // but it depends on which 'virtual column' it is in. Compute that now.
698 unsigned VCol = 0;
699 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
700 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
701 ++VCol;
Mike Stump1eb44332009-09-09 15:08:12 +0000702
Chris Lattnerf04da132007-10-24 17:06:59 +0000703 // Okay, now that we know the virtual column, we know how many spaces to
704 // insert. We assume 8-character tab-stops.
705 unsigned Spaces = 8-(VCol & 7);
Mike Stump1eb44332009-09-09 15:08:12 +0000706
Chris Lattnerf04da132007-10-24 17:06:59 +0000707 // Get the location of the tab.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000708 SourceLocation TabLoc = SM->getLocForStartOfFile(MainFileID);
709 TabLoc = TabLoc.getFileLocWithOffset(BufPtr-MainBufStart);
Mike Stump1eb44332009-09-09 15:08:12 +0000710
Chris Lattnerf04da132007-10-24 17:06:59 +0000711 // Rewrite the single tab character into a sequence of spaces.
Chris Lattneraadaf782008-01-31 19:51:04 +0000712 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerf04da132007-10-24 17:06:59 +0000713 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000714}
715
Steve Naroffeb0646c2008-12-02 15:48:25 +0000716static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
717 ObjCIvarDecl *OID) {
718 std::string S;
719 S = "((struct ";
720 S += ClassDecl->getIdentifier()->getName();
721 S += "_IMPL *)self)->";
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +0000722 S += OID->getName();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000723 return S;
724}
725
Steve Naroffa0876e82008-12-02 17:36:43 +0000726void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
727 ObjCImplementationDecl *IMD,
728 ObjCCategoryImplDecl *CID) {
Steve Naroffd40910b2008-12-01 20:33:01 +0000729 SourceLocation startLoc = PID->getLocStart();
730 InsertText(startLoc, "// ", 3);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000731 const char *startBuf = SM->getCharacterData(startLoc);
732 assert((*startBuf == '@') && "bogus @synthesize location");
733 const char *semiBuf = strchr(startBuf, ';');
734 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek8189cde2009-02-07 01:47:29 +0000735 SourceLocation onePastSemiLoc =
736 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000737
738 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
739 return; // FIXME: is this correct?
Mike Stump1eb44332009-09-09 15:08:12 +0000740
Steve Naroffeb0646c2008-12-02 15:48:25 +0000741 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000742 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000743 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000744 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000745
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000746 if (!OID)
747 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000748
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000749 std::string Getr;
750 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
751 Getr += "{ ";
752 // Synthesize an explicit cast to gain access to the ivar.
Mike Stump1eb44332009-09-09 15:08:12 +0000753 // FIXME: deal with code generation implications for various property
754 // attributes (copy, retain, nonatomic).
Steve Naroff3539cdb2008-12-02 17:54:50 +0000755 // See objc-act.c:objc_synthesize_new_getter() for details.
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000756 Getr += "return " + getIvarAccessString(ClassDecl, OID);
757 Getr += "; }";
Steve Naroffeb0646c2008-12-02 15:48:25 +0000758 InsertText(onePastSemiLoc, Getr.c_str(), Getr.size());
Steve Naroffeb0646c2008-12-02 15:48:25 +0000759 if (PD->isReadOnly())
760 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000761
Steve Naroffeb0646c2008-12-02 15:48:25 +0000762 // Generate the 'setter' function.
763 std::string Setr;
764 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000765 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000766 // Synthesize an explicit cast to initialize the ivar.
Mike Stump1eb44332009-09-09 15:08:12 +0000767 // FIXME: deal with code generation implications for various property
768 // attributes (copy, retain, nonatomic).
Steve Naroff15f081d2008-12-03 00:56:33 +0000769 // See objc-act.c:objc_synthesize_new_setter() for details.
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000770 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
Steve Narofff4312dc2008-12-11 19:29:16 +0000771 Setr += PD->getNameAsCString();
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000772 Setr += "; }";
Steve Naroffeb0646c2008-12-02 15:48:25 +0000773 InsertText(onePastSemiLoc, Setr.c_str(), Setr.size());
Steve Naroffd40910b2008-12-01 20:33:01 +0000774}
Chris Lattner8a12c272007-10-11 18:38:32 +0000775
Steve Naroffb29b4272008-04-14 22:03:09 +0000776void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000777 // Get the start location and compute the semi location.
778 SourceLocation startLoc = ClassDecl->getLocation();
779 const char *startBuf = SM->getCharacterData(startLoc);
780 const char *semiPtr = strchr(startBuf, ';');
Mike Stump1eb44332009-09-09 15:08:12 +0000781
Chris Lattnerf04da132007-10-24 17:06:59 +0000782 // Translate to typedef's that forward reference structs with the same name
783 // as the class. As a convenience, we include the original declaration
784 // as a comment.
785 std::string typedefString;
786 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000787 typedefString.append(startBuf, semiPtr-startBuf+1);
788 typedefString += "\n";
Chris Lattner67956052009-02-20 18:04:31 +0000789 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
790 I != E; ++I) {
Ted Kremenek321c22f2009-11-18 00:28:11 +0000791 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
Steve Naroff32174822007-11-09 12:50:28 +0000792 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000793 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000794 typedefString += "\n";
795 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000796 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000797 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000798 typedefString += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000799 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000800 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000801 }
Mike Stump1eb44332009-09-09 15:08:12 +0000802
Steve Naroff934f2762007-10-24 22:48:43 +0000803 // Replace the @class with typedefs corresponding to the classes.
Mike Stump1eb44332009-09-09 15:08:12 +0000804 ReplaceText(startLoc, semiPtr-startBuf+1,
Chris Lattneraadaf782008-01-31 19:51:04 +0000805 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000806}
807
Steve Naroffb29b4272008-04-14 22:03:09 +0000808void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000809 SourceLocation LocStart = Method->getLocStart();
810 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000811
Chris Lattner30fc9332009-02-04 01:06:56 +0000812 if (SM->getInstantiationLineNumber(LocEnd) >
813 SM->getInstantiationLineNumber(LocStart)) {
Steve Naroff94ac21e2008-10-21 13:37:27 +0000814 InsertText(LocStart, "#if 0\n", 6);
815 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000816 } else {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000817 InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000818 }
819}
820
Mike Stump1eb44332009-09-09 15:08:12 +0000821void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Steve Naroff6327e0d2009-01-11 01:06:09 +0000822 SourceLocation Loc = prop->getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000823
Steve Naroff6327e0d2009-01-11 01:06:09 +0000824 ReplaceText(Loc, 0, "// ", 3);
Mike Stump1eb44332009-09-09 15:08:12 +0000825
Steve Naroff6327e0d2009-01-11 01:06:09 +0000826 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000827}
828
Steve Naroffb29b4272008-04-14 22:03:09 +0000829void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000830 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000831
Steve Naroff423cb562007-10-30 13:30:57 +0000832 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000833 ReplaceText(LocStart, 0, "// ", 3);
Mike Stump1eb44332009-09-09 15:08:12 +0000834
835 for (ObjCCategoryDecl::instmeth_iterator
836 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000837 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000838 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +0000839 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000840 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000841 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000842 RewriteMethodDeclaration(*I);
843
Steve Naroff423cb562007-10-30 13:30:57 +0000844 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000845 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000846}
847
Steve Naroffb29b4272008-04-14 22:03:09 +0000848void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000849 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Mike Stump1eb44332009-09-09 15:08:12 +0000850
Steve Naroff752d6ef2007-10-30 16:42:30 +0000851 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000852
Steve Naroff752d6ef2007-10-30 16:42:30 +0000853 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000854 ReplaceText(LocStart, 0, "// ", 3);
Mike Stump1eb44332009-09-09 15:08:12 +0000855
856 for (ObjCProtocolDecl::instmeth_iterator
857 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000858 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000859 RewriteMethodDeclaration(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000860 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000861 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000862 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000863 RewriteMethodDeclaration(*I);
864
Steve Naroff752d6ef2007-10-30 16:42:30 +0000865 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000866 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattneraadaf782008-01-31 19:51:04 +0000867 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000868
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000869 // Must comment out @optional/@required
870 const char *startBuf = SM->getCharacterData(LocStart);
871 const char *endBuf = SM->getCharacterData(LocEnd);
872 for (const char *p = startBuf; p < endBuf; p++) {
873 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
874 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000875 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000876 ReplaceText(OptionalLoc, strlen("@optional"),
877 CommentedOptional.c_str(), CommentedOptional.size());
Mike Stump1eb44332009-09-09 15:08:12 +0000878
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000879 }
880 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
881 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000882 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000883 ReplaceText(OptionalLoc, strlen("@required"),
884 CommentedRequired.c_str(), CommentedRequired.size());
Mike Stump1eb44332009-09-09 15:08:12 +0000885
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000886 }
887 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000888}
889
Steve Naroffb29b4272008-04-14 22:03:09 +0000890void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000891 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000892 if (LocStart.isInvalid())
893 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000894 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000895 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000896}
897
Mike Stump1eb44332009-09-09 15:08:12 +0000898void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000899 std::string &ResultStr) {
Steve Naroffced80a82008-10-30 12:09:33 +0000900 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroff76e429d2008-07-16 14:40:40 +0000901 const FunctionType *FPRetType = 0;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000902 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000903 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000904 ResultStr += "id";
Steve Narofff4312dc2008-12-11 19:29:16 +0000905 else if (OMD->getResultType()->isFunctionPointerType() ||
906 OMD->getResultType()->isBlockPointerType()) {
Steve Naroff76e429d2008-07-16 14:40:40 +0000907 // needs special handling, since pointer-to-functions have special
908 // syntax (where a decaration models use).
909 QualType retType = OMD->getResultType();
Steve Narofff4312dc2008-12-11 19:29:16 +0000910 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +0000911 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +0000912 PointeeTy = PT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000913 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +0000914 PointeeTy = BPT->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +0000915 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Steve Narofff4312dc2008-12-11 19:29:16 +0000916 ResultStr += FPRetType->getResultType().getAsString();
917 ResultStr += "(*";
Steve Naroff76e429d2008-07-16 14:40:40 +0000918 }
919 } else
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000920 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000921 ResultStr += " ";
Mike Stump1eb44332009-09-09 15:08:12 +0000922
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000923 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000924 std::string NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +0000925
Douglas Gregorf8d49f62009-01-09 17:18:27 +0000926 if (OMD->isInstanceMethod())
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000927 NameStr += "_I_";
928 else
929 NameStr += "_C_";
Mike Stump1eb44332009-09-09 15:08:12 +0000930
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000931 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000932 NameStr += "_";
Mike Stump1eb44332009-09-09 15:08:12 +0000933
934 if (ObjCCategoryImplDecl *CID =
Steve Naroff3e0a5402009-01-08 19:41:02 +0000935 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000936 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000937 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000938 }
Mike Stump1eb44332009-09-09 15:08:12 +0000939 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +0000940 {
941 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000942 int len = selString.size();
943 for (int i = 0; i < len; i++)
944 if (selString[i] == ':')
945 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000946 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000947 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000948 // Remember this name for metadata emission
949 MethodInternalNames[OMD] = NameStr;
950 ResultStr += NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +0000951
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000952 // Rewrite arguments
953 ResultStr += "(";
Mike Stump1eb44332009-09-09 15:08:12 +0000954
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000955 // invisible arguments
Douglas Gregorf8d49f62009-01-09 17:18:27 +0000956 if (OMD->isInstanceMethod()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000957 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000958 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +0000959 if (!LangOpts.Microsoft) {
960 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
961 ResultStr += "struct ";
962 }
963 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000964 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000965 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000966 }
967 else
Steve Naroff621edce2009-04-29 16:37:50 +0000968 ResultStr += Context->getObjCClassType().getAsString();
Mike Stump1eb44332009-09-09 15:08:12 +0000969
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000970 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000971 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000972 ResultStr += " _cmd";
Mike Stump1eb44332009-09-09 15:08:12 +0000973
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000974 // Method arguments.
Chris Lattner89951a82009-02-20 18:43:26 +0000975 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
976 E = OMD->param_end(); PI != E; ++PI) {
977 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000978 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +0000979 if (PDecl->getType()->isObjCQualifiedIdType()) {
980 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000981 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +0000982 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000983 std::string Name = PDecl->getNameAsString();
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000984 if (isTopLevelBlockPointerType(PDecl->getType())) {
Steve Naroffc8ad87b2008-10-30 14:45:29 +0000985 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Ted Kremenek6217b802009-07-29 21:53:49 +0000986 const BlockPointerType *BPT = PDecl->getType()->getAs<BlockPointerType>();
Douglas Gregord249e1d1f2009-05-29 20:38:28 +0000987 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name,
988 Context->PrintingPolicy);
Steve Naroffc8ad87b2008-10-30 14:45:29 +0000989 } else
Douglas Gregord249e1d1f2009-05-29 20:38:28 +0000990 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroff543409e2008-04-18 21:13:19 +0000991 ResultStr += Name;
992 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000993 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +0000994 if (OMD->isVariadic())
995 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000996 ResultStr += ") ";
Mike Stump1eb44332009-09-09 15:08:12 +0000997
Steve Naroff76e429d2008-07-16 14:40:40 +0000998 if (FPRetType) {
999 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump1eb44332009-09-09 15:08:12 +00001000
Steve Naroff76e429d2008-07-16 14:40:40 +00001001 // Now, emit the argument types (if any).
Douglas Gregor72564e72009-02-26 23:50:07 +00001002 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001003 ResultStr += "(";
1004 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1005 if (i) ResultStr += ", ";
1006 std::string ParamStr = FT->getArgType(i).getAsString();
1007 ResultStr += ParamStr;
1008 }
1009 if (FT->isVariadic()) {
1010 if (FT->getNumArgs()) ResultStr += ", ";
1011 ResultStr += "...";
1012 }
1013 ResultStr += ")";
1014 } else {
1015 ResultStr += "()";
1016 }
1017 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001018}
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001019void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001020 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1021 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump1eb44332009-09-09 15:08:12 +00001022
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001023 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001024 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001025 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001026 InsertText(CID->getLocStart(), "// ", 3);
Mike Stump1eb44332009-09-09 15:08:12 +00001027
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001028 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001029 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1030 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001031 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001032 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001033 ObjCMethodDecl *OMD = *I;
1034 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001035 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001036 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redld3a413d2009-04-26 20:35:05 +00001037
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001038 const char *startBuf = SM->getCharacterData(LocStart);
1039 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +00001040 ReplaceText(LocStart, endBuf-startBuf,
1041 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001042 }
Mike Stump1eb44332009-09-09 15:08:12 +00001043
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001044 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001045 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1046 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001047 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001048 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001049 ObjCMethodDecl *OMD = *I;
1050 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001051 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001052 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001053
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001054 const char *startBuf = SM->getCharacterData(LocStart);
1055 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +00001056 ReplaceText(LocStart, endBuf-startBuf,
Mike Stump1eb44332009-09-09 15:08:12 +00001057 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001058 }
Steve Naroffd40910b2008-12-01 20:33:01 +00001059 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001060 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001061 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001062 I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +00001063 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001064 }
1065
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001066 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001067 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001068 else
Mike Stump1eb44332009-09-09 15:08:12 +00001069 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001070}
1071
Steve Naroffb29b4272008-04-14 22:03:09 +00001072void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001073 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001074 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001075 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001076 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001077 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001078 ResultStr += "\n";
1079 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001080 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001081 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001082 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001083 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001084 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001085 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001086 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001087 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001088 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump1eb44332009-09-09 15:08:12 +00001089
1090 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001091 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff6327e0d2009-01-11 01:06:09 +00001092 RewriteProperty(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001093 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001094 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001095 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001096 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001097 for (ObjCInterfaceDecl::classmeth_iterator
1098 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001099 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001100 RewriteMethodDeclaration(*I);
1101
Steve Naroff2feac5e2007-10-30 03:43:13 +00001102 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +00001103 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +00001104}
1105
Steve Naroffb619d952008-12-09 12:56:34 +00001106Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1107 SourceRange SrcRange) {
Steve Naroffc77a6362008-12-04 16:24:46 +00001108 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1109 // This allows us to reuse all the fun and games in SynthMessageExpr().
1110 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1111 ObjCMessageExpr *MsgExpr;
1112 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1113 llvm::SmallVector<Expr *, 1> ExprVec;
1114 ExprVec.push_back(newStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001115
Steve Naroff8599e7a2008-12-08 16:43:47 +00001116 Stmt *Receiver = PropRefExpr->getBase();
1117 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1118 if (PRE && PropGetters[PRE]) {
1119 // This allows us to handle chain/nested property getters.
1120 Receiver = PropGetters[PRE];
1121 }
Mike Stump1eb44332009-09-09 15:08:12 +00001122 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
1123 PDecl->getSetterName(), PDecl->getType(),
1124 PDecl->getSetterMethodDecl(),
1125 SourceLocation(), SourceLocation(),
Steve Naroffc77a6362008-12-04 16:24:46 +00001126 &ExprVec[0], 1);
1127 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001128
Steve Naroffc77a6362008-12-04 16:24:46 +00001129 // Now do the actual rewrite.
Steve Naroffb619d952008-12-09 12:56:34 +00001130 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffe58ee0c2008-12-10 14:53:27 +00001131 //delete BinOp;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001132 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1133 // to things that stay around.
1134 Context->Deallocate(MsgExpr);
Steve Naroffc77a6362008-12-04 16:24:46 +00001135 return ReplacingStmt;
Steve Naroff15f081d2008-12-03 00:56:33 +00001136}
1137
Steve Naroffc77a6362008-12-04 16:24:46 +00001138Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Naroff15f081d2008-12-03 00:56:33 +00001139 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1140 // This allows us to reuse all the fun and games in SynthMessageExpr().
1141 ObjCMessageExpr *MsgExpr;
1142 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
Mike Stump1eb44332009-09-09 15:08:12 +00001143
Steve Naroff8599e7a2008-12-08 16:43:47 +00001144 Stmt *Receiver = PropRefExpr->getBase();
Mike Stump1eb44332009-09-09 15:08:12 +00001145
Steve Naroff8599e7a2008-12-08 16:43:47 +00001146 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1147 if (PRE && PropGetters[PRE]) {
1148 // This allows us to handle chain/nested property getters.
1149 Receiver = PropGetters[PRE];
1150 }
Mike Stump1eb44332009-09-09 15:08:12 +00001151 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
1152 PDecl->getGetterName(), PDecl->getType(),
1153 PDecl->getGetterMethodDecl(),
1154 SourceLocation(), SourceLocation(),
Steve Naroff15f081d2008-12-03 00:56:33 +00001155 0, 0);
1156
Steve Naroff4c3580e2008-12-04 23:50:32 +00001157 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001158
1159 if (!PropParentMap)
1160 PropParentMap = new ParentMap(CurrentBody);
1161
1162 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1163 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1164 // We stash away the ReplacingStmt since actually doing the
1165 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1166 PropGetters[PropRefExpr] = ReplacingStmt;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001167 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1168 // to things that stay around.
1169 Context->Deallocate(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001170 return PropRefExpr; // return the original...
1171 } else {
1172 ReplaceStmt(PropRefExpr, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001173 // delete PropRefExpr; elsewhere...
Ted Kremenek8189cde2009-02-07 01:47:29 +00001174 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1175 // to things that stay around.
1176 Context->Deallocate(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001177 return ReplacingStmt;
1178 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001179}
1180
Mike Stump1eb44332009-09-09 15:08:12 +00001181Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001182 SourceLocation OrigStart) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001183 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff54055232008-10-27 17:20:55 +00001184 if (CurMethodDef) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001185 if (const PointerType *pType = IV->getBase()->getType()->getAs<PointerType>()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001186 ObjCInterfaceType *iFaceDecl =
1187 dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Narofff0757612008-05-08 17:52:16 +00001188 // lookup which class implements the instance variable.
1189 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001190 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001191 clsDeclared);
Steve Narofff0757612008-05-08 17:52:16 +00001192 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001193
Steve Narofff0757612008-05-08 17:52:16 +00001194 // Synthesize an explicit cast to gain access to the ivar.
1195 std::string RecName = clsDeclared->getIdentifier()->getName();
1196 RecName += "_IMPL";
1197 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001198 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001199 SourceLocation(), II);
Steve Narofff0757612008-05-08 17:52:16 +00001200 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1201 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Mike Stump1eb44332009-09-09 15:08:12 +00001202 CastExpr *castExpr = new (Context) CStyleCastExpr(castT,
Anders Carlssoncdef2b72009-07-31 00:48:10 +00001203 CastExpr::CK_Unknown,
1204 IV->getBase(),
1205 castT,SourceLocation(),
1206 SourceLocation());
Steve Narofff0757612008-05-08 17:52:16 +00001207 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001208 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1209 IV->getBase()->getLocEnd(),
1210 castExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001211 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +00001212 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001213 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1214 IV->getLocation(),
1215 D->getType());
Steve Narofff0757612008-05-08 17:52:16 +00001216 ReplaceStmt(IV, ME);
Steve Naroff4c3580e2008-12-04 23:50:32 +00001217 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Narofff0757612008-05-08 17:52:16 +00001218 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001219 }
Mike Stump1eb44332009-09-09 15:08:12 +00001220
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001221 ReplaceStmt(IV->getBase(), PE);
1222 // Cannot delete IV->getBase(), since PE points to it.
1223 // Replace the old base with the cast. This is important when doing
1224 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001225 IV->setBase(PE);
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001226 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001227 }
Steve Naroff84472a82008-04-18 21:55:08 +00001228 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001229 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump1eb44332009-09-09 15:08:12 +00001230
Steve Naroff9f525972008-05-06 23:20:07 +00001231 // Explicit ivar refs need to have a cast inserted.
1232 // FIXME: consider sharing some of this code with the code above.
Ted Kremenek6217b802009-07-29 21:53:49 +00001233 if (const PointerType *pType = IV->getBase()->getType()->getAs<PointerType>()) {
Steve Narofff0757612008-05-08 17:52:16 +00001234 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001235 // lookup which class implements the instance variable.
1236 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001237 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001238 clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001239 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001240
Steve Naroff9f525972008-05-06 23:20:07 +00001241 // Synthesize an explicit cast to gain access to the ivar.
1242 std::string RecName = clsDeclared->getIdentifier()->getName();
1243 RecName += "_IMPL";
1244 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001245 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001246 SourceLocation(), II);
Steve Naroff9f525972008-05-06 23:20:07 +00001247 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1248 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Mike Stump1eb44332009-09-09 15:08:12 +00001249 CastExpr *castExpr = new (Context) CStyleCastExpr(castT,
Anders Carlssoncdef2b72009-07-31 00:48:10 +00001250 CastExpr::CK_Unknown,
1251 IV->getBase(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00001252 castT, SourceLocation(),
1253 SourceLocation());
Steve Naroff9f525972008-05-06 23:20:07 +00001254 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001255 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner8d366162008-05-28 16:38:23 +00001256 IV->getBase()->getLocEnd(), castExpr);
Steve Naroff9f525972008-05-06 23:20:07 +00001257 ReplaceStmt(IV->getBase(), PE);
1258 // Cannot delete IV->getBase(), since PE points to it.
1259 // Replace the old base with the cast. This is important when doing
1260 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001261 IV->setBase(PE);
Steve Naroff9f525972008-05-06 23:20:07 +00001262 return IV;
1263 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001264 }
Steve Naroff84472a82008-04-18 21:55:08 +00001265 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +00001266}
1267
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001268/// SynthCountByEnumWithState - To print:
1269/// ((unsigned int (*)
1270/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001271/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001272/// sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001273/// "countByEnumeratingWithState:objects:count:"),
1274/// &enumState,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001275/// (id *)items, (unsigned int)16)
1276///
Steve Naroffb29b4272008-04-14 22:03:09 +00001277void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001278 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1279 "id *, unsigned int))(void *)objc_msgSend)";
1280 buf += "\n\t\t";
1281 buf += "((id)l_collection,\n\t\t";
1282 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1283 buf += "\n\t\t";
1284 buf += "&enumState, "
1285 "(id *)items, (unsigned int)16)";
1286}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001287
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001288/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1289/// statement to exit to its outer synthesized loop.
1290///
Steve Naroffb29b4272008-04-14 22:03:09 +00001291Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001292 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1293 return S;
1294 // replace break with goto __break_label
1295 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001296
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001297 SourceLocation startLoc = S->getLocStart();
1298 buf = "goto __break_label_";
1299 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001300 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001301
1302 return 0;
1303}
1304
1305/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1306/// statement to continue with its inner synthesized loop.
1307///
Steve Naroffb29b4272008-04-14 22:03:09 +00001308Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001309 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1310 return S;
1311 // replace continue with goto __continue_label
1312 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001313
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001314 SourceLocation startLoc = S->getLocStart();
1315 buf = "goto __continue_label_";
1316 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001317 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001318
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001319 return 0;
1320}
1321
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001322/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001323/// It rewrites:
1324/// for ( type elem in collection) { stmts; }
Mike Stump1eb44332009-09-09 15:08:12 +00001325
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001326/// Into:
1327/// {
Mike Stump1eb44332009-09-09 15:08:12 +00001328/// type elem;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001329/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001330/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001331/// id l_collection = (id)collection;
Mike Stump1eb44332009-09-09 15:08:12 +00001332/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001333/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001334/// if (limit) {
1335/// unsigned long startMutations = *enumState.mutationsPtr;
1336/// do {
1337/// unsigned long counter = 0;
1338/// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001339/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001340/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001341/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001342/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001343/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001344/// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001345/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001346/// objects:items count:16]);
1347/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001348/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001349/// }
1350/// else
1351/// elem = nil;
1352/// }
1353///
Steve Naroffb29b4272008-04-14 22:03:09 +00001354Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001355 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001356 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001357 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001358 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump1eb44332009-09-09 15:08:12 +00001359 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001360 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001361
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001362 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001363 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001364 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001365 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001366 std::string buf;
1367 buf = "\n{\n\t";
1368 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1369 // type elem;
Chris Lattner7e24e822009-03-28 06:33:19 +00001370 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001371 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001372 if (ElementType->isObjCQualifiedIdType() ||
1373 ElementType->isObjCQualifiedInterfaceType())
1374 // Simply use 'id' for all qualified types.
1375 elementTypeAsString = "id";
1376 else
1377 elementTypeAsString = ElementType.getAsString();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001378 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001379 buf += " ";
Chris Lattner8ec03f52008-11-24 03:54:41 +00001380 elementName = D->getNameAsCString();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001381 buf += elementName;
1382 buf += ";\n\t";
1383 }
Chris Lattner06767512008-04-08 05:52:18 +00001384 else {
1385 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner8ec03f52008-11-24 03:54:41 +00001386 elementName = DR->getDecl()->getNameAsCString();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001387 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1388 if (VD->getType()->isObjCQualifiedIdType() ||
1389 VD->getType()->isObjCQualifiedInterfaceType())
1390 // Simply use 'id' for all qualified types.
1391 elementTypeAsString = "id";
1392 else
1393 elementTypeAsString = VD->getType().getAsString();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001394 }
Mike Stump1eb44332009-09-09 15:08:12 +00001395
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001396 // struct __objcFastEnumerationState enumState = { 0 };
1397 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1398 // id items[16];
1399 buf += "id items[16];\n\t";
1400 // id l_collection = (id)
1401 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001402 // Find start location of 'collection' the hard way!
1403 const char *startCollectionBuf = startBuf;
1404 startCollectionBuf += 3; // skip 'for'
1405 startCollectionBuf = strchr(startCollectionBuf, '(');
1406 startCollectionBuf++; // skip '('
1407 // find 'in' and skip it.
1408 while (*startCollectionBuf != ' ' ||
1409 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1410 (*(startCollectionBuf+3) != ' ' &&
1411 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1412 startCollectionBuf++;
1413 startCollectionBuf += 3;
Mike Stump1eb44332009-09-09 15:08:12 +00001414
1415 // Replace: "for (type element in" with string constructed thus far.
Chris Lattneraadaf782008-01-31 19:51:04 +00001416 ReplaceText(startLoc, startCollectionBuf - startBuf,
1417 buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001418 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001419 SourceLocation rightParenLoc = S->getRParenLoc();
1420 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1421 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001422 buf = ";\n\t";
Mike Stump1eb44332009-09-09 15:08:12 +00001423
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001424 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1425 // objects:items count:16];
1426 // which is synthesized into:
Mike Stump1eb44332009-09-09 15:08:12 +00001427 // unsigned int limit =
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001428 // ((unsigned int (*)
1429 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001430 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001431 // sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001432 // "countByEnumeratingWithState:objects:count:"),
1433 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001434 // (id *)items, (unsigned int)16);
1435 buf += "unsigned long limit =\n\t\t";
1436 SynthCountByEnumWithState(buf);
1437 buf += ";\n\t";
1438 /// if (limit) {
1439 /// unsigned long startMutations = *enumState.mutationsPtr;
1440 /// do {
1441 /// unsigned long counter = 0;
1442 /// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001443 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001444 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001445 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001446 buf += "if (limit) {\n\t";
1447 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1448 buf += "do {\n\t\t";
1449 buf += "unsigned long counter = 0;\n\t\t";
1450 buf += "do {\n\t\t\t";
1451 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1452 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1453 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001454 buf += " = (";
1455 buf += elementTypeAsString;
1456 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001457 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattneraadaf782008-01-31 19:51:04 +00001458 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001459
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001460 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001461 /// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001462 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001463 /// objects:items count:16]);
1464 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001465 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001466 /// }
1467 /// else
1468 /// elem = nil;
1469 /// }
Mike Stump1eb44332009-09-09 15:08:12 +00001470 ///
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001471 buf = ";\n\t";
1472 buf += "__continue_label_";
1473 buf += utostr(ObjCBcLabelNo.back());
1474 buf += ": ;";
1475 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001476 buf += "} while (counter < limit);\n\t";
1477 buf += "} while (limit = ";
1478 SynthCountByEnumWithState(buf);
1479 buf += ");\n\t";
1480 buf += elementName;
Steve Naroff5605fdf2008-12-17 14:24:39 +00001481 buf += " = ((id)0);\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001482 buf += "__break_label_";
1483 buf += utostr(ObjCBcLabelNo.back());
1484 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001485 buf += "}\n\t";
1486 buf += "else\n\t\t";
1487 buf += elementName;
Steve Naroff5605fdf2008-12-17 14:24:39 +00001488 buf += " = ((id)0);\n";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001489 buf += "}\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001490
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001491 // Insert all these *after* the statement body.
Sebastian Redld3a413d2009-04-26 20:35:05 +00001492 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Naroff600e4e82008-07-21 18:26:02 +00001493 if (isa<CompoundStmt>(S->getBody())) {
1494 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1495 InsertText(endBodyLoc, buf.c_str(), buf.size());
1496 } else {
1497 /* Need to treat single statements specially. For example:
1498 *
1499 * for (A *a in b) if (stuff()) break;
1500 * for (A *a in b) xxxyy;
1501 *
1502 * The following code simply scans ahead to the semi to find the actual end.
1503 */
1504 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1505 const char *semiBuf = strchr(stmtBuf, ';');
1506 assert(semiBuf && "Can't find ';'");
1507 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1508 InsertText(endBodyLoc, buf.c_str(), buf.size());
1509 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001510 Stmts.pop_back();
1511 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001512 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001513}
1514
Mike Stump1eb44332009-09-09 15:08:12 +00001515/// RewriteObjCSynchronizedStmt -
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001516/// This routine rewrites @synchronized(expr) stmt;
1517/// into:
1518/// objc_sync_enter(expr);
1519/// @try stmt @finally { objc_sync_exit(expr); }
1520///
Steve Naroffb29b4272008-04-14 22:03:09 +00001521Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001522 // Get the start location and compute the semi location.
1523 SourceLocation startLoc = S->getLocStart();
1524 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001525
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001526 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump1eb44332009-09-09 15:08:12 +00001527
1528 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001529 buf = "objc_sync_enter((id)";
1530 const char *lparenBuf = startBuf;
1531 while (*lparenBuf != '(') lparenBuf++;
1532 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001533 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1534 // the sync expression is typically a message expression that's already
Steve Naroffc7089f12008-08-19 13:04:19 +00001535 // been rewritten! (which implies the SourceLocation's are invalid).
1536 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001537 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001538 while (*endBuf != ')') endBuf--;
1539 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001540 buf = ");\n";
1541 // declare a new scope with two variables, _stack and _rethrow.
1542 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1543 buf += "int buf[18/*32-bit i386*/];\n";
1544 buf += "char *pointers[4];} _stack;\n";
1545 buf += "id volatile _rethrow = 0;\n";
1546 buf += "objc_exception_try_enter(&_stack);\n";
1547 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00001548 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001549 startLoc = S->getSynchBody()->getLocEnd();
1550 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001551
Steve Naroffc7089f12008-08-19 13:04:19 +00001552 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001553 SourceLocation lastCurlyLoc = startLoc;
1554 buf = "}\nelse {\n";
1555 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroff621edce2009-04-29 16:37:50 +00001556 buf += "}\n";
1557 buf += "{ /* implicit finally clause */\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001558 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb85e77a2009-12-05 21:43:12 +00001559
1560 std::string syncBuf;
1561 syncBuf += " objc_sync_exit(";
Mike Stump1eb44332009-09-09 15:08:12 +00001562 Expr *syncExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssoncdef2b72009-07-31 00:48:10 +00001563 CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00001564 S->getSynchExpr(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00001565 Context->getObjCIdType(),
1566 SourceLocation(),
1567 SourceLocation());
Ted Kremeneka95d3752008-09-13 05:16:45 +00001568 std::string syncExprBufS;
1569 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00001570 syncExpr->printPretty(syncExprBuf, *Context, 0,
1571 PrintingPolicy(LangOpts));
Steve Naroffb85e77a2009-12-05 21:43:12 +00001572 syncBuf += syncExprBuf.str();
1573 syncBuf += ");";
1574
1575 buf += syncBuf;
1576 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001577 buf += "}\n";
1578 buf += "}";
Mike Stump1eb44332009-09-09 15:08:12 +00001579
Chris Lattneraadaf782008-01-31 19:51:04 +00001580 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffb85e77a2009-12-05 21:43:12 +00001581
1582 bool hasReturns = false;
1583 HasReturnStmts(S->getSynchBody(), hasReturns);
1584 if (hasReturns)
1585 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1586
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001587 return 0;
1588}
1589
Steve Naroffb85e77a2009-12-05 21:43:12 +00001590void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1591{
Steve Naroff8c565152008-12-05 17:03:39 +00001592 // Perform a bottom up traversal of all children.
1593 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1594 CI != E; ++CI)
1595 if (*CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001596 WarnAboutReturnGotoStmts(*CI);
Steve Naroff8c565152008-12-05 17:03:39 +00001597
Steve Naroffb85e77a2009-12-05 21:43:12 +00001598 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001599 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff8c565152008-12-05 17:03:39 +00001600 TryFinallyContainsReturnDiag);
1601 }
1602 return;
1603}
1604
Steve Naroffb85e77a2009-12-05 21:43:12 +00001605void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1606{
1607 // Perform a bottom up traversal of all children.
1608 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1609 CI != E; ++CI)
1610 if (*CI)
1611 HasReturnStmts(*CI, hasReturns);
1612
1613 if (isa<ReturnStmt>(S))
1614 hasReturns = true;
1615 return;
1616}
1617
1618void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1619 // Perform a bottom up traversal of all children.
1620 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1621 CI != E; ++CI)
1622 if (*CI) {
1623 RewriteTryReturnStmts(*CI);
1624 }
1625 if (isa<ReturnStmt>(S)) {
1626 SourceLocation startLoc = S->getLocStart();
1627 const char *startBuf = SM->getCharacterData(startLoc);
1628
1629 const char *semiBuf = strchr(startBuf, ';');
1630 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1631 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1632
1633 std::string buf;
1634 buf = "{ objc_exception_try_exit(&_stack); return";
1635
1636 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
1637 InsertText(onePastSemiLoc, "}", 1);
1638 }
1639 return;
1640}
1641
1642void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1643 // Perform a bottom up traversal of all children.
1644 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1645 CI != E; ++CI)
1646 if (*CI) {
1647 RewriteSyncReturnStmts(*CI, syncExitBuf);
1648 }
1649 if (isa<ReturnStmt>(S)) {
1650 SourceLocation startLoc = S->getLocStart();
1651 const char *startBuf = SM->getCharacterData(startLoc);
1652
1653 const char *semiBuf = strchr(startBuf, ';');
1654 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1655 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1656
1657 std::string buf;
1658 buf = "{ objc_exception_try_exit(&_stack);";
1659 buf += syncExitBuf;
1660 buf += " return";
1661
1662 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
1663 InsertText(onePastSemiLoc, "}", 1);
1664 }
1665 return;
1666}
1667
Steve Naroffb29b4272008-04-14 22:03:09 +00001668Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001669 // Get the start location and compute the semi location.
1670 SourceLocation startLoc = S->getLocStart();
1671 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001672
Steve Naroff75730982007-11-07 04:08:17 +00001673 assert((*startBuf == '@') && "bogus @try location");
1674
1675 std::string buf;
1676 // declare a new scope with two variables, _stack and _rethrow.
1677 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1678 buf += "int buf[18/*32-bit i386*/];\n";
1679 buf += "char *pointers[4];} _stack;\n";
1680 buf += "id volatile _rethrow = 0;\n";
1681 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001682 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001683
Chris Lattneraadaf782008-01-31 19:51:04 +00001684 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001685
Steve Naroff75730982007-11-07 04:08:17 +00001686 startLoc = S->getTryBody()->getLocEnd();
1687 startBuf = SM->getCharacterData(startLoc);
1688
1689 assert((*startBuf == '}') && "bogus @try block");
Mike Stump1eb44332009-09-09 15:08:12 +00001690
Steve Naroff75730982007-11-07 04:08:17 +00001691 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffc9ba1722008-07-16 15:31:30 +00001692 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1693 if (catchList) {
1694 startLoc = startLoc.getFileLocWithOffset(1);
1695 buf = " /* @catch begin */ else {\n";
1696 buf += " id _caught = objc_exception_extract(&_stack);\n";
1697 buf += " objc_exception_try_enter (&_stack);\n";
1698 buf += " if (_setjmp(_stack.buf))\n";
1699 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1700 buf += " else { /* @catch continue */";
Mike Stump1eb44332009-09-09 15:08:12 +00001701
Steve Naroffc9ba1722008-07-16 15:31:30 +00001702 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001703 } else { /* no catch list */
1704 buf = "}\nelse {\n";
1705 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1706 buf += "}";
1707 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffc9ba1722008-07-16 15:31:30 +00001708 }
Steve Naroff75730982007-11-07 04:08:17 +00001709 bool sawIdTypedCatch = false;
1710 Stmt *lastCatchBody = 0;
Steve Naroff75730982007-11-07 04:08:17 +00001711 while (catchList) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00001712 ParmVarDecl *catchDecl = catchList->getCatchParamDecl();
Steve Naroff75730982007-11-07 04:08:17 +00001713
Mike Stump1eb44332009-09-09 15:08:12 +00001714 if (catchList == S->getCatchStmts())
Steve Naroff75730982007-11-07 04:08:17 +00001715 buf = "if ("; // we are generating code for the first catch clause
1716 else
1717 buf = "else if (";
1718 startLoc = catchList->getLocStart();
1719 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001720
Steve Naroff75730982007-11-07 04:08:17 +00001721 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump1eb44332009-09-09 15:08:12 +00001722
Steve Naroff75730982007-11-07 04:08:17 +00001723 const char *lParenLoc = strchr(startBuf, '(');
1724
Steve Naroffbe4b3332008-02-01 22:08:12 +00001725 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001726 // Now rewrite the body...
1727 lastCatchBody = catchList->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001728 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1729 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner06767512008-04-08 05:52:18 +00001730 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1731 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001732 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001733
Steve Naroffe12e6922008-02-01 20:02:07 +00001734 buf += "1) { id _tmp = _caught;";
Daniel Dunbard7407dc2009-08-19 19:10:30 +00001735 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff7ba138a2009-03-03 19:52:17 +00001736 } else if (catchDecl) {
1737 QualType t = catchDecl->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001738 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001739 buf += "1) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001740 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001741 sawIdTypedCatch = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001742 } else if (const PointerType *pType = t->getAs<PointerType>()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001743 ObjCInterfaceType *cls; // Should be a pointer to a class.
Mike Stump1eb44332009-09-09 15:08:12 +00001744
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001745 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001746 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001747 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001748 buf += cls->getDecl()->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001749 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001750 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001751 }
1752 }
1753 // Now rewrite the body...
1754 lastCatchBody = catchList->getCatchBody();
1755 SourceLocation rParenLoc = catchList->getRParenLoc();
1756 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1757 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1758 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1759 assert((*rParenBuf == ')') && "bogus @catch paren location");
1760 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001761
Steve Naroff75730982007-11-07 04:08:17 +00001762 buf = " = _caught;";
Mike Stump1eb44332009-09-09 15:08:12 +00001763 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroff75730982007-11-07 04:08:17 +00001764 // declares the @catch parameter).
Chris Lattneraadaf782008-01-31 19:51:04 +00001765 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff7ba138a2009-03-03 19:52:17 +00001766 } else {
Steve Naroff75730982007-11-07 04:08:17 +00001767 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001768 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001769 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001770 catchList = catchList->getNextCatchStmt();
1771 }
1772 // Complete the catch list...
1773 if (lastCatchBody) {
1774 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001775 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1776 "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001777
Steve Naroff378f47a2008-09-11 15:29:03 +00001778 // Insert the last (implicit) else clause *before* the right curly brace.
1779 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1780 buf = "} /* last catch end */\n";
1781 buf += "else {\n";
1782 buf += " _rethrow = _caught;\n";
1783 buf += " objc_exception_try_exit(&_stack);\n";
1784 buf += "} } /* @catch end */\n";
1785 if (!S->getFinallyStmt())
1786 buf += "}\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001787 InsertText(bodyLoc, buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001788
Steve Naroff75730982007-11-07 04:08:17 +00001789 // Set lastCurlyLoc
1790 lastCurlyLoc = lastCatchBody->getLocEnd();
1791 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001792 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001793 startLoc = finalStmt->getLocStart();
1794 startBuf = SM->getCharacterData(startLoc);
1795 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump1eb44332009-09-09 15:08:12 +00001796
Steve Naroff75730982007-11-07 04:08:17 +00001797 buf = "/* @finally */";
Chris Lattneraadaf782008-01-31 19:51:04 +00001798 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001799
Steve Naroff75730982007-11-07 04:08:17 +00001800 Stmt *body = finalStmt->getFinallyBody();
1801 SourceLocation startLoc = body->getLocStart();
1802 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001803 assert(*SM->getCharacterData(startLoc) == '{' &&
1804 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001805 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner06767512008-04-08 05:52:18 +00001806 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001807
Steve Naroff75730982007-11-07 04:08:17 +00001808 startLoc = startLoc.getFileLocWithOffset(1);
1809 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001810 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001811 endLoc = endLoc.getFileLocWithOffset(-1);
1812 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001813 InsertText(endLoc, buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001814
Steve Naroff75730982007-11-07 04:08:17 +00001815 // Set lastCurlyLoc
1816 lastCurlyLoc = body->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00001817
Steve Naroff8c565152008-12-05 17:03:39 +00001818 // Now check for any return/continue/go statements within the @try.
Steve Naroffb85e77a2009-12-05 21:43:12 +00001819 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00001820 } else { /* no finally clause - make sure we synthesize an implicit one */
1821 buf = "{ /* implicit finally clause */\n";
1822 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1823 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1824 buf += "}";
1825 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffb85e77a2009-12-05 21:43:12 +00001826
1827 // Now check for any return/continue/go statements within the @try.
1828 // The implicit finally clause won't called if the @try contains any
1829 // jump statements.
1830 bool hasReturns = false;
1831 HasReturnStmts(S->getTryBody(), hasReturns);
1832 if (hasReturns)
1833 RewriteTryReturnStmts(S->getTryBody());
Steve Naroff75730982007-11-07 04:08:17 +00001834 }
1835 // Now emit the final closing curly brace...
1836 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1837 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001838 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001839 return 0;
1840}
1841
Steve Naroffb29b4272008-04-14 22:03:09 +00001842Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001843 return 0;
1844}
1845
Steve Naroffb29b4272008-04-14 22:03:09 +00001846Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001847 return 0;
1848}
1849
Mike Stump1eb44332009-09-09 15:08:12 +00001850// This can't be done with ReplaceStmt(S, ThrowExpr), since
1851// the throw expression is typically a message expression that's already
Steve Naroff2bd03922007-11-07 15:32:26 +00001852// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001853Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001854 // Get the start location and compute the semi location.
1855 SourceLocation startLoc = S->getLocStart();
1856 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001857
Steve Naroff2bd03922007-11-07 15:32:26 +00001858 assert((*startBuf == '@') && "bogus @throw location");
1859
1860 std::string buf;
1861 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001862 if (S->getThrowExpr())
1863 buf = "objc_exception_throw(";
1864 else // add an implicit argument
1865 buf = "objc_exception_throw(_caught";
Mike Stump1eb44332009-09-09 15:08:12 +00001866
Steve Naroff4ba0acb2008-07-25 15:41:30 +00001867 // handle "@ throw" correctly.
1868 const char *wBuf = strchr(startBuf, 'w');
1869 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1870 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001871
Steve Naroff2bd03922007-11-07 15:32:26 +00001872 const char *semiBuf = strchr(startBuf, ';');
1873 assert((*semiBuf == ';') && "@throw: can't find ';'");
1874 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1875 buf = ");";
Chris Lattneraadaf782008-01-31 19:51:04 +00001876 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001877 return 0;
1878}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001879
Steve Naroffb29b4272008-04-14 22:03:09 +00001880Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001881 // Create a new string expression.
1882 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001883 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001884 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattner2085fd62009-02-18 06:40:38 +00001885 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
1886 StrEncoding.length(), false,StrType,
1887 SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001888 ReplaceStmt(Exp, Replacement);
Mike Stump1eb44332009-09-09 15:08:12 +00001889
Chris Lattner07506182007-11-30 22:53:43 +00001890 // Replace this subexpr in the parent.
Steve Naroff4c3580e2008-12-04 23:50:32 +00001891 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00001892 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001893}
1894
Steve Naroffb29b4272008-04-14 22:03:09 +00001895Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff1a937642008-12-22 22:16:07 +00001896 if (!SelGetUidFunctionDecl)
1897 SynthSelGetUidFunctionDecl();
Steve Naroffb42f8412007-11-05 14:50:49 +00001898 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1899 // Create a call to sel_registerName("selName").
1900 llvm::SmallVector<Expr*, 8> SelExprs;
1901 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001902 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00001903 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00001904 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00001905 false, argType, SourceLocation()));
Steve Naroffb42f8412007-11-05 14:50:49 +00001906 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1907 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001908 ReplaceStmt(Exp, SelExp);
Steve Naroff4c3580e2008-12-04 23:50:32 +00001909 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00001910 return SelExp;
1911}
1912
Steve Naroffb29b4272008-04-14 22:03:09 +00001913CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff934f2762007-10-24 22:48:43 +00001914 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001915 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001916 QualType msgSendType = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001917
Steve Naroffebf2b562007-10-23 23:50:29 +00001918 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001919 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001920
Steve Naroffebf2b562007-10-23 23:50:29 +00001921 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001922 QualType pToFunc = Context->getPointerType(msgSendType);
Mike Stump1eb44332009-09-09 15:08:12 +00001923 ImplicitCastExpr *ICE = new (Context) ImplicitCastExpr(pToFunc,
Anders Carlssoncdef2b72009-07-31 00:48:10 +00001924 CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00001925 DRE,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001926 /*isLvalue=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00001927
John McCall183700f2009-09-21 23:43:11 +00001928 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001929
Ted Kremenek668bf912009-02-09 20:51:47 +00001930 return new (Context) CallExpr(*Context, ICE, args, nargs, FT->getResultType(),
1931 SourceLocation());
Steve Naroff934f2762007-10-24 22:48:43 +00001932}
1933
Steve Naroffd5255f52007-11-01 13:24:47 +00001934static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1935 const char *&startRef, const char *&endRef) {
1936 while (startBuf < endBuf) {
1937 if (*startBuf == '<')
1938 startRef = startBuf; // mark the start.
1939 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001940 if (startRef && *startRef == '<') {
1941 endRef = startBuf; // mark the end.
1942 return true;
1943 }
1944 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001945 }
1946 startBuf++;
1947 }
1948 return false;
1949}
1950
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001951static void scanToNextArgument(const char *&argRef) {
1952 int angle = 0;
1953 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1954 if (*argRef == '<')
1955 angle++;
1956 else if (*argRef == '>')
1957 angle--;
1958 argRef++;
1959 }
1960 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1961}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001962
Steve Naroffb29b4272008-04-14 22:03:09 +00001963bool RewriteObjC::needToScanForQualifiers(QualType T) {
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001964 return T->isObjCQualifiedIdType() || T->isObjCQualifiedInterfaceType();
Steve Naroffd5255f52007-11-01 13:24:47 +00001965}
1966
Steve Naroff4f95b752008-07-29 18:15:38 +00001967void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1968 QualType Type = E->getType();
1969 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00001970 SourceLocation Loc, EndLoc;
Mike Stump1eb44332009-09-09 15:08:12 +00001971
Steve Naroffcda658e2008-11-19 21:15:47 +00001972 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
1973 Loc = ECE->getLParenLoc();
1974 EndLoc = ECE->getRParenLoc();
1975 } else {
1976 Loc = E->getLocStart();
1977 EndLoc = E->getLocEnd();
1978 }
1979 // This will defend against trying to rewrite synthesized expressions.
1980 if (Loc.isInvalid() || EndLoc.isInvalid())
1981 return;
1982
Steve Naroff4f95b752008-07-29 18:15:38 +00001983 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00001984 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00001985 const char *startRef = 0, *endRef = 0;
1986 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1987 // Get the locations of the startRef, endRef.
1988 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1989 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1990 // Comment out the protocol references.
1991 InsertText(LessLoc, "/*", 2);
1992 InsertText(GreaterLoc, "*/", 2);
1993 }
1994 }
1995}
1996
Steve Naroffb29b4272008-04-14 22:03:09 +00001997void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001998 SourceLocation Loc;
1999 QualType Type;
Douglas Gregor72564e72009-02-26 23:50:07 +00002000 const FunctionProtoType *proto = 0;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002001 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2002 Loc = VD->getLocation();
2003 Type = VD->getType();
2004 }
2005 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2006 Loc = FD->getLocation();
2007 // Check for ObjC 'id' and class types that have been adorned with protocol
2008 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall183700f2009-09-21 23:43:11 +00002009 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002010 assert(funcType && "missing function type");
Douglas Gregor72564e72009-02-26 23:50:07 +00002011 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002012 if (!proto)
2013 return;
2014 Type = proto->getResultType();
2015 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00002016 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2017 Loc = FD->getLocation();
2018 Type = FD->getType();
2019 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002020 else
2021 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002022
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002023 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00002024 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002025
Steve Naroffd5255f52007-11-01 13:24:47 +00002026 const char *endBuf = SM->getCharacterData(Loc);
2027 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00002028 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00002029 startBuf--; // scan backward (from the decl location) for return type.
2030 const char *startRef = 0, *endRef = 0;
2031 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2032 // Get the locations of the startRef, endRef.
2033 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2034 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2035 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002036 InsertText(LessLoc, "/*", 2);
2037 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00002038 }
2039 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002040 if (!proto)
2041 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00002042 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002043 const char *startBuf = SM->getCharacterData(Loc);
2044 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00002045 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2046 if (needToScanForQualifiers(proto->getArgType(i))) {
2047 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002048
Steve Naroffd5255f52007-11-01 13:24:47 +00002049 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002050 // scan forward (from the decl location) for argument types.
2051 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00002052 const char *startRef = 0, *endRef = 0;
2053 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2054 // Get the locations of the startRef, endRef.
Mike Stump1eb44332009-09-09 15:08:12 +00002055 SourceLocation LessLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002056 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002057 SourceLocation GreaterLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002058 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002059 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002060 InsertText(LessLoc, "/*", 2);
2061 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00002062 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002063 startBuf = ++endBuf;
2064 }
2065 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00002066 // If the function name is derived from a macro expansion, then the
2067 // argument buffer will not follow the name. Need to speak with Chris.
2068 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002069 startBuf++; // scan forward (from the decl location) for argument types.
2070 startBuf++;
2071 }
Steve Naroffd5255f52007-11-01 13:24:47 +00002072 }
Steve Naroff9165ad32007-10-31 04:38:33 +00002073}
2074
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002075// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00002076void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002077 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2078 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002079 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002080 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002081 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002082 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002083 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002084 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002085 SelGetUidIdent, getFuncType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002086 FunctionDecl::Extern, false);
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002087}
2088
Steve Naroffb29b4272008-04-14 22:03:09 +00002089void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002090 // declared in <objc/objc.h>
Douglas Gregor51efe562009-01-09 01:47:02 +00002091 if (FD->getIdentifier() &&
2092 strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002093 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00002094 return;
2095 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002096 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00002097}
2098
Steve Naroffc0a123c2008-03-11 17:37:02 +00002099// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00002100void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002101 if (SuperContructorFunctionDecl)
2102 return;
Steve Naroff46a98a72008-12-23 20:11:22 +00002103 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroffc0a123c2008-03-11 17:37:02 +00002104 llvm::SmallVector<QualType, 16> ArgTys;
2105 QualType argT = Context->getObjCIdType();
2106 assert(!argT.isNull() && "Can't find 'id' type");
2107 ArgTys.push_back(argT);
2108 ArgTys.push_back(argT);
2109 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2110 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002111 false, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002112 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002113 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002114 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002115 FunctionDecl::Extern, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002116}
2117
Steve Naroff09b266e2007-10-30 23:14:51 +00002118// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002119void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002120 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2121 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002122 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002123 assert(!argT.isNull() && "Can't find 'id' type");
2124 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002125 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002126 assert(!argT.isNull() && "Can't find 'SEL' type");
2127 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002128 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002129 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002130 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002131 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002132 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002133 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002134 FunctionDecl::Extern, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002135}
2136
Steve Naroff874e2322007-11-15 10:28:18 +00002137// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002138void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00002139 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2140 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002141 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002142 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002143 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002144 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2145 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2146 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002147 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002148 assert(!argT.isNull() && "Can't find 'SEL' type");
2149 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002150 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00002151 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002152 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002153 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002154 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002155 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002156 FunctionDecl::Extern, false);
Steve Naroff874e2322007-11-15 10:28:18 +00002157}
2158
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002159// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002160void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002161 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2162 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002163 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002164 assert(!argT.isNull() && "Can't find 'id' type");
2165 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002166 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002167 assert(!argT.isNull() && "Can't find 'SEL' type");
2168 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002169 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002170 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002171 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002172 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002173 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002174 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002175 FunctionDecl::Extern, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002176}
2177
Mike Stump1eb44332009-09-09 15:08:12 +00002178// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002179// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002180void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump1eb44332009-09-09 15:08:12 +00002181 IdentifierInfo *msgSendIdent =
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002182 &Context->Idents.get("objc_msgSendSuper_stret");
2183 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002184 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002185 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002186 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002187 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2188 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2189 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002190 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002191 assert(!argT.isNull() && "Can't find 'SEL' type");
2192 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002193 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002194 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002195 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002196 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002197 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002198 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002199 FunctionDecl::Extern, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002200}
2201
Steve Naroff1284db82008-05-08 22:02:18 +00002202// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002203void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002204 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2205 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002206 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002207 assert(!argT.isNull() && "Can't find 'id' type");
2208 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002209 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002210 assert(!argT.isNull() && "Can't find 'SEL' type");
2211 ArgTys.push_back(argT);
Steve Naroff1284db82008-05-08 22:02:18 +00002212 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002213 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002214 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002215 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002216 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002217 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002218 FunctionDecl::Extern, false);
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002219}
2220
Steve Naroff09b266e2007-10-30 23:14:51 +00002221// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002222void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002223 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2224 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002225 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002226 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002227 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002228 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002229 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002230 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002231 getClassIdent, getClassType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002232 FunctionDecl::Extern, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002233}
2234
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002235// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002236void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002237 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2238 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002239 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002240 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002241 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002242 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002243 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002244 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002245 getClassIdent, getClassType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002246 FunctionDecl::Extern, false);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002247}
2248
Steve Naroffb29b4272008-04-14 22:03:09 +00002249Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002250 QualType strType = getConstantStringStructType();
2251
2252 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002253
2254 std::string tmpName = InFileName;
2255 unsigned i;
2256 for (i=0; i < tmpName.length(); i++) {
2257 char c = tmpName.at(i);
2258 // replace any non alphanumeric characters with '_'.
2259 if (!isalpha(c) && (c < '0' || c > '9'))
2260 tmpName[i] = '_';
2261 }
2262 S += tmpName;
2263 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002264 S += utostr(NumObjCStringLiterals++);
2265
Steve Naroffba92b2e2008-03-27 22:29:16 +00002266 Preamble += "static __NSConstantStringImpl " + S;
2267 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2268 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002269 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002270 std::string prettyBufS;
2271 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00002272 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2273 PrintingPolicy(LangOpts));
Steve Naroffba92b2e2008-03-27 22:29:16 +00002274 Preamble += prettyBuf.str();
2275 Preamble += ",";
Steve Narofffd5b76f2009-12-06 01:48:44 +00002276 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002277
2278 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2279 &Context->Idents.get(S.c_str()), strType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002280 VarDecl::Static);
Ted Kremenek8189cde2009-02-07 01:47:29 +00002281 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
2282 Expr *Unop = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002283 Context->getPointerType(DRE->getType()),
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002284 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002285 // cast to NSConstantString *
Mike Stump1eb44332009-09-09 15:08:12 +00002286 CastExpr *cast = new (Context) CStyleCastExpr(Exp->getType(),
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002287 CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00002288 Unop, Exp->getType(),
2289 SourceLocation(),
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002290 SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002291 ReplaceStmt(Exp, cast);
Steve Naroff4c3580e2008-12-04 23:50:32 +00002292 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002293 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002294}
2295
Steve Naroffb29b4272008-04-14 22:03:09 +00002296ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002297 // check if we are sending a message to 'super'
Douglas Gregorf8d49f62009-01-09 17:18:27 +00002298 if (!CurMethodDef || !CurMethodDef->isInstanceMethod()) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002299
Douglas Gregorcd9b46e2008-11-04 14:56:14 +00002300 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002301 const ObjCObjectPointerType *OPT =
John McCall183700f2009-09-21 23:43:11 +00002302 Super->getType()->getAs<ObjCObjectPointerType>();
Steve Naroff14108da2009-07-10 23:34:53 +00002303 assert(OPT);
2304 const ObjCInterfaceType *IT = OPT->getInterfaceType();
Chris Lattner0d17f6f2008-06-21 18:04:54 +00002305 return IT->getDecl();
2306 }
2307 return 0;
Steve Naroff874e2322007-11-15 10:28:18 +00002308}
2309
2310// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002311QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002312 if (!SuperStructDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002313 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002314 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002315 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002316 QualType FieldTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00002317
Steve Naroff874e2322007-11-15 10:28:18 +00002318 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002319 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002320 // struct objc_class *super;
Mike Stump1eb44332009-09-09 15:08:12 +00002321 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor44b43212008-12-11 16:49:14 +00002322
Steve Naroff874e2322007-11-15 10:28:18 +00002323 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002324 for (unsigned i = 0; i < 2; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002325 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2326 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002327 FieldTypes[i], 0,
2328 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002329 /*Mutable=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002330 }
Mike Stump1eb44332009-09-09 15:08:12 +00002331
Douglas Gregor44b43212008-12-11 16:49:14 +00002332 SuperStructDecl->completeDefinition(*Context);
Steve Naroff874e2322007-11-15 10:28:18 +00002333 }
2334 return Context->getTagDeclType(SuperStructDecl);
2335}
2336
Steve Naroffb29b4272008-04-14 22:03:09 +00002337QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002338 if (!ConstantStringDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002339 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002340 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002341 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002342 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002343
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002344 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002345 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002346 // int flags;
Mike Stump1eb44332009-09-09 15:08:12 +00002347 FieldTypes[1] = Context->IntTy;
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002348 // char *str;
Mike Stump1eb44332009-09-09 15:08:12 +00002349 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002350 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002351 FieldTypes[3] = Context->LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002352
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002353 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002354 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002355 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2356 ConstantStringDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00002357 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002358 FieldTypes[i], 0,
Douglas Gregor44b43212008-12-11 16:49:14 +00002359 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002360 /*Mutable=*/true));
Douglas Gregor44b43212008-12-11 16:49:14 +00002361 }
2362
2363 ConstantStringDecl->completeDefinition(*Context);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002364 }
2365 return Context->getTagDeclType(ConstantStringDecl);
2366}
2367
Steve Naroffb29b4272008-04-14 22:03:09 +00002368Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002369 if (!SelGetUidFunctionDecl)
2370 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002371 if (!MsgSendFunctionDecl)
2372 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002373 if (!MsgSendSuperFunctionDecl)
2374 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002375 if (!MsgSendStretFunctionDecl)
2376 SynthMsgSendStretFunctionDecl();
2377 if (!MsgSendSuperStretFunctionDecl)
2378 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002379 if (!MsgSendFpretFunctionDecl)
2380 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002381 if (!GetClassFunctionDecl)
2382 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002383 if (!GetMetaClassFunctionDecl)
2384 SynthGetMetaClassFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002385
Steve Naroff874e2322007-11-15 10:28:18 +00002386 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002387 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2388 // May need to use objc_msgSend_stret() as well.
2389 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroff621edce2009-04-29 16:37:50 +00002390 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2391 QualType resultType = mDecl->getResultType();
Chris Lattner8b51fd72008-07-26 22:36:27 +00002392 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002393 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002394 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002395 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002396 }
Mike Stump1eb44332009-09-09 15:08:12 +00002397
Steve Naroff934f2762007-10-24 22:48:43 +00002398 // Synthesize a call to objc_msgSend().
2399 llvm::SmallVector<Expr*, 8> MsgExprs;
2400 IdentifierInfo *clsName = Exp->getClassName();
Mike Stump1eb44332009-09-09 15:08:12 +00002401
Steve Naroff934f2762007-10-24 22:48:43 +00002402 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2403 if (clsName) { // class message.
Steve Narofffc93d522008-07-24 19:44:33 +00002404 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2405 // the 'super' idiom within a class method.
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00002406 if (clsName->getName() == "super") {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002407 MsgSendFlavor = MsgSendSuperFunctionDecl;
2408 if (MsgSendStretFlavor)
2409 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2410 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump1eb44332009-09-09 15:08:12 +00002411
2412 ObjCInterfaceDecl *SuperDecl =
Steve Naroff54055232008-10-27 17:20:55 +00002413 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002414
2415 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00002416
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002417 // set the receiver to self, the first argument to all methods.
Steve Naroff621edce2009-04-29 16:37:50 +00002418 InitExprs.push_back(
Mike Stump1eb44332009-09-09 15:08:12 +00002419 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002420 CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00002421 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroff621edce2009-04-29 16:37:50 +00002422 Context->getObjCIdType(),
2423 SourceLocation()),
2424 Context->getObjCIdType(),
2425 SourceLocation(), SourceLocation())); // set the 'receiver'.
2426
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002427 llvm::SmallVector<Expr*, 8> ClsExprs;
2428 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner2085fd62009-02-18 06:40:38 +00002429 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbare013d682009-10-18 20:26:12 +00002430 SuperDecl->getIdentifier()->getNameStart(),
2431 SuperDecl->getIdentifier()->getLength(),
2432 false, argType, SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002433 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002434 &ClsExprs[0],
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002435 ClsExprs.size());
2436 // To turn off a warning, type-cast to 'id'
Douglas Gregor49badde2008-10-27 19:41:14 +00002437 InitExprs.push_back( // set 'super class', using objc_getClass().
Mike Stump1eb44332009-09-09 15:08:12 +00002438 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002439 CastExpr::CK_Unknown,
Douglas Gregor49badde2008-10-27 19:41:14 +00002440 Cls, Context->getObjCIdType(),
Mike Stump1eb44332009-09-09 15:08:12 +00002441 SourceLocation(), SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002442 // struct objc_super
2443 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00002444 Expr *SuperRep;
Mike Stump1eb44332009-09-09 15:08:12 +00002445
Steve Naroff23f41272008-03-11 18:14:26 +00002446 if (LangOpts.Microsoft) {
2447 SynthSuperContructorFunctionDecl();
2448 // Simulate a contructor call...
Mike Stump1eb44332009-09-09 15:08:12 +00002449 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff23f41272008-03-11 18:14:26 +00002450 superType, SourceLocation());
Ted Kremenek668bf912009-02-09 20:51:47 +00002451 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00002452 InitExprs.size(),
Ted Kremenek668bf912009-02-09 20:51:47 +00002453 superType, SourceLocation());
Steve Naroff46a98a72008-12-23 20:11:22 +00002454 // The code for super is a little tricky to prevent collision with
2455 // the structure definition in the header. The rewriter has it's own
2456 // internal definition (__rw_objc_super) that is uses. This is why
2457 // we need the cast below. For example:
2458 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2459 //
Ted Kremenek8189cde2009-02-07 01:47:29 +00002460 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002461 Context->getPointerType(SuperRep->getType()),
Steve Naroff46a98a72008-12-23 20:11:22 +00002462 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002463 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
2464 CastExpr::CK_Unknown, SuperRep,
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002465 Context->getPointerType(superType),
Mike Stump1eb44332009-09-09 15:08:12 +00002466 SourceLocation(), SourceLocation());
2467 } else {
Steve Naroff23f41272008-03-11 18:14:26 +00002468 // (struct objc_super) { <exprs from above> }
Mike Stump1eb44332009-09-09 15:08:12 +00002469 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2470 &InitExprs[0], InitExprs.size(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002471 SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00002472 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE,
Chris Lattner418f6c72008-10-26 23:43:26 +00002473 false);
Steve Naroff46a98a72008-12-23 20:11:22 +00002474 // struct objc_super *
Ted Kremenek8189cde2009-02-07 01:47:29 +00002475 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002476 Context->getPointerType(SuperRep->getType()),
Steve Naroff46a98a72008-12-23 20:11:22 +00002477 SourceLocation());
Steve Naroff23f41272008-03-11 18:14:26 +00002478 }
Steve Naroff46a98a72008-12-23 20:11:22 +00002479 MsgExprs.push_back(SuperRep);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002480 } else {
2481 llvm::SmallVector<Expr*, 8> ClsExprs;
2482 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner2085fd62009-02-18 06:40:38 +00002483 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbare013d682009-10-18 20:26:12 +00002484 clsName->getNameStart(),
Chris Lattner2085fd62009-02-18 06:40:38 +00002485 clsName->getLength(),
2486 false, argType,
2487 SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002488 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002489 &ClsExprs[0],
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002490 ClsExprs.size());
2491 MsgExprs.push_back(Cls);
2492 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002493 } else { // instance message.
2494 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00002495
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002496 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00002497 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002498 if (MsgSendStretFlavor)
2499 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00002500 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump1eb44332009-09-09 15:08:12 +00002501
Steve Naroff874e2322007-11-15 10:28:18 +00002502 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00002503
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002504 InitExprs.push_back(
Mike Stump1eb44332009-09-09 15:08:12 +00002505 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002506 CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00002507 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Narofff616ebb2008-07-16 22:35:27 +00002508 Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002509 SourceLocation()),
2510 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002511 SourceLocation(), SourceLocation())); // set the 'receiver'.
Mike Stump1eb44332009-09-09 15:08:12 +00002512
Steve Naroff874e2322007-11-15 10:28:18 +00002513 llvm::SmallVector<Expr*, 8> ClsExprs;
2514 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002515 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbare013d682009-10-18 20:26:12 +00002516 SuperDecl->getIdentifier()->getNameStart(),
2517 SuperDecl->getIdentifier()->getLength(),
2518 false, argType, SourceLocation()));
Steve Naroff874e2322007-11-15 10:28:18 +00002519 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002520 &ClsExprs[0],
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002521 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00002522 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002523 InitExprs.push_back(
Douglas Gregor49badde2008-10-27 19:41:14 +00002524 // set 'super class', using objc_getClass().
Mike Stump1eb44332009-09-09 15:08:12 +00002525 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002526 CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00002527 Cls, Context->getObjCIdType(), SourceLocation(), SourceLocation()));
Steve Naroff874e2322007-11-15 10:28:18 +00002528 // struct objc_super
2529 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00002530 Expr *SuperRep;
Mike Stump1eb44332009-09-09 15:08:12 +00002531
Steve Naroffc0a123c2008-03-11 17:37:02 +00002532 if (LangOpts.Microsoft) {
2533 SynthSuperContructorFunctionDecl();
2534 // Simulate a contructor call...
Mike Stump1eb44332009-09-09 15:08:12 +00002535 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroffc0a123c2008-03-11 17:37:02 +00002536 superType, SourceLocation());
Ted Kremenek668bf912009-02-09 20:51:47 +00002537 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00002538 InitExprs.size(),
Ted Kremenek668bf912009-02-09 20:51:47 +00002539 superType, SourceLocation());
Steve Naroff46a98a72008-12-23 20:11:22 +00002540 // The code for super is a little tricky to prevent collision with
2541 // the structure definition in the header. The rewriter has it's own
2542 // internal definition (__rw_objc_super) that is uses. This is why
2543 // we need the cast below. For example:
2544 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2545 //
Ted Kremenek8189cde2009-02-07 01:47:29 +00002546 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002547 Context->getPointerType(SuperRep->getType()),
Steve Naroff46a98a72008-12-23 20:11:22 +00002548 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002549 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002550 CastExpr::CK_Unknown,
Steve Naroff46a98a72008-12-23 20:11:22 +00002551 SuperRep, Context->getPointerType(superType),
Mike Stump1eb44332009-09-09 15:08:12 +00002552 SourceLocation(), SourceLocation());
Steve Naroffc0a123c2008-03-11 17:37:02 +00002553 } else {
2554 // (struct objc_super) { <exprs from above> }
Mike Stump1eb44332009-09-09 15:08:12 +00002555 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2556 &InitExprs[0], InitExprs.size(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002557 SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00002558 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002559 }
Steve Naroff46a98a72008-12-23 20:11:22 +00002560 MsgExprs.push_back(SuperRep);
Steve Naroff874e2322007-11-15 10:28:18 +00002561 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002562 // Remove all type-casts because it may contain objc-style types; e.g.
2563 // Foo<Proto> *.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002564 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002565 recExpr = CE->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00002566 recExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002567 CastExpr::CK_Unknown, recExpr,
Mike Stump1eb44332009-09-09 15:08:12 +00002568 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002569 SourceLocation(), SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00002570 MsgExprs.push_back(recExpr);
2571 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002572 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00002573 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002574 llvm::SmallVector<Expr*, 8> SelExprs;
2575 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002576 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002577 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00002578 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00002579 false, argType, SourceLocation()));
Steve Naroff934f2762007-10-24 22:48:43 +00002580 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2581 &SelExprs[0], SelExprs.size());
2582 MsgExprs.push_back(SelExp);
Mike Stump1eb44332009-09-09 15:08:12 +00002583
Steve Naroff934f2762007-10-24 22:48:43 +00002584 // Now push any user supplied arguments.
2585 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002586 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002587 // Make all implicit casts explicit...ICE comes in handy:-)
2588 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2589 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregor49badde2008-10-27 19:41:14 +00002590 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002591 ? Context->getObjCIdType()
Douglas Gregor49badde2008-10-27 19:41:14 +00002592 : ICE->getType();
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002593 userExpr = new (Context) CStyleCastExpr(type, CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00002594 userExpr, type, SourceLocation(),
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002595 SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002596 }
2597 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002598 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002599 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002600 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002601 userExpr = CE->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00002602 userExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002603 CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00002604 userExpr, Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002605 SourceLocation(), SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002606 }
Mike Stump1eb44332009-09-09 15:08:12 +00002607 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002608 MsgExprs.push_back(userExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00002609 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2610 // out the argument in the original expression (since we aren't deleting
2611 // the ObjCMessageExpr). See RewritePropertySetter() usage for more info.
2612 //Exp->setArg(i, 0);
Steve Naroff934f2762007-10-24 22:48:43 +00002613 }
Steve Naroffab972d32007-11-04 22:37:50 +00002614 // Generate the funky cast.
2615 CastExpr *cast;
2616 llvm::SmallVector<QualType, 8> ArgTypes;
2617 QualType returnType;
Mike Stump1eb44332009-09-09 15:08:12 +00002618
Steve Naroffab972d32007-11-04 22:37:50 +00002619 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002620 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2621 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2622 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002623 ArgTypes.push_back(Context->getObjCIdType());
2624 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner89951a82009-02-20 18:43:26 +00002625 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002626 // Push any user argument types.
Chris Lattner89951a82009-02-20 18:43:26 +00002627 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2628 E = OMD->param_end(); PI != E; ++PI) {
2629 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump1eb44332009-09-09 15:08:12 +00002630 ? Context->getObjCIdType()
Chris Lattner89951a82009-02-20 18:43:26 +00002631 : (*PI)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00002632 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroff01f2ffa2008-12-11 21:05:33 +00002633 if (isTopLevelBlockPointerType(t)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002634 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroffa206b062008-10-29 14:49:46 +00002635 t = Context->getPointerType(BPT->getPointeeType());
2636 }
Steve Naroff352336b2007-11-05 14:36:37 +00002637 ArgTypes.push_back(t);
2638 }
Chris Lattner89951a82009-02-20 18:43:26 +00002639 returnType = OMD->getResultType()->isObjCQualifiedIdType()
2640 ? Context->getObjCIdType() : OMD->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00002641 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002642 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002643 }
2644 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002645 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002646
Steve Naroffab972d32007-11-04 22:37:50 +00002647 // Create a reference to the objc_msgSend() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00002648 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002649 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002650
Mike Stump1eb44332009-09-09 15:08:12 +00002651 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Naroffab972d32007-11-04 22:37:50 +00002652 // If we don't do this cast, we get the following bizarre warning/note:
2653 // xx.m:13: warning: function called through a non-compatible type
2654 // xx.m:13: note: if this code is reached, the program will abort
Mike Stump1eb44332009-09-09 15:08:12 +00002655 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy),
2656 CastExpr::CK_Unknown, DRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002657 Context->getPointerType(Context->VoidTy),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002658 SourceLocation(), SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002659
Steve Naroffab972d32007-11-04 22:37:50 +00002660 // Now do the "normal" pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00002661 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002662 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00002663 // If we don't have a method decl, force a variadic cast.
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002664 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Naroffab972d32007-11-04 22:37:50 +00002665 castType = Context->getPointerType(castType);
Mike Stump1eb44332009-09-09 15:08:12 +00002666 cast = new (Context) CStyleCastExpr(castType, CastExpr::CK_Unknown, cast,
2667 castType, SourceLocation(),
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002668 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002669
2670 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002671 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump1eb44332009-09-09 15:08:12 +00002672
John McCall183700f2009-09-21 23:43:11 +00002673 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00002674 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00002675 MsgExprs.size(),
Ted Kremenek668bf912009-02-09 20:51:47 +00002676 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002677 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002678 if (MsgSendStretFlavor) {
2679 // We have the method which returns a struct/union. Must also generate
2680 // call to objc_msgSend_stret and hang both varieties on a conditional
2681 // expression which dictate which one to envoke depending on size of
2682 // method's return type.
Mike Stump1eb44332009-09-09 15:08:12 +00002683
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002684 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00002685 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002686 SourceLocation());
2687 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Mike Stump1eb44332009-09-09 15:08:12 +00002688 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy),
2689 CastExpr::CK_Unknown, STDRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002690 Context->getPointerType(Context->VoidTy),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002691 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002692 // Now do the "normal" pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00002693 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002694 &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002695 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002696 castType = Context->getPointerType(castType);
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002697 cast = new (Context) CStyleCastExpr(castType, CastExpr::CK_Unknown,
2698 cast, castType, SourceLocation(), SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002699
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002700 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002701 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump1eb44332009-09-09 15:08:12 +00002702
John McCall183700f2009-09-21 23:43:11 +00002703 FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00002704 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00002705 MsgExprs.size(),
Ted Kremenek668bf912009-02-09 20:51:47 +00002706 FT->getResultType(), SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002707
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002708 // Build sizeof(returnType)
Mike Stump1eb44332009-09-09 15:08:12 +00002709 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
John McCalla93c9342009-12-07 02:54:59 +00002710 Context->getTrivialTypeSourceInfo(returnType),
Sebastian Redl05189992008-11-11 17:56:53 +00002711 Context->getSizeType(),
2712 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002713 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2714 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2715 // For X86 it is more complicated and some kind of target specific routine
2716 // is needed to decide what to do.
Mike Stump1eb44332009-09-09 15:08:12 +00002717 unsigned IntSize =
Chris Lattner98be4942008-03-05 18:54:05 +00002718 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Mike Stump1eb44332009-09-09 15:08:12 +00002719 IntegerLiteral *limit = new (Context) IntegerLiteral(llvm::APInt(IntSize, 8),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002720 Context->IntTy,
2721 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002722 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
2723 BinaryOperator::LE,
2724 Context->IntTy,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002725 SourceLocation());
2726 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump1eb44332009-09-09 15:08:12 +00002727 ConditionalOperator *CondExpr =
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00002728 new (Context) ConditionalOperator(lessThanExpr,
2729 SourceLocation(), CE,
2730 SourceLocation(), STCE, returnType);
Ted Kremenek8189cde2009-02-07 01:47:29 +00002731 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002732 }
Mike Stump1eb44332009-09-09 15:08:12 +00002733 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002734 return ReplacingStmt;
2735}
2736
Steve Naroffb29b4272008-04-14 22:03:09 +00002737Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002738 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Mike Stump1eb44332009-09-09 15:08:12 +00002739
Steve Naroff934f2762007-10-24 22:48:43 +00002740 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002741 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00002742
2743 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002744 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002745}
2746
Steve Naroff621edce2009-04-29 16:37:50 +00002747// typedef struct objc_object Protocol;
2748QualType RewriteObjC::getProtocolType() {
2749 if (!ProtocolTypeDecl) {
John McCalla93c9342009-12-07 02:54:59 +00002750 TypeSourceInfo *TInfo
2751 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroff621edce2009-04-29 16:37:50 +00002752 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002753 SourceLocation(),
Steve Naroff621edce2009-04-29 16:37:50 +00002754 &Context->Idents.get("Protocol"),
John McCalla93c9342009-12-07 02:54:59 +00002755 TInfo);
Steve Naroff621edce2009-04-29 16:37:50 +00002756 }
2757 return Context->getTypeDeclType(ProtocolTypeDecl);
2758}
2759
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002760/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroff621edce2009-04-29 16:37:50 +00002761/// a synthesized/forward data reference (to the protocol's metadata).
2762/// The forward references (and metadata) are generated in
2763/// RewriteObjC::HandleTranslationUnit().
Steve Naroffb29b4272008-04-14 22:03:09 +00002764Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroff621edce2009-04-29 16:37:50 +00002765 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
2766 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00002767 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Douglas Gregor0da76df2009-11-23 11:41:28 +00002768 ID, getProtocolType(), 0, VarDecl::Extern);
Steve Naroff621edce2009-04-29 16:37:50 +00002769 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), SourceLocation());
2770 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
2771 Context->getPointerType(DRE->getType()),
2772 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002773 CastExpr *castExpr = new (Context) CStyleCastExpr(DerefExpr->getType(),
2774 CastExpr::CK_Unknown,
2775 DerefExpr, DerefExpr->getType(),
Steve Naroff621edce2009-04-29 16:37:50 +00002776 SourceLocation(), SourceLocation());
2777 ReplaceStmt(Exp, castExpr);
2778 ProtocolExprDecls.insert(Exp->getProtocol());
Mike Stump1eb44332009-09-09 15:08:12 +00002779 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00002780 return castExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00002781
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002782}
2783
Mike Stump1eb44332009-09-09 15:08:12 +00002784bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffbaf58c32008-05-31 14:15:04 +00002785 const char *endBuf) {
2786 while (startBuf < endBuf) {
2787 if (*startBuf == '#') {
2788 // Skip whitespace.
2789 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2790 ;
2791 if (!strncmp(startBuf, "if", strlen("if")) ||
2792 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2793 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2794 !strncmp(startBuf, "define", strlen("define")) ||
2795 !strncmp(startBuf, "undef", strlen("undef")) ||
2796 !strncmp(startBuf, "else", strlen("else")) ||
2797 !strncmp(startBuf, "elif", strlen("elif")) ||
2798 !strncmp(startBuf, "endif", strlen("endif")) ||
2799 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2800 !strncmp(startBuf, "include", strlen("include")) ||
2801 !strncmp(startBuf, "import", strlen("import")) ||
2802 !strncmp(startBuf, "include_next", strlen("include_next")))
2803 return true;
2804 }
2805 startBuf++;
2806 }
2807 return false;
2808}
2809
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002810/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002811/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00002812void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002813 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002814 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Mike Stump1eb44332009-09-09 15:08:12 +00002815 assert(CDecl->getNameAsCString() &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002816 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002817 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002818 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002819 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002820 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002821 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00002822 SourceLocation LocStart = CDecl->getLocStart();
2823 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00002824
Steve Narofffea763e82007-11-14 19:25:57 +00002825 const char *startBuf = SM->getCharacterData(LocStart);
2826 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump1eb44332009-09-09 15:08:12 +00002827
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002828 // If no ivars and no root or if its root, directly or indirectly,
2829 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002830 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2831 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner2c78b872009-04-14 23:22:57 +00002832 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Chris Lattneraadaf782008-01-31 19:51:04 +00002833 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002834 return;
2835 }
Mike Stump1eb44332009-09-09 15:08:12 +00002836
2837 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002838 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002839 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002840 Result += CDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002841 if (LangOpts.Microsoft)
2842 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00002843
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002844 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002845 const char *cursor = strchr(startBuf, '{');
Mike Stump1eb44332009-09-09 15:08:12 +00002846 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002847 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00002848 // If the buffer contains preprocessor directives, we do more fine-grained
2849 // rewrites. This is intended to fix code that looks like (which occurs in
2850 // NSURL.h, for example):
2851 //
2852 // #ifdef XYZ
2853 // @interface Foo : NSObject
2854 // #else
2855 // @interface FooBar : NSObject
2856 // #endif
2857 // {
2858 // int i;
2859 // }
2860 // @end
2861 //
2862 // This clause is segregated to avoid breaking the common case.
2863 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002864 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffbaf58c32008-05-31 14:15:04 +00002865 CDecl->getClassLoc();
2866 const char *endHeader = SM->getCharacterData(L);
Chris Lattner2c78b872009-04-14 23:22:57 +00002867 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffbaf58c32008-05-31 14:15:04 +00002868
Chris Lattnercafeb352009-02-20 18:18:36 +00002869 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00002870 // advance to the end of the referenced protocols.
2871 while (endHeader < cursor && *endHeader != '>') endHeader++;
2872 endHeader++;
2873 }
2874 // rewrite the original header
2875 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2876 } else {
2877 // rewrite the original header *without* disturbing the '{'
Steve Naroff17c87782009-12-04 21:36:32 +00002878 ReplaceText(LocStart, cursor-startBuf, Result.c_str(), Result.size());
Steve Naroffbaf58c32008-05-31 14:15:04 +00002879 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002880 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002881 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002882 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002883 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002884 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00002885 Result += "_IVARS;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002886
Steve Narofffea763e82007-11-14 19:25:57 +00002887 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002888 SourceLocation OnePastCurly =
2889 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2890 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002891 }
2892 cursor++; // past '{'
Mike Stump1eb44332009-09-09 15:08:12 +00002893
Steve Narofffea763e82007-11-14 19:25:57 +00002894 // Now comment out any visibility specifiers.
2895 while (cursor < endBuf) {
2896 if (*cursor == '@') {
2897 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002898 // Skip whitespace.
2899 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2900 /*scan*/;
2901
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002902 // FIXME: presence of @public, etc. inside comment results in
2903 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002904 if (!strncmp(cursor, "public", strlen("public")) ||
2905 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00002906 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002907 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002908 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002909 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002910 // FIXME: If there are cases where '<' is used in ivar declaration part
2911 // of user code, then scan the ivar list and use needToScanForQualifiers
2912 // for type checking.
2913 else if (*cursor == '<') {
2914 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002915 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002916 cursor = strchr(cursor, '>');
2917 cursor++;
2918 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002919 InsertText(atLoc, " */", 3);
Steve Naroffced80a82008-10-30 12:09:33 +00002920 } else if (*cursor == '^') { // rewrite block specifier.
2921 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2922 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002923 }
Steve Narofffea763e82007-11-14 19:25:57 +00002924 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002925 }
Steve Narofffea763e82007-11-14 19:25:57 +00002926 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002927 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00002928 } else { // we don't have any instance variables - insert super struct.
Chris Lattner2c78b872009-04-14 23:22:57 +00002929 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Narofffea763e82007-11-14 19:25:57 +00002930 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002931 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002932 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002933 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00002934 Result += "_IVARS;\n};\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00002935 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002936 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002937 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002938 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00002939 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002940}
2941
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002942// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002943/// class methods.
Douglas Gregor653f1b12009-04-23 01:02:12 +00002944template<typename MethodIterator>
2945void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
2946 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002947 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002948 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002949 const char *ClassName,
2950 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002951 if (MethodBegin == MethodEnd) return;
Mike Stump1eb44332009-09-09 15:08:12 +00002952
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002953 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002954 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002955 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002956 SEL _cmd;
2957 char *method_types;
2958 void *_imp;
2959 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002960 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002961 Result += "\nstruct _objc_method {\n";
2962 Result += "\tSEL _cmd;\n";
2963 Result += "\tchar *method_types;\n";
2964 Result += "\tvoid *_imp;\n";
2965 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002966
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002967 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002968 }
Mike Stump1eb44332009-09-09 15:08:12 +00002969
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002970 // Build _objc_method_list for class's methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00002971
Steve Naroff946a6932008-03-11 00:12:29 +00002972 /* struct {
2973 struct _objc_method_list *next_method;
2974 int method_count;
2975 struct _objc_method method_list[];
2976 }
2977 */
Douglas Gregor653f1b12009-04-23 01:02:12 +00002978 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroff946a6932008-03-11 00:12:29 +00002979 Result += "\nstatic struct {\n";
2980 Result += "\tstruct _objc_method_list *next_method;\n";
2981 Result += "\tint method_count;\n";
2982 Result += "\tstruct _objc_method method_list[";
Douglas Gregor653f1b12009-04-23 01:02:12 +00002983 Result += utostr(NumMethods);
Steve Naroff946a6932008-03-11 00:12:29 +00002984 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002985 Result += prefix;
2986 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2987 Result += "_METHODS_";
2988 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002989 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002990 Result += IsInstanceMethod ? "inst" : "cls";
2991 Result += "_meth\")))= ";
Douglas Gregor653f1b12009-04-23 01:02:12 +00002992 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002993
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002994 Result += "\t,{{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002995 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002996 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002997 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002998 Result += "\", \"";
2999 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003000 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003001 Result += MethodInternalNames[*MethodBegin];
3002 Result += "}\n";
3003 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3004 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003005 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003006 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003007 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003008 Result += "\", \"";
3009 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003010 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003011 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00003012 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003013 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003014 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003015}
3016
Steve Naroff621edce2009-04-29 16:37:50 +00003017/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00003018void RewriteObjC::
Steve Naroff621edce2009-04-29 16:37:50 +00003019RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, const char *prefix,
3020 const char *ClassName, std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003021 static bool objc_protocol_methods = false;
Steve Naroff621edce2009-04-29 16:37:50 +00003022
3023 // Output struct protocol_methods holder of method selector and type.
3024 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3025 /* struct protocol_methods {
3026 SEL _cmd;
3027 char *method_types;
3028 }
3029 */
3030 Result += "\nstruct _protocol_methods {\n";
3031 Result += "\tstruct objc_selector *_cmd;\n";
3032 Result += "\tchar *method_types;\n";
3033 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003034
Steve Naroff621edce2009-04-29 16:37:50 +00003035 objc_protocol_methods = true;
3036 }
3037 // Do not synthesize the protocol more than once.
3038 if (ObjCSynthesizedProtocols.count(PDecl))
3039 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003040
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003041 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3042 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3043 PDecl->instmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003044 /* struct _objc_protocol_method_list {
3045 int protocol_method_count;
3046 struct protocol_methods protocols[];
3047 }
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003048 */
Steve Naroff621edce2009-04-29 16:37:50 +00003049 Result += "\nstatic struct {\n";
3050 Result += "\tint protocol_method_count;\n";
3051 Result += "\tstruct _protocol_methods protocol_methods[";
3052 Result += utostr(NumMethods);
3053 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3054 Result += PDecl->getNameAsString();
3055 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3056 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003057
Steve Naroff621edce2009-04-29 16:37:50 +00003058 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003059 for (ObjCProtocolDecl::instmeth_iterator
3060 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003061 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003062 if (I == PDecl->instmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003063 Result += "\t ,{{(struct objc_selector *)\"";
3064 else
3065 Result += "\t ,{(struct objc_selector *)\"";
3066 Result += (*I)->getSelector().getAsString().c_str();
3067 std::string MethodTypeString;
3068 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3069 Result += "\", \"";
3070 Result += MethodTypeString;
3071 Result += "\"}\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003072 }
Steve Naroff621edce2009-04-29 16:37:50 +00003073 Result += "\t }\n};\n";
3074 }
Mike Stump1eb44332009-09-09 15:08:12 +00003075
Steve Naroff621edce2009-04-29 16:37:50 +00003076 // Output class methods declared in this protocol.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003077 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3078 PDecl->classmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003079 if (NumMethods > 0) {
3080 /* struct _objc_protocol_method_list {
3081 int protocol_method_count;
3082 struct protocol_methods protocols[];
3083 }
3084 */
3085 Result += "\nstatic struct {\n";
3086 Result += "\tint protocol_method_count;\n";
3087 Result += "\tstruct _protocol_methods protocol_methods[";
3088 Result += utostr(NumMethods);
3089 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3090 Result += PDecl->getNameAsString();
3091 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3092 "{\n\t";
3093 Result += utostr(NumMethods);
3094 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003095
Steve Naroff621edce2009-04-29 16:37:50 +00003096 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003097 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003098 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003099 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003100 if (I == PDecl->classmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003101 Result += "\t ,{{(struct objc_selector *)\"";
3102 else
3103 Result += "\t ,{(struct objc_selector *)\"";
3104 Result += (*I)->getSelector().getAsString().c_str();
3105 std::string MethodTypeString;
3106 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3107 Result += "\", \"";
3108 Result += MethodTypeString;
3109 Result += "\"}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003110 }
Steve Naroff621edce2009-04-29 16:37:50 +00003111 Result += "\t }\n};\n";
3112 }
3113
3114 // Output:
3115 /* struct _objc_protocol {
3116 // Objective-C 1.0 extensions
3117 struct _objc_protocol_extension *isa;
3118 char *protocol_name;
3119 struct _objc_protocol **protocol_list;
3120 struct _objc_protocol_method_list *instance_methods;
3121 struct _objc_protocol_method_list *class_methods;
Mike Stump1eb44332009-09-09 15:08:12 +00003122 };
Steve Naroff621edce2009-04-29 16:37:50 +00003123 */
3124 static bool objc_protocol = false;
3125 if (!objc_protocol) {
3126 Result += "\nstruct _objc_protocol {\n";
3127 Result += "\tstruct _objc_protocol_extension *isa;\n";
3128 Result += "\tchar *protocol_name;\n";
3129 Result += "\tstruct _objc_protocol **protocol_list;\n";
3130 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3131 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003132 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003133
Steve Naroff621edce2009-04-29 16:37:50 +00003134 objc_protocol = true;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003135 }
Mike Stump1eb44332009-09-09 15:08:12 +00003136
Steve Naroff621edce2009-04-29 16:37:50 +00003137 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3138 Result += PDecl->getNameAsString();
3139 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3140 "{\n\t0, \"";
3141 Result += PDecl->getNameAsString();
3142 Result += "\", 0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003143 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003144 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3145 Result += PDecl->getNameAsString();
3146 Result += ", ";
3147 }
3148 else
3149 Result += "0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003150 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003151 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3152 Result += PDecl->getNameAsString();
3153 Result += "\n";
3154 }
3155 else
3156 Result += "0\n";
3157 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003158
Steve Naroff621edce2009-04-29 16:37:50 +00003159 // Mark this protocol as having been generated.
3160 if (!ObjCSynthesizedProtocols.insert(PDecl))
3161 assert(false && "protocol already synthesized");
3162
3163}
3164
3165void RewriteObjC::
3166RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
3167 const char *prefix, const char *ClassName,
3168 std::string &Result) {
3169 if (Protocols.empty()) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003170
Steve Naroff621edce2009-04-29 16:37:50 +00003171 for (unsigned i = 0; i != Protocols.size(); i++)
3172 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3173
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003174 // Output the top lovel protocol meta-data for the class.
3175 /* struct _objc_protocol_list {
3176 struct _objc_protocol_list *next;
3177 int protocol_count;
3178 struct _objc_protocol *class_protocols[];
3179 }
3180 */
3181 Result += "\nstatic struct {\n";
3182 Result += "\tstruct _objc_protocol_list *next;\n";
3183 Result += "\tint protocol_count;\n";
3184 Result += "\tstruct _objc_protocol *class_protocols[";
3185 Result += utostr(Protocols.size());
3186 Result += "];\n} _OBJC_";
3187 Result += prefix;
3188 Result += "_PROTOCOLS_";
3189 Result += ClassName;
3190 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3191 "{\n\t0, ";
3192 Result += utostr(Protocols.size());
3193 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003194
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003195 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003196 Result += Protocols[0]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003197 Result += " \n";
Mike Stump1eb44332009-09-09 15:08:12 +00003198
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003199 for (unsigned i = 1; i != Protocols.size(); i++) {
3200 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003201 Result += Protocols[i]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003202 Result += "\n";
3203 }
3204 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003205}
3206
Steve Naroff621edce2009-04-29 16:37:50 +00003207
Mike Stump1eb44332009-09-09 15:08:12 +00003208/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003209/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00003210void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003211 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003212 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003213 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003214 ObjCCategoryDecl *CDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00003215 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003216 CDecl = CDecl->getNextClassCategory())
3217 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3218 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003219
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003220 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00003221 FullCategoryName += '_';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003222 FullCategoryName += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003223
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003224 // Build _objc_method_list for class's instance methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003225 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003226 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003227
3228 // If any of our property implementations have associated getters or
3229 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003230 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3231 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003232 Prop != PropEnd; ++Prop) {
3233 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3234 continue;
3235 if (!(*Prop)->getPropertyIvarDecl())
3236 continue;
3237 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3238 if (!PD)
3239 continue;
3240 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3241 InstanceMethods.push_back(Getter);
3242 if (PD->isReadOnly())
3243 continue;
3244 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3245 InstanceMethods.push_back(Setter);
3246 }
3247 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003248 true, "CATEGORY_", FullCategoryName.c_str(),
3249 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003250
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003251 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003252 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003253 false, "CATEGORY_", FullCategoryName.c_str(),
3254 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003255
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003256 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00003257 // Null CDecl is case of a category implementation with no category interface
3258 if (CDecl)
Steve Naroff621edce2009-04-29 16:37:50 +00003259 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
3260 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003261 /* struct _objc_category {
3262 char *category_name;
3263 char *class_name;
3264 struct _objc_method_list *instance_methods;
3265 struct _objc_method_list *class_methods;
3266 struct _objc_protocol_list *protocols;
3267 // Objective-C 1.0 extensions
3268 uint32_t size; // sizeof (struct _objc_category)
Mike Stump1eb44332009-09-09 15:08:12 +00003269 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003270 // @property decl.
Mike Stump1eb44332009-09-09 15:08:12 +00003271 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003272 */
Mike Stump1eb44332009-09-09 15:08:12 +00003273
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003274 static bool objc_category = false;
3275 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003276 Result += "\nstruct _objc_category {\n";
3277 Result += "\tchar *category_name;\n";
3278 Result += "\tchar *class_name;\n";
3279 Result += "\tstruct _objc_method_list *instance_methods;\n";
3280 Result += "\tstruct _objc_method_list *class_methods;\n";
3281 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003282 Result += "\tunsigned int size;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003283 Result += "\tstruct _objc_property_list *instance_properties;\n";
3284 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003285 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003286 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003287 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3288 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003289 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003290 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003291 Result += "\"\n\t, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003292 Result += ClassDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003293 Result += "\"\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003294
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003295 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003296 Result += "\t, (struct _objc_method_list *)"
3297 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3298 Result += FullCategoryName;
3299 Result += "\n";
3300 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003301 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003302 Result += "\t, 0\n";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003303 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003304 Result += "\t, (struct _objc_method_list *)"
3305 "&_OBJC_CATEGORY_CLASS_METHODS_";
3306 Result += FullCategoryName;
3307 Result += "\n";
3308 }
3309 else
3310 Result += "\t, 0\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003311
Chris Lattnercafeb352009-02-20 18:18:36 +00003312 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003313 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003314 Result += FullCategoryName;
3315 Result += "\n";
3316 }
3317 else
3318 Result += "\t, 0\n";
3319 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003320}
3321
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003322/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3323/// ivar offset.
Mike Stump1eb44332009-09-09 15:08:12 +00003324void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
3325 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003326 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00003327 if (ivar->isBitField()) {
3328 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3329 // place all bitfields at offset 0.
3330 Result += "0";
3331 } else {
3332 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003333 Result += IDecl->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003334 if (LangOpts.Microsoft)
3335 Result += "_IMPL";
3336 Result += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003337 Result += ivar->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003338 Result += ")";
3339 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003340}
3341
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003342//===----------------------------------------------------------------------===//
3343// Meta Data Emission
3344//===----------------------------------------------------------------------===//
3345
Steve Naroffb29b4272008-04-14 22:03:09 +00003346void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003347 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003348 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00003349
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003350 // Explictly declared @interface's are already synthesized.
Steve Naroff33feeb02009-04-20 20:09:33 +00003351 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003352 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003353 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003354 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003355 }
Mike Stump1eb44332009-09-09 15:08:12 +00003356
Chris Lattnerbe6df082007-12-12 07:56:42 +00003357 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003358 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump1eb44332009-09-09 15:08:12 +00003359 ? IDecl->ivar_size()
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003360 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003361 if (NumIvars > 0) {
3362 static bool objc_ivar = false;
3363 if (!objc_ivar) {
3364 /* struct _objc_ivar {
3365 char *ivar_name;
3366 char *ivar_type;
3367 int ivar_offset;
Mike Stump1eb44332009-09-09 15:08:12 +00003368 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003369 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003370 Result += "\nstruct _objc_ivar {\n";
3371 Result += "\tchar *ivar_name;\n";
3372 Result += "\tchar *ivar_type;\n";
3373 Result += "\tint ivar_offset;\n";
3374 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003375
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003376 objc_ivar = true;
3377 }
3378
Steve Naroff946a6932008-03-11 00:12:29 +00003379 /* struct {
3380 int ivar_count;
3381 struct _objc_ivar ivar_list[nIvars];
Mike Stump1eb44332009-09-09 15:08:12 +00003382 };
Steve Naroff946a6932008-03-11 00:12:29 +00003383 */
Mike Stump1eb44332009-09-09 15:08:12 +00003384 Result += "\nstatic struct {\n";
Steve Naroff946a6932008-03-11 00:12:29 +00003385 Result += "\tint ivar_count;\n";
3386 Result += "\tstruct _objc_ivar ivar_list[";
3387 Result += utostr(NumIvars);
3388 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003389 Result += IDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003390 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003391 "{\n\t";
3392 Result += utostr(NumIvars);
3393 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003394
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003395 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003396 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003397 if (!IDecl->ivar_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003398 for (ObjCImplementationDecl::ivar_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003399 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003400 IV != IVEnd; ++IV)
3401 IVars.push_back(*IV);
3402 IVI = IVars.begin();
3403 IVE = IVars.end();
Chris Lattnerbe6df082007-12-12 07:56:42 +00003404 } else {
3405 IVI = CDecl->ivar_begin();
3406 IVE = CDecl->ivar_end();
3407 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003408 Result += "\t,{{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003409 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003410 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003411 std::string TmpString, StrEncoding;
3412 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3413 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003414 Result += StrEncoding;
3415 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003416 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003417 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003418 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003419 Result += "\t ,{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003420 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003421 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003422 std::string TmpString, StrEncoding;
3423 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3424 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003425 Result += StrEncoding;
3426 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003427 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003428 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003429 }
Mike Stump1eb44332009-09-09 15:08:12 +00003430
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003431 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003432 }
Mike Stump1eb44332009-09-09 15:08:12 +00003433
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003434 // Build _objc_method_list for class's instance methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003435 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003436 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003437
3438 // If any of our property implementations have associated getters or
3439 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003440 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3441 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003442 Prop != PropEnd; ++Prop) {
3443 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3444 continue;
3445 if (!(*Prop)->getPropertyIvarDecl())
3446 continue;
3447 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3448 if (!PD)
3449 continue;
3450 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3451 InstanceMethods.push_back(Getter);
3452 if (PD->isReadOnly())
3453 continue;
3454 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3455 InstanceMethods.push_back(Setter);
3456 }
3457 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003458 true, "", IDecl->getNameAsCString(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003459
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003460 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003461 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003462 false, "", IDecl->getNameAsCString(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003463
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003464 // Protocols referenced in class declaration?
Steve Naroff621edce2009-04-29 16:37:50 +00003465 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
3466 "CLASS", CDecl->getNameAsCString(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003467
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003468 // Declaration of class/meta-class metadata
3469 /* struct _objc_class {
3470 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003471 const char *super_class_name;
3472 char *name;
3473 long version;
3474 long info;
3475 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003476 struct _objc_ivar_list *ivars;
3477 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003478 struct objc_cache *cache;
3479 struct objc_protocol_list *protocols;
3480 const char *ivar_layout;
3481 struct _objc_class_ext *ext;
Mike Stump1eb44332009-09-09 15:08:12 +00003482 };
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003483 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003484 static bool objc_class = false;
3485 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003486 Result += "\nstruct _objc_class {\n";
3487 Result += "\tstruct _objc_class *isa;\n";
3488 Result += "\tconst char *super_class_name;\n";
3489 Result += "\tchar *name;\n";
3490 Result += "\tlong version;\n";
3491 Result += "\tlong info;\n";
3492 Result += "\tlong instance_size;\n";
3493 Result += "\tstruct _objc_ivar_list *ivars;\n";
3494 Result += "\tstruct _objc_method_list *methods;\n";
3495 Result += "\tstruct objc_cache *cache;\n";
3496 Result += "\tstruct _objc_protocol_list *protocols;\n";
3497 Result += "\tconst char *ivar_layout;\n";
3498 Result += "\tstruct _objc_class_ext *ext;\n";
3499 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003500 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003501 }
Mike Stump1eb44332009-09-09 15:08:12 +00003502
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003503 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003504 ObjCInterfaceDecl *RootClass = 0;
3505 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003506 while (SuperClass) {
3507 RootClass = SuperClass;
3508 SuperClass = SuperClass->getSuperClass();
3509 }
3510 SuperClass = CDecl->getSuperClass();
Mike Stump1eb44332009-09-09 15:08:12 +00003511
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003512 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003513 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003514 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003515 "{\n\t(struct _objc_class *)\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003516 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003517 Result += "\"";
3518
3519 if (SuperClass) {
3520 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003521 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003522 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003523 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003524 Result += "\"";
3525 }
3526 else {
3527 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003528 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003529 Result += "\"";
3530 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003531 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003532 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003533 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003534 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff23f41272008-03-11 18:14:26 +00003535 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003536 Result += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003537 Result += "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003538 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003539 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003540 Result += ", 0\n";
Chris Lattnercafeb352009-02-20 18:18:36 +00003541 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003542 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003543 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003544 Result += ",0,0\n";
3545 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003546 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003547 Result += "\t,0,0,0,0\n";
3548 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003549
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003550 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003551 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003552 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003553 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003554 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003555 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003556 if (SuperClass) {
3557 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003558 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003559 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003560 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003561 Result += "\"";
3562 }
3563 else {
3564 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003565 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003566 Result += "\"";
3567 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003568 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003569 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003570 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003571 Result += ",0";
3572 else {
3573 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003574 Result += ",sizeof(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003575 Result += CDecl->getNameAsString();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003576 if (LangOpts.Microsoft)
3577 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003578 Result += ")";
3579 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003580 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00003581 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003582 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003583 Result += "\n\t";
3584 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003585 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003586 Result += ",0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003587 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroff946a6932008-03-11 00:12:29 +00003588 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003589 Result += CDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003590 Result += ", 0\n\t";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003591 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003592 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003593 Result += ",0,0";
Chris Lattnercafeb352009-02-20 18:18:36 +00003594 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003595 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003596 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003597 Result += ", 0,0\n";
3598 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003599 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003600 Result += ",0,0,0\n";
3601 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003602}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003603
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003604/// RewriteImplementations - This routine rewrites all method implementations
3605/// and emits meta-data.
3606
Steve Narofface66252008-11-13 20:07:04 +00003607void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003608 int ClsDefCount = ClassImplementation.size();
3609 int CatDefCount = CategoryImplementation.size();
Mike Stump1eb44332009-09-09 15:08:12 +00003610
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003611 // Rewrite implemented methods
3612 for (int i = 0; i < ClsDefCount; i++)
3613 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00003614
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003615 for (int i = 0; i < CatDefCount; i++)
3616 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00003617}
Mike Stump1eb44332009-09-09 15:08:12 +00003618
Steve Narofface66252008-11-13 20:07:04 +00003619void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3620 int ClsDefCount = ClassImplementation.size();
3621 int CatDefCount = CategoryImplementation.size();
3622
Steve Naroff5df5b762008-05-07 21:23:49 +00003623 // This is needed for determining instance variable offsets.
Mike Stump1eb44332009-09-09 15:08:12 +00003624 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003625 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003626 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003627 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003628
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003629 // For each implemented category, write out all its meta data.
3630 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003631 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroff621edce2009-04-29 16:37:50 +00003632
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003633 // Write objc_symtab metadata
3634 /*
3635 struct _objc_symtab
3636 {
3637 long sel_ref_cnt;
3638 SEL *refs;
3639 short cls_def_cnt;
3640 short cat_def_cnt;
3641 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump1eb44332009-09-09 15:08:12 +00003642 };
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003643 */
Mike Stump1eb44332009-09-09 15:08:12 +00003644
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003645 Result += "\nstruct _objc_symtab {\n";
3646 Result += "\tlong sel_ref_cnt;\n";
3647 Result += "\tSEL *refs;\n";
3648 Result += "\tshort cls_def_cnt;\n";
3649 Result += "\tshort cat_def_cnt;\n";
3650 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3651 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003652
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003653 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00003654 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003655 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003656 + ", " + utostr(CatDefCount) + "\n";
3657 for (int i = 0; i < ClsDefCount; i++) {
3658 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003659 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003660 Result += "\n";
3661 }
Mike Stump1eb44332009-09-09 15:08:12 +00003662
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003663 for (int i = 0; i < CatDefCount; i++) {
3664 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003665 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003666 Result += "_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003667 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003668 Result += "\n";
3669 }
Mike Stump1eb44332009-09-09 15:08:12 +00003670
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003671 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003672
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003673 // Write objc_module metadata
Mike Stump1eb44332009-09-09 15:08:12 +00003674
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003675 /*
3676 struct _objc_module {
3677 long version;
3678 long size;
3679 const char *name;
3680 struct _objc_symtab *symtab;
3681 }
3682 */
Mike Stump1eb44332009-09-09 15:08:12 +00003683
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003684 Result += "\nstruct _objc_module {\n";
3685 Result += "\tlong version;\n";
3686 Result += "\tlong size;\n";
3687 Result += "\tconst char *name;\n";
3688 Result += "\tstruct _objc_symtab *symtab;\n";
3689 Result += "};\n\n";
3690 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00003691 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003692 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003693 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003694 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003695
3696 if (LangOpts.Microsoft) {
Steve Naroff621edce2009-04-29 16:37:50 +00003697 if (ProtocolExprDecls.size()) {
3698 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
3699 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003700 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00003701 E = ProtocolExprDecls.end(); I != E; ++I) {
3702 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
3703 Result += (*I)->getNameAsString();
3704 Result += " = &_OBJC_PROTOCOL_";
3705 Result += (*I)->getNameAsString();
3706 Result += ";\n";
3707 }
3708 Result += "#pragma data_seg(pop)\n\n";
3709 }
Steve Naroff4f943c22008-03-10 20:43:59 +00003710 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00003711 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003712 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3713 Result += "&_OBJC_MODULES;\n";
3714 Result += "#pragma data_seg(pop)\n\n";
3715 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003716}
Chris Lattner311ff022007-10-16 22:36:42 +00003717
Steve Naroff54055232008-10-27 17:20:55 +00003718std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3719 const char *funcName,
3720 std::string Tag) {
3721 const FunctionType *AFT = CE->getFunctionType();
3722 QualType RT = AFT->getResultType();
3723 std::string StructRef = "struct " + Tag;
3724 std::string S = "static " + RT.getAsString() + " __" +
3725 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003726
Steve Naroff54055232008-10-27 17:20:55 +00003727 BlockDecl *BD = CE->getBlockDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00003728
Douglas Gregor72564e72009-02-26 23:50:07 +00003729 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003730 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Naroffdf8570d2009-02-02 17:19:26 +00003731 // block (to reference imported block decl refs).
3732 S += "(" + StructRef + " *__cself)";
Steve Naroff54055232008-10-27 17:20:55 +00003733 } else if (BD->param_empty()) {
3734 S += "(" + StructRef + " *__cself)";
3735 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00003736 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff54055232008-10-27 17:20:55 +00003737 assert(FT && "SynthesizeBlockFunc: No function proto");
3738 S += '(';
3739 // first add the implicit argument.
3740 S += StructRef + " *__cself, ";
3741 std::string ParamStr;
3742 for (BlockDecl::param_iterator AI = BD->param_begin(),
3743 E = BD->param_end(); AI != E; ++AI) {
3744 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003745 ParamStr = (*AI)->getNameAsString();
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00003746 (*AI)->getType().getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00003747 S += ParamStr;
3748 }
3749 if (FT->isVariadic()) {
3750 if (!BD->param_empty()) S += ", ";
3751 S += "...";
3752 }
3753 S += ')';
3754 }
3755 S += " {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003756
Steve Naroff54055232008-10-27 17:20:55 +00003757 // Create local declarations to avoid rewriting all closure decl ref exprs.
3758 // First, emit a declaration for all "by ref" decls.
Mike Stump1eb44332009-09-09 15:08:12 +00003759 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003760 E = BlockByRefDecls.end(); I != E; ++I) {
3761 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003762 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00003763 std::string TypeString = "struct __Block_byref_" + Name + " *";
3764 Name = TypeString + Name;
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003765 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003766 }
Steve Naroff54055232008-10-27 17:20:55 +00003767 // Next, emit a declaration for all "by copy" declarations.
Mike Stump1eb44332009-09-09 15:08:12 +00003768 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003769 E = BlockByCopyDecls.end(); I != E; ++I) {
3770 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003771 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003772 // Handle nested closure invocation. For example:
3773 //
3774 // void (^myImportedClosure)(void);
3775 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00003776 //
Steve Naroff54055232008-10-27 17:20:55 +00003777 // void (^anotherClosure)(void);
3778 // anotherClosure = ^(void) {
3779 // myImportedClosure(); // import and invoke the closure
3780 // };
3781 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003782 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00003783 S += "struct __block_impl *";
3784 else
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00003785 (*I)->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003786 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff54055232008-10-27 17:20:55 +00003787 }
3788 std::string RewrittenStr = RewrittenBlockExprs[CE];
3789 const char *cstr = RewrittenStr.c_str();
3790 while (*cstr++ != '{') ;
3791 S += cstr;
3792 S += "\n";
3793 return S;
3794}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003795
Steve Naroff54055232008-10-27 17:20:55 +00003796std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3797 const char *funcName,
3798 std::string Tag) {
3799 std::string StructRef = "struct " + Tag;
3800 std::string S = "static void __";
Mike Stump1eb44332009-09-09 15:08:12 +00003801
Steve Naroff54055232008-10-27 17:20:55 +00003802 S += funcName;
3803 S += "_block_copy_" + utostr(i);
3804 S += "(" + StructRef;
3805 S += "*dst, " + StructRef;
3806 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00003807 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003808 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00003809 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003810 S += (*I)->getNameAsString();
Steve Naroff47a24222008-12-11 20:51:38 +00003811 S += ", (void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003812 S += (*I)->getNameAsString();
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00003813 if (BlockByRefDecls.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00003814 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00003815 else
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00003816 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00003817 }
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00003818 S += "}\n";
3819
Steve Naroff54055232008-10-27 17:20:55 +00003820 S += "\nstatic void __";
3821 S += funcName;
3822 S += "_block_dispose_" + utostr(i);
3823 S += "(" + StructRef;
3824 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00003825 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003826 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00003827 S += "_Block_object_dispose((void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003828 S += (*I)->getNameAsString();
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00003829 if (BlockByRefDecls.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00003830 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00003831 else
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00003832 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00003833 }
Mike Stump1eb44332009-09-09 15:08:12 +00003834 S += "}\n";
Steve Naroff54055232008-10-27 17:20:55 +00003835 return S;
3836}
3837
Steve Naroff01aec112009-12-06 21:14:13 +00003838std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3839 std::string Desc) {
Steve Naroffced80a82008-10-30 12:09:33 +00003840 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00003841 std::string Constructor = " " + Tag;
Mike Stump1eb44332009-09-09 15:08:12 +00003842
Steve Naroff54055232008-10-27 17:20:55 +00003843 S += " {\n struct __block_impl impl;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003844 S += " struct " + Desc;
3845 S += "* Desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003846
Steve Naroff01aec112009-12-06 21:14:13 +00003847 Constructor += "(void *fp, "; // Invoke function pointer.
3848 Constructor += "struct " + Desc; // Descriptor pointer.
3849 Constructor += " *desc";
Mike Stump1eb44332009-09-09 15:08:12 +00003850
Steve Naroff54055232008-10-27 17:20:55 +00003851 if (BlockDeclRefs.size()) {
3852 // Output all "by copy" declarations.
Mike Stump1eb44332009-09-09 15:08:12 +00003853 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003854 E = BlockByCopyDecls.end(); I != E; ++I) {
3855 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003856 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003857 std::string ArgName = "_" + FieldName;
3858 // Handle nested closure invocation. For example:
3859 //
3860 // void (^myImportedBlock)(void);
3861 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00003862 //
Steve Naroff54055232008-10-27 17:20:55 +00003863 // void (^anotherBlock)(void);
3864 // anotherBlock = ^(void) {
3865 // myImportedBlock(); // import and invoke the closure
3866 // };
3867 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003868 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00003869 S += "struct __block_impl *";
3870 Constructor += ", void *" + ArgName;
3871 } else {
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00003872 (*I)->getType().getAsStringInternal(FieldName, Context->PrintingPolicy);
3873 (*I)->getType().getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00003874 Constructor += ", " + ArgName;
3875 }
3876 S += FieldName + ";\n";
3877 }
3878 // Output all "by ref" declarations.
Mike Stump1eb44332009-09-09 15:08:12 +00003879 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003880 E = BlockByRefDecls.end(); I != E; ++I) {
3881 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003882 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003883 std::string ArgName = "_" + FieldName;
3884 // Handle nested closure invocation. For example:
3885 //
3886 // void (^myImportedBlock)(void);
3887 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00003888 //
Steve Naroff54055232008-10-27 17:20:55 +00003889 // void (^anotherBlock)(void);
3890 // anotherBlock = ^(void) {
3891 // myImportedBlock(); // import and invoke the closure
3892 // };
3893 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003894 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00003895 S += "struct __block_impl *";
3896 Constructor += ", void *" + ArgName;
3897 } else {
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00003898 std::string TypeString = "struct __Block_byref_" + FieldName;
3899 TypeString += " *";
3900 FieldName = TypeString + FieldName;
3901 ArgName = TypeString + ArgName;
Steve Naroff54055232008-10-27 17:20:55 +00003902 Constructor += ", " + ArgName;
3903 }
3904 S += FieldName + "; // by ref\n";
3905 }
3906 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00003907 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00003908 if (GlobalVarDecl)
3909 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3910 else
3911 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003912 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003913
Steve Naroff01aec112009-12-06 21:14:13 +00003914 Constructor += " Desc = desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003915
Steve Naroff54055232008-10-27 17:20:55 +00003916 // Initialize all "by copy" arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00003917 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003918 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003919 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003920 Constructor += " ";
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003921 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00003922 Constructor += Name + " = (struct __block_impl *)_";
3923 else
3924 Constructor += Name + " = _";
3925 Constructor += Name + ";\n";
3926 }
3927 // Initialize all "by ref" arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00003928 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003929 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003930 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003931 Constructor += " ";
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003932 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00003933 Constructor += Name + " = (struct __block_impl *)_";
3934 else
3935 Constructor += Name + " = _";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00003936 Constructor += Name + "->__forwarding;\n";
Steve Naroff54055232008-10-27 17:20:55 +00003937 }
3938 } else {
3939 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00003940 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00003941 if (GlobalVarDecl)
3942 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3943 else
3944 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003945 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3946 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00003947 }
3948 Constructor += " ";
3949 Constructor += "}\n";
3950 S += Constructor;
3951 S += "};\n";
3952 return S;
3953}
3954
Steve Naroff01aec112009-12-06 21:14:13 +00003955std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
3956 std::string ImplTag, int i,
3957 const char *FunName,
3958 unsigned hasCopy) {
3959 std::string S = "\nstatic struct " + DescTag;
3960
3961 S += " {\n unsigned long reserved;\n";
3962 S += " unsigned long Block_size;\n";
3963 if (hasCopy) {
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00003964 S += " void (*copy)(struct ";
3965 S += ImplTag; S += "*, struct ";
3966 S += ImplTag; S += "*);\n";
3967
3968 S += " void (*dispose)(struct ";
3969 S += ImplTag; S += "*);\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003970 }
3971 S += "} ";
3972
3973 S += DescTag + "_DATA = { 0, sizeof(struct ";
3974 S += ImplTag + ")";
3975 if (hasCopy) {
3976 S += ", __" + std::string(FunName) + "_block_copy_" + utostr(i);
3977 S += ", __" + std::string(FunName) + "_block_dispose_" + utostr(i);
3978 }
3979 S += "};\n";
3980 return S;
3981}
3982
Steve Naroff54055232008-10-27 17:20:55 +00003983void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3984 const char *FunName) {
3985 // Insert closures that were part of the function.
3986 for (unsigned i = 0; i < Blocks.size(); i++) {
3987
3988 CollectBlockDeclRefInfo(Blocks[i]);
3989
Steve Naroff01aec112009-12-06 21:14:13 +00003990 std::string ImplTag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
3991 std::string DescTag = "__" + std::string(FunName) + "_block_desc_" + utostr(i);
Mike Stump1eb44332009-09-09 15:08:12 +00003992
Steve Naroff01aec112009-12-06 21:14:13 +00003993 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff54055232008-10-27 17:20:55 +00003994
3995 InsertText(FunLocStart, CI.c_str(), CI.size());
3996
Steve Naroff01aec112009-12-06 21:14:13 +00003997 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump1eb44332009-09-09 15:08:12 +00003998
Steve Naroff54055232008-10-27 17:20:55 +00003999 InsertText(FunLocStart, CF.c_str(), CF.size());
4000
4001 if (ImportedBlockDecls.size()) {
Steve Naroff01aec112009-12-06 21:14:13 +00004002 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Steve Naroff54055232008-10-27 17:20:55 +00004003 InsertText(FunLocStart, HF.c_str(), HF.size());
4004 }
Steve Naroff01aec112009-12-06 21:14:13 +00004005 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4006 ImportedBlockDecls.size() > 0);
4007 InsertText(FunLocStart, BD.c_str(), BD.size());
Mike Stump1eb44332009-09-09 15:08:12 +00004008
Steve Naroff54055232008-10-27 17:20:55 +00004009 BlockDeclRefs.clear();
4010 BlockByRefDecls.clear();
4011 BlockByCopyDecls.clear();
4012 BlockCallExprs.clear();
4013 ImportedBlockDecls.clear();
4014 }
4015 Blocks.clear();
4016 RewrittenBlockExprs.clear();
4017}
4018
4019void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4020 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner8ec03f52008-11-24 03:54:41 +00004021 const char *FuncName = FD->getNameAsCString();
Mike Stump1eb44332009-09-09 15:08:12 +00004022
Steve Naroff54055232008-10-27 17:20:55 +00004023 SynthesizeBlockLiterals(FunLocStart, FuncName);
4024}
4025
4026void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00004027 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4028 //SourceLocation FunLocStart = MD->getLocStart();
4029 // FIXME: This hack works around a bug in Rewrite.InsertText().
4030 SourceLocation FunLocStart = MD->getLocStart().getFileLocWithOffset(-1);
Chris Lattner077bf5e2008-11-24 03:33:13 +00004031 std::string FuncName = MD->getSelector().getAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004032 // Convert colons to underscores.
4033 std::string::size_type loc = 0;
4034 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4035 FuncName.replace(loc, 1, "_");
Mike Stump1eb44332009-09-09 15:08:12 +00004036
Steve Naroff54055232008-10-27 17:20:55 +00004037 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
4038}
4039
4040void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
4041 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4042 CI != E; ++CI)
4043 if (*CI) {
4044 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4045 GetBlockDeclRefExprs(CBE->getBody());
4046 else
4047 GetBlockDeclRefExprs(*CI);
4048 }
4049 // Handle specific things.
4050 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
4051 // FIXME: Handle enums.
4052 if (!isa<FunctionDecl>(CDRE->getDecl()))
4053 BlockDeclRefs.push_back(CDRE);
4054 return;
4055}
4056
4057void RewriteObjC::GetBlockCallExprs(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 GetBlockCallExprs(CBE->getBody());
4063 else
4064 GetBlockCallExprs(*CI);
4065 }
Mike Stump1eb44332009-09-09 15:08:12 +00004066
Steve Naroff54055232008-10-27 17:20:55 +00004067 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
4068 if (CE->getCallee()->getType()->isBlockPointerType()) {
4069 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
4070 }
4071 }
4072 return;
4073}
4074
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004075Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff54055232008-10-27 17:20:55 +00004076 // Navigate to relevant type information.
Steve Naroff54055232008-10-27 17:20:55 +00004077 const BlockPointerType *CPT = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004078
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004079 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004080 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004081 } else if (const BlockDeclRefExpr *CDRE =
4082 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004083 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004084 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004085 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004086 }
4087 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4088 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4089 }
4090 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4091 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4092 else if (const ConditionalOperator *CEXPR =
4093 dyn_cast<ConditionalOperator>(BlockExp)) {
4094 Expr *LHSExp = CEXPR->getLHS();
4095 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4096 Expr *RHSExp = CEXPR->getRHS();
4097 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4098 Expr *CONDExp = CEXPR->getCond();
4099 ConditionalOperator *CondExpr =
4100 new (Context) ConditionalOperator(CONDExp,
4101 SourceLocation(), cast<Expr>(LHSStmt),
4102 SourceLocation(), cast<Expr>(RHSStmt),
4103 Exp->getType());
4104 return CondExpr;
Fariborz Jahaniane24b22b2009-12-18 01:15:21 +00004105 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4106 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004107 } else {
4108 assert(1 && "RewriteBlockClass: Bad type");
4109 }
4110 assert(CPT && "RewriteBlockClass: Bad type");
John McCall183700f2009-09-21 23:43:11 +00004111 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff54055232008-10-27 17:20:55 +00004112 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor72564e72009-02-26 23:50:07 +00004113 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff54055232008-10-27 17:20:55 +00004114 // FTP will be null for closures that don't take arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004115
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004116 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
4117 SourceLocation(),
4118 &Context->Idents.get("__block_impl"));
4119 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00004120
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004121 // Generate a funky cast.
4122 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00004123
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004124 // Push the block argument type.
4125 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00004126 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004127 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004128 E = FTP->arg_type_end(); I && (I != E); ++I) {
4129 QualType t = *I;
4130 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004131 if (isTopLevelBlockPointerType(t)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004132 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004133 t = Context->getPointerType(BPT->getPointeeType());
4134 }
4135 ArgTypes.push_back(t);
4136 }
Steve Naroff54055232008-10-27 17:20:55 +00004137 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004138 // Now do the pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00004139 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004140 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00004141
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004142 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump1eb44332009-09-09 15:08:12 +00004143
4144 CastExpr *BlkCast = new (Context) CStyleCastExpr(PtrBlock,
Anders Carlssoncdef2b72009-07-31 00:48:10 +00004145 CastExpr::CK_Unknown,
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004146 const_cast<Expr*>(BlockExp),
Ted Kremenek8189cde2009-02-07 01:47:29 +00004147 PtrBlock, SourceLocation(),
4148 SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004149 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004150 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4151 BlkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004152 //PE->dump();
Mike Stump1eb44332009-09-09 15:08:12 +00004153
Douglas Gregor44b43212008-12-11 16:49:14 +00004154 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00004155 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004156 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004157 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4158 FD->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00004159
Anders Carlssoncdef2b72009-07-31 00:48:10 +00004160 CastExpr *FunkCast = new (Context) CStyleCastExpr(PtrToFuncCastType,
4161 CastExpr::CK_Unknown, ME,
Ted Kremenek8189cde2009-02-07 01:47:29 +00004162 PtrToFuncCastType,
4163 SourceLocation(),
4164 SourceLocation());
4165 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump1eb44332009-09-09 15:08:12 +00004166
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004167 llvm::SmallVector<Expr*, 8> BlkExprs;
4168 // Add the implicit argument.
4169 BlkExprs.push_back(BlkCast);
4170 // Add the user arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004171 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004172 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004173 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00004174 }
Ted Kremenek668bf912009-02-09 20:51:47 +00004175 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4176 BlkExprs.size(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00004177 Exp->getType(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004178 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00004179}
4180
4181void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004182 Stmt *BlockCall = SynthesizeBlockCall(Exp, Exp->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004183 ReplaceStmt(Exp, BlockCall);
Steve Naroff54055232008-10-27 17:20:55 +00004184}
4185
Steve Naroff621edce2009-04-29 16:37:50 +00004186// We need to return the rewritten expression to handle cases where the
4187// BlockDeclRefExpr is embedded in another expression being rewritten.
4188// For example:
4189//
4190// int main() {
4191// __block Foo *f;
4192// __block int i;
Mike Stump1eb44332009-09-09 15:08:12 +00004193//
Steve Naroff621edce2009-04-29 16:37:50 +00004194// void (^myblock)() = ^() {
4195// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4196// i = 77;
4197// };
4198//}
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004199Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanianbbf37e22009-12-23 19:26:34 +00004200 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004201 // for each DeclRefExp where BYREFVAR is name of the variable.
4202 ValueDecl *VD;
4203 bool isArrow = true;
4204 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4205 VD = BDRE->getDecl();
4206 else {
4207 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4208 isArrow = false;
4209 }
4210
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004211 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4212 &Context->Idents.get("__forwarding"),
4213 Context->VoidPtrTy, 0,
4214 /*BitWidth=*/0, /*Mutable=*/true);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004215 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4216 FD, SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004217 FD->getType());
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004218
4219 const char *Name = VD->getNameAsCString();
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004220 FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4221 &Context->Idents.get(Name),
4222 Context->VoidPtrTy, 0,
4223 /*BitWidth=*/0, /*Mutable=*/true);
4224 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004225 DeclRefExp->getType());
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004226
4227
4228
Steve Naroffdf8570d2009-02-02 17:19:26 +00004229 // Need parens to enforce precedence.
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004230 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4231 ME);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004232 ReplaceStmt(DeclRefExp, PE);
Steve Naroff621edce2009-04-29 16:37:50 +00004233 return PE;
Steve Naroff54055232008-10-27 17:20:55 +00004234}
4235
Steve Naroffb2f9e512008-11-03 23:29:32 +00004236void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4237 SourceLocation LocStart = CE->getLParenLoc();
4238 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00004239
4240 // Need to avoid trying to rewrite synthesized casts.
4241 if (LocStart.isInvalid())
4242 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00004243 // Need to avoid trying to rewrite casts contained in macros.
4244 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4245 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004246
Steve Naroff54055232008-10-27 17:20:55 +00004247 const char *startBuf = SM->getCharacterData(LocStart);
4248 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump1eb44332009-09-09 15:08:12 +00004249
Steve Naroff54055232008-10-27 17:20:55 +00004250 // advance the location to startArgList.
4251 const char *argPtr = startBuf;
Mike Stump1eb44332009-09-09 15:08:12 +00004252
Steve Naroff54055232008-10-27 17:20:55 +00004253 while (*argPtr++ && (argPtr < endBuf)) {
4254 switch (*argPtr) {
Mike Stump1eb44332009-09-09 15:08:12 +00004255 case '^':
Steve Naroff54055232008-10-27 17:20:55 +00004256 // Replace the '^' with '*'.
4257 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
4258 ReplaceText(LocStart, 1, "*", 1);
4259 break;
4260 }
4261 }
4262 return;
4263}
4264
4265void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4266 SourceLocation DeclLoc = FD->getLocation();
4267 unsigned parenCount = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004268
Steve Naroff54055232008-10-27 17:20:55 +00004269 // We have 1 or more arguments that have closure pointers.
4270 const char *startBuf = SM->getCharacterData(DeclLoc);
4271 const char *startArgList = strchr(startBuf, '(');
Mike Stump1eb44332009-09-09 15:08:12 +00004272
Steve Naroff54055232008-10-27 17:20:55 +00004273 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004274
Steve Naroff54055232008-10-27 17:20:55 +00004275 parenCount++;
4276 // advance the location to startArgList.
4277 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4278 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump1eb44332009-09-09 15:08:12 +00004279
Steve Naroff54055232008-10-27 17:20:55 +00004280 const char *argPtr = startArgList;
Mike Stump1eb44332009-09-09 15:08:12 +00004281
Steve Naroff54055232008-10-27 17:20:55 +00004282 while (*argPtr++ && parenCount) {
4283 switch (*argPtr) {
Mike Stump1eb44332009-09-09 15:08:12 +00004284 case '^':
Steve Naroff54055232008-10-27 17:20:55 +00004285 // Replace the '^' with '*'.
4286 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
4287 ReplaceText(DeclLoc, 1, "*", 1);
4288 break;
Mike Stump1eb44332009-09-09 15:08:12 +00004289 case '(':
4290 parenCount++;
Steve Naroff54055232008-10-27 17:20:55 +00004291 break;
Mike Stump1eb44332009-09-09 15:08:12 +00004292 case ')':
Steve Naroff54055232008-10-27 17:20:55 +00004293 parenCount--;
4294 break;
4295 }
4296 }
4297 return;
4298}
4299
4300bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004301 const FunctionProtoType *FTP;
Ted Kremenek6217b802009-07-29 21:53:49 +00004302 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004303 if (PT) {
John McCall183700f2009-09-21 23:43:11 +00004304 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004305 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00004306 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004307 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall183700f2009-09-21 23:43:11 +00004308 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004309 }
4310 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004311 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004312 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004313 if (isTopLevelBlockPointerType(*I))
Steve Naroff54055232008-10-27 17:20:55 +00004314 return true;
4315 }
4316 return false;
4317}
4318
Ted Kremenek8189cde2009-02-07 01:47:29 +00004319void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4320 const char *&RParen) {
Steve Naroff54055232008-10-27 17:20:55 +00004321 const char *argPtr = strchr(Name, '(');
4322 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004323
Steve Naroff54055232008-10-27 17:20:55 +00004324 LParen = argPtr; // output the start.
4325 argPtr++; // skip past the left paren.
4326 unsigned parenCount = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004327
Steve Naroff54055232008-10-27 17:20:55 +00004328 while (*argPtr && parenCount) {
4329 switch (*argPtr) {
4330 case '(': parenCount++; break;
4331 case ')': parenCount--; break;
4332 default: break;
4333 }
4334 if (parenCount) argPtr++;
4335 }
4336 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4337 RParen = argPtr; // output the end
4338}
4339
4340void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4341 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4342 RewriteBlockPointerFunctionArgs(FD);
4343 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004344 }
Steve Naroff54055232008-10-27 17:20:55 +00004345 // Handle Variables and Typedefs.
4346 SourceLocation DeclLoc = ND->getLocation();
4347 QualType DeclT;
4348 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4349 DeclT = VD->getType();
4350 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4351 DeclT = TDD->getUnderlyingType();
4352 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4353 DeclT = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00004354 else
Steve Naroff54055232008-10-27 17:20:55 +00004355 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump1eb44332009-09-09 15:08:12 +00004356
Steve Naroff54055232008-10-27 17:20:55 +00004357 const char *startBuf = SM->getCharacterData(DeclLoc);
4358 const char *endBuf = startBuf;
4359 // scan backward (from the decl location) for the end of the previous decl.
4360 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4361 startBuf--;
Mike Stump1eb44332009-09-09 15:08:12 +00004362
Steve Naroff54055232008-10-27 17:20:55 +00004363 // *startBuf != '^' if we are dealing with a pointer to function that
4364 // may take block argument types (which will be handled below).
4365 if (*startBuf == '^') {
4366 // Replace the '^' with '*', computing a negative offset.
4367 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
4368 ReplaceText(DeclLoc, 1, "*", 1);
4369 }
4370 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4371 // Replace the '^' with '*' for arguments.
4372 DeclLoc = ND->getLocation();
4373 startBuf = SM->getCharacterData(DeclLoc);
4374 const char *argListBegin, *argListEnd;
4375 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4376 while (argListBegin < argListEnd) {
4377 if (*argListBegin == '^') {
4378 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
4379 ReplaceText(CaretLoc, 1, "*", 1);
4380 }
4381 argListBegin++;
4382 }
4383 }
4384 return;
4385}
4386
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004387
4388/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4389/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4390/// struct Block_byref_id_object *src) {
4391/// _Block_object_assign (&_dest->object, _src->object,
4392/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4393/// [|BLOCK_FIELD_IS_WEAK]) // object
4394/// _Block_object_assign(&_dest->object, _src->object,
4395/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4396/// [|BLOCK_FIELD_IS_WEAK]) // block
4397/// }
4398/// And:
4399/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4400/// _Block_object_dispose(_src->object,
4401/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4402/// [|BLOCK_FIELD_IS_WEAK]) // object
4403/// _Block_object_dispose(_src->object,
4404/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4405/// [|BLOCK_FIELD_IS_WEAK]) // block
4406/// }
4407
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004408std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4409 int flag) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004410 std::string S;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004411 if (CopyDestroyCache.count(flag) > 0)
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004412 return S;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004413 CopyDestroyCache.insert(flag);
4414 S = "static void __Block_byref_id_object_copy_";
4415 S += utostr(flag);
4416 S += "(void *dst, void *src) {\n";
4417
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004418 // offset into the object pointer is computed as:
4419 // void * + void* + int + int + void* + void *
4420 unsigned IntSize =
4421 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4422 unsigned VoidPtrSize =
4423 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4424
4425 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/8;
4426 S += " _Block_object_assign((char*)dst + ";
4427 S += utostr(offset);
4428 S += ", *(void * *) ((char*)src + ";
4429 S += utostr(offset);
4430 S += "), ";
4431 S += utostr(flag);
4432 S += ");\n}\n";
4433
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004434 S += "static void __Block_byref_id_object_dispose_";
4435 S += utostr(flag);
4436 S += "(void *src) {\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004437 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4438 S += utostr(offset);
4439 S += "), ";
4440 S += utostr(flag);
4441 S += ");\n}\n";
4442 return S;
4443}
4444
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004445/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4446/// the declaration into:
4447/// struct __Block_byref_ND {
4448/// void *__isa; // NULL for everything except __weak pointers
4449/// struct __Block_byref_ND *__forwarding;
4450/// int32_t __flags;
4451/// int32_t __size;
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004452/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4453/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004454/// typex ND;
4455/// };
4456///
4457/// It then replaces declaration of ND variable with:
4458/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4459/// __size=sizeof(struct __Block_byref_ND),
4460/// ND=initializer-if-any};
4461///
4462///
4463void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004464 int flag;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004465 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4466 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00004467 SourceLocation X = ND->getLocEnd();
4468 X = SM->getInstantiationLoc(X);
4469 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004470 std::string Name(ND->getNameAsString());
4471 std::string ByrefType = "struct __Block_byref_";
4472 ByrefType += Name;
4473 ByrefType += " {\n";
4474 ByrefType += " void *__isa;\n";
4475 ByrefType += " struct __Block_byref_" + Name + " *__forwarding;\n";
4476 ByrefType += " int __flags;\n";
4477 ByrefType += " int __size;\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004478 // Add void *__Block_byref_id_object_copy;
4479 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004480 QualType Ty = ND->getType();
4481 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4482 if (HasCopyAndDispose) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004483 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4484 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004485 }
4486
4487 Ty.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004488 ByrefType += " " + Name + ";\n";
4489 ByrefType += "};\n";
4490 // Insert this type in global scope. It is needed by helper function.
4491 assert(CurFunctionDef && "RewriteByRefVar - CurFunctionDef is null");
4492 SourceLocation FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4493 InsertText(FunLocStart, ByrefType.c_str(), ByrefType.size());
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004494 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004495 flag = BLOCK_BYREF_CALLER;
4496 QualType Ty = ND->getType();
4497 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4498 if (Ty->isBlockPointerType())
4499 flag |= BLOCK_FIELD_IS_BLOCK;
4500 else
4501 flag |= BLOCK_FIELD_IS_OBJECT;
4502 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004503 if (!HF.empty())
4504 InsertText(FunLocStart, HF.c_str(), HF.size());
4505 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004506
4507 // struct __Block_byref_ND ND =
4508 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4509 // initializer-if-any};
4510 bool hasInit = (ND->getInit() != 0);
4511 Name = ND->getNameAsString();
4512 ByrefType = "struct __Block_byref_" + Name;
4513 if (!hasInit) {
4514 ByrefType += " " + Name + " = ";
4515 ByrefType += "{0, &" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004516 unsigned flags = 0;
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004517 if (HasCopyAndDispose)
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004518 flags |= BLOCK_HAS_COPY_DISPOSE;
4519 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004520 ByrefType += ", ";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004521 ByrefType += "sizeof(struct __Block_byref_" + Name + ")";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004522 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004523 ByrefType += ", __Block_byref_id_object_copy_";
4524 ByrefType += utostr(flag);
4525 ByrefType += ", __Block_byref_id_object_dispose_";
4526 ByrefType += utostr(flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004527 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004528 ByrefType += "};\n";
4529 ReplaceText(DeclLoc, endBuf-startBuf+Name.size(),
4530 ByrefType.c_str(), ByrefType.size());
4531 }
4532 else {
4533 SourceLocation startLoc = ND->getInit()->getLocStart();
4534 ByrefType += " " + Name;
4535 ReplaceText(DeclLoc, endBuf-startBuf,
4536 ByrefType.c_str(), ByrefType.size());
4537 ByrefType = " = {0, &" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004538 unsigned flags = 0;
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004539 if (HasCopyAndDispose)
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004540 flags |= BLOCK_HAS_COPY_DISPOSE;
4541 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004542 ByrefType += ", ";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004543 ByrefType += "sizeof(struct __Block_byref_" + Name + "), ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004544 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004545 ByrefType += "__Block_byref_id_object_copy_";
4546 ByrefType += utostr(flag);
4547 ByrefType += ", __Block_byref_id_object_dispose_";
4548 ByrefType += utostr(flag);
4549 ByrefType += ", ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004550 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004551 InsertText(startLoc, ByrefType.c_str(), ByrefType.size());
Steve Naroffc5143c52009-12-23 17:24:33 +00004552
4553 // Complete the newly synthesized compound expression by inserting a right
4554 // curly brace before the end of the declaration.
4555 // FIXME: This approach avoids rewriting the initializer expression. It
4556 // also assumes there is only one declarator. For example, the following
4557 // isn't currently supported by this routine (in general):
4558 //
4559 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4560 //
4561 const char *startBuf = SM->getCharacterData(startLoc);
4562 const char *semiBuf = strchr(startBuf, ';');
4563 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4564 SourceLocation semiLoc =
4565 startLoc.getFileLocWithOffset(semiBuf-startBuf);
4566
4567 InsertText(semiLoc, "}", 1);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004568 }
Fariborz Jahanian1be6b462009-12-22 00:48:54 +00004569 return;
4570}
4571
Mike Stump1eb44332009-09-09 15:08:12 +00004572void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00004573 // Add initializers for any closure decl refs.
4574 GetBlockDeclRefExprs(Exp->getBody());
4575 if (BlockDeclRefs.size()) {
4576 // Unique all "by copy" declarations.
4577 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4578 if (!BlockDeclRefs[i]->isByRef())
4579 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
4580 // Unique all "by ref" declarations.
4581 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4582 if (BlockDeclRefs[i]->isByRef()) {
4583 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
4584 }
4585 // Find any imported blocks...they will need special attention.
4586 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00004587 if (BlockDeclRefs[i]->isByRef() ||
4588 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4589 BlockDeclRefs[i]->getType()->isBlockPointerType()) {
Steve Naroff00072682008-11-13 17:40:07 +00004590 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff54055232008-10-27 17:20:55 +00004591 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4592 }
4593 }
4594}
4595
Steve Narofffa15fd92008-10-28 20:29:00 +00004596FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
4597 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor72564e72009-02-26 23:50:07 +00004598 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Mike Stump1eb44332009-09-09 15:08:12 +00004599 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00004600 ID, FType, 0, FunctionDecl::Extern, false,
Douglas Gregor2224f842009-02-25 16:33:18 +00004601 false);
Steve Narofffa15fd92008-10-28 20:29:00 +00004602}
4603
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004604Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004605 Blocks.push_back(Exp);
4606
4607 CollectBlockDeclRefInfo(Exp);
4608 std::string FuncName;
Mike Stump1eb44332009-09-09 15:08:12 +00004609
Steve Narofffa15fd92008-10-28 20:29:00 +00004610 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00004611 FuncName = CurFunctionDef->getNameAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00004612 else if (CurMethodDef) {
Chris Lattner077bf5e2008-11-24 03:33:13 +00004613 FuncName = CurMethodDef->getSelector().getAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00004614 // Convert colons to underscores.
4615 std::string::size_type loc = 0;
4616 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4617 FuncName.replace(loc, 1, "_");
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004618 } else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004619 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump1eb44332009-09-09 15:08:12 +00004620
Steve Narofffa15fd92008-10-28 20:29:00 +00004621 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump1eb44332009-09-09 15:08:12 +00004622
Steve Narofffa15fd92008-10-28 20:29:00 +00004623 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4624 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00004625
Steve Narofffa15fd92008-10-28 20:29:00 +00004626 // Get a pointer to the function type so we can cast appropriately.
4627 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
4628
4629 FunctionDecl *FD;
4630 Expr *NewRep;
Mike Stump1eb44332009-09-09 15:08:12 +00004631
Steve Narofffa15fd92008-10-28 20:29:00 +00004632 // Simulate a contructor call...
4633 FD = SynthBlockInitFunctionDecl(Tag.c_str());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004634 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00004635
Steve Narofffa15fd92008-10-28 20:29:00 +00004636 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00004637
Steve Narofffdc03722008-10-29 21:23:59 +00004638 // Initialize the block function.
Steve Narofffa15fd92008-10-28 20:29:00 +00004639 FD = SynthBlockInitFunctionDecl(Func.c_str());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004640 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
4641 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00004642 CastExpr *castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy,
4643 CastExpr::CK_Unknown, Arg,
Ted Kremenek8189cde2009-02-07 01:47:29 +00004644 Context->VoidPtrTy, SourceLocation(),
4645 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00004646 InitExprs.push_back(castExpr);
4647
Steve Naroff01aec112009-12-06 21:14:13 +00004648 // Initialize the block descriptor.
4649 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump1eb44332009-09-09 15:08:12 +00004650
Steve Naroff01aec112009-12-06 21:14:13 +00004651 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
4652 &Context->Idents.get(DescData.c_str()),
4653 Context->VoidPtrTy, 0,
4654 VarDecl::Static);
4655 UnaryOperator *DescRefExpr = new (Context) UnaryOperator(
4656 new (Context) DeclRefExpr(NewVD,
4657 Context->VoidPtrTy, SourceLocation()),
4658 UnaryOperator::AddrOf,
4659 Context->getPointerType(Context->VoidPtrTy),
4660 SourceLocation());
4661 InitExprs.push_back(DescRefExpr);
4662
Steve Narofffa15fd92008-10-28 20:29:00 +00004663 // Add initializers for any closure decl refs.
4664 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00004665 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00004666 // Output all "by copy" declarations.
Mike Stump1eb44332009-09-09 15:08:12 +00004667 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00004668 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004669 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00004670 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner8ec03f52008-11-24 03:54:41 +00004671 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004672 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004673 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004674 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004675 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00004676 Exp = new (Context) CStyleCastExpr(Context->VoidPtrTy,
4677 CastExpr::CK_Unknown, Arg,
4678 Context->VoidPtrTy,
Anders Carlssoncdef2b72009-07-31 00:48:10 +00004679 SourceLocation(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00004680 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004681 } else {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004682 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004683 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004684 }
Mike Stump1eb44332009-09-09 15:08:12 +00004685 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004686 }
4687 // Output all "by ref" declarations.
Mike Stump1eb44332009-09-09 15:08:12 +00004688 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00004689 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004690 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004691 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4692 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00004693 Context->getPointerType(Exp->getType()),
Steve Narofffdc03722008-10-29 21:23:59 +00004694 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00004695 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004696 }
4697 }
Fariborz Jahanianff127882009-12-23 21:52:32 +00004698 if (ImportedBlockDecls.size()) {
4699 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4700 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff01aec112009-12-06 21:14:13 +00004701 unsigned IntSize =
4702 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanianff127882009-12-23 21:52:32 +00004703 Expr *FlagExp = new (Context) IntegerLiteral(llvm::APInt(IntSize, flag),
4704 Context->IntTy, SourceLocation());
4705 InitExprs.push_back(FlagExp);
Steve Naroff01aec112009-12-06 21:14:13 +00004706 }
Ted Kremenek668bf912009-02-09 20:51:47 +00004707 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4708 FType, SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004709 NewRep = new (Context) UnaryOperator(NewRep, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00004710 Context->getPointerType(NewRep->getType()),
Steve Narofffa15fd92008-10-28 20:29:00 +00004711 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00004712 NewRep = new (Context) CStyleCastExpr(FType, CastExpr::CK_Unknown, NewRep,
Anders Carlssoncdef2b72009-07-31 00:48:10 +00004713 FType, SourceLocation(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00004714 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004715 BlockDeclRefs.clear();
4716 BlockByRefDecls.clear();
4717 BlockByCopyDecls.clear();
4718 ImportedBlockDecls.clear();
4719 return NewRep;
4720}
4721
4722//===----------------------------------------------------------------------===//
4723// Function Body / Expression rewriting
4724//===----------------------------------------------------------------------===//
4725
Steve Naroffc77a6362008-12-04 16:24:46 +00004726// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
4727// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
4728// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
4729// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
4730// Since the rewriter isn't capable of rewriting rewritten code, it's important
4731// we get this right.
4732void RewriteObjC::CollectPropertySetters(Stmt *S) {
4733 // Perform a bottom up traversal of all children.
4734 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4735 CI != E; ++CI)
4736 if (*CI)
4737 CollectPropertySetters(*CI);
4738
4739 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
4740 if (BinOp->isAssignmentOp()) {
4741 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
4742 PropSetters[PRE] = BinOp;
4743 }
4744 }
4745}
4746
Steve Narofffa15fd92008-10-28 20:29:00 +00004747Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump1eb44332009-09-09 15:08:12 +00004748 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00004749 isa<DoStmt>(S) || isa<ForStmt>(S))
4750 Stmts.push_back(S);
4751 else if (isa<ObjCForCollectionStmt>(S)) {
4752 Stmts.push_back(S);
Anders Carlssonfc4020a2009-12-22 06:13:42 +00004753 ++BcLabelCount;
4754 ObjCBcLabelNo.push_back(BcLabelCount);
Steve Narofffa15fd92008-10-28 20:29:00 +00004755 }
Mike Stump1eb44332009-09-09 15:08:12 +00004756
Steve Narofffa15fd92008-10-28 20:29:00 +00004757 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00004758
Steve Narofffa15fd92008-10-28 20:29:00 +00004759 // Perform a bottom up rewrite of all children.
4760 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4761 CI != E; ++CI)
4762 if (*CI) {
4763 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Mike Stump1eb44332009-09-09 15:08:12 +00004764 if (newStmt)
Steve Narofffa15fd92008-10-28 20:29:00 +00004765 *CI = newStmt;
4766 }
Mike Stump1eb44332009-09-09 15:08:12 +00004767
Steve Narofffa15fd92008-10-28 20:29:00 +00004768 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4769 // Rewrite the block body in place.
4770 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Mike Stump1eb44332009-09-09 15:08:12 +00004771
Steve Narofffa15fd92008-10-28 20:29:00 +00004772 // Now we snarf the rewritten text and stash it away for later use.
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004773 std::string Str = Rewrite.getRewritenText(BE->getSourceRange());
4774 RewrittenBlockExprs[BE] = Str;
Mike Stump1eb44332009-09-09 15:08:12 +00004775
Steve Narofffa15fd92008-10-28 20:29:00 +00004776 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
4777 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004778 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00004779 return blockTranscribed;
4780 }
4781 // Handle specific things.
4782 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4783 return RewriteAtEncode(AtEncode);
Mike Stump1eb44332009-09-09 15:08:12 +00004784
Steve Narofffa15fd92008-10-28 20:29:00 +00004785 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
4786 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
4787
Steve Naroffc77a6362008-12-04 16:24:46 +00004788 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
4789 BinaryOperator *BinOp = PropSetters[PropRefExpr];
4790 if (BinOp) {
4791 // Because the rewriter doesn't allow us to rewrite rewritten code,
4792 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroffb619d952008-12-09 12:56:34 +00004793 DisableReplaceStmt = true;
4794 // Save the source range. Even if we disable the replacement, the
4795 // rewritten node will have been inserted into the tree. If the synthesized
4796 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump1eb44332009-09-09 15:08:12 +00004797 // self.errorHandler = handler ? handler :
Steve Naroffb619d952008-12-09 12:56:34 +00004798 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
4799 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroffc77a6362008-12-04 16:24:46 +00004800 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroffb619d952008-12-09 12:56:34 +00004801 DisableReplaceStmt = false;
Steve Naroff4c3580e2008-12-04 23:50:32 +00004802 //
4803 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
4804 // we changed the RHS of BinOp, the rewriter would fail (since it needs
4805 // to see the original expression). Consider this example:
4806 //
4807 // Foo *obj1, *obj2;
4808 //
4809 // obj1.i = [obj2 rrrr];
4810 //
4811 // 'BinOp' for the previous expression looks like:
4812 //
4813 // (BinaryOperator 0x231ccf0 'int' '='
4814 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
4815 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
4816 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
4817 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
4818 //
4819 // 'newStmt' represents the rewritten message expression. For example:
4820 //
4821 // (CallExpr 0x231d300 'id':'struct objc_object *'
4822 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
4823 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
4824 // (CStyleCastExpr 0x231d220 'void *'
4825 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
4826 //
4827 // Note that 'newStmt' is passed to RewritePropertySetter so that it
4828 // can be used as the setter argument. ReplaceStmt() will still 'see'
4829 // the original RHS (since we haven't altered BinOp).
4830 //
Mike Stump1eb44332009-09-09 15:08:12 +00004831 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff4c3580e2008-12-04 23:50:32 +00004832 // node. As a result, we now leak the original AST nodes.
4833 //
Steve Naroffb619d952008-12-09 12:56:34 +00004834 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroffc77a6362008-12-04 16:24:46 +00004835 } else {
4836 return RewritePropertyGetter(PropRefExpr);
Steve Naroff15f081d2008-12-03 00:56:33 +00004837 }
4838 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004839 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4840 return RewriteAtSelector(AtSelector);
Mike Stump1eb44332009-09-09 15:08:12 +00004841
Steve Narofffa15fd92008-10-28 20:29:00 +00004842 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4843 return RewriteObjCStringLiteral(AtString);
Mike Stump1eb44332009-09-09 15:08:12 +00004844
Steve Narofffa15fd92008-10-28 20:29:00 +00004845 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00004846#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00004847 // Before we rewrite it, put the original message expression in a comment.
4848 SourceLocation startLoc = MessExpr->getLocStart();
4849 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00004850
Steve Narofffa15fd92008-10-28 20:29:00 +00004851 const char *startBuf = SM->getCharacterData(startLoc);
4852 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00004853
Steve Narofffa15fd92008-10-28 20:29:00 +00004854 std::string messString;
4855 messString += "// ";
4856 messString.append(startBuf, endBuf-startBuf+1);
4857 messString += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004858
4859 // FIXME: Missing definition of
Steve Narofffa15fd92008-10-28 20:29:00 +00004860 // InsertText(clang::SourceLocation, char const*, unsigned int).
4861 // InsertText(startLoc, messString.c_str(), messString.size());
4862 // Tried this, but it didn't work either...
4863 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00004864#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00004865 return RewriteMessageExpr(MessExpr);
4866 }
Mike Stump1eb44332009-09-09 15:08:12 +00004867
Steve Narofffa15fd92008-10-28 20:29:00 +00004868 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4869 return RewriteObjCTryStmt(StmtTry);
4870
4871 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4872 return RewriteObjCSynchronizedStmt(StmtTry);
4873
4874 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4875 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump1eb44332009-09-09 15:08:12 +00004876
Steve Narofffa15fd92008-10-28 20:29:00 +00004877 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4878 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump1eb44332009-09-09 15:08:12 +00004879
4880 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofffa15fd92008-10-28 20:29:00 +00004881 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump1eb44332009-09-09 15:08:12 +00004882 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofffa15fd92008-10-28 20:29:00 +00004883 OrigStmtRange.getEnd());
4884 if (BreakStmt *StmtBreakStmt =
4885 dyn_cast<BreakStmt>(S))
4886 return RewriteBreakStmt(StmtBreakStmt);
4887 if (ContinueStmt *StmtContinueStmt =
4888 dyn_cast<ContinueStmt>(S))
4889 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00004890
4891 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofffa15fd92008-10-28 20:29:00 +00004892 // and cast exprs.
4893 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4894 // FIXME: What we're doing here is modifying the type-specifier that
4895 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump1eb44332009-09-09 15:08:12 +00004896 // a separate type-specifier that we can rewrite.
Steve Naroff3d7e7862009-12-05 15:55:59 +00004897 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4898 // the context of an ObjCForCollectionStmt. For example:
4899 // NSArray *someArray;
4900 // for (id <FooProtocol> index in someArray) ;
4901 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4902 // and it depends on the original text locations/positions.
Benjamin Kramerb2041de2009-12-05 22:16:51 +00004903 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
Steve Naroff3d7e7862009-12-05 15:55:59 +00004904 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump1eb44332009-09-09 15:08:12 +00004905
Steve Narofffa15fd92008-10-28 20:29:00 +00004906 // Blocks rewrite rules.
4907 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4908 DI != DE; ++DI) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004909 Decl *SD = *DI;
Steve Narofffa15fd92008-10-28 20:29:00 +00004910 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004911 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004912 RewriteBlockPointerDecl(ND);
Mike Stump1eb44332009-09-09 15:08:12 +00004913 else if (ND->getType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00004914 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004915 if (VarDecl *VD = dyn_cast<VarDecl>(SD))
4916 if (VD->hasAttr<BlocksAttr>())
4917 RewriteByRefVar(VD);
Steve Narofffa15fd92008-10-28 20:29:00 +00004918 }
4919 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004920 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004921 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00004922 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00004923 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4924 }
4925 }
4926 }
Mike Stump1eb44332009-09-09 15:08:12 +00004927
Steve Narofffa15fd92008-10-28 20:29:00 +00004928 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4929 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump1eb44332009-09-09 15:08:12 +00004930
4931 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00004932 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4933 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump1eb44332009-09-09 15:08:12 +00004934 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4935 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004936 && "Statement stack mismatch");
4937 Stmts.pop_back();
4938 }
4939 // Handle blocks rewriting.
4940 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4941 if (BDRE->isByRef())
Steve Naroff621edce2009-04-29 16:37:50 +00004942 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofffa15fd92008-10-28 20:29:00 +00004943 }
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004944 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4945 ValueDecl *VD = DRE->getDecl();
4946 if (VD->hasAttr<BlocksAttr>())
4947 return RewriteBlockDeclRefExpr(DRE);
4948 }
4949
Steve Narofffa15fd92008-10-28 20:29:00 +00004950 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004951 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004952 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004953 ReplaceStmt(S, BlockCall);
4954 return BlockCall;
4955 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004956 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00004957 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004958 RewriteCastExpr(CE);
4959 }
4960#if 0
4961 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00004962 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004963 // Get the new text.
4964 std::string SStr;
4965 llvm::raw_string_ostream Buf(SStr);
Eli Friedman3a9eb442009-05-30 05:19:26 +00004966 Replacement->printPretty(Buf, *Context);
Steve Narofffa15fd92008-10-28 20:29:00 +00004967 const std::string &Str = Buf.str();
4968
4969 printf("CAST = %s\n", &Str[0]);
4970 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4971 delete S;
4972 return Replacement;
4973 }
4974#endif
4975 // Return this stmt unmodified.
4976 return S;
4977}
4978
Steve Naroff3d7e7862009-12-05 15:55:59 +00004979void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
4980 for (RecordDecl::field_iterator i = RD->field_begin(),
4981 e = RD->field_end(); i != e; ++i) {
4982 FieldDecl *FD = *i;
4983 if (isTopLevelBlockPointerType(FD->getType()))
4984 RewriteBlockPointerDecl(FD);
4985 if (FD->getType()->isObjCQualifiedIdType() ||
4986 FD->getType()->isObjCQualifiedInterfaceType())
4987 RewriteObjCQualifiedInterfaceTypes(FD);
4988 }
4989}
4990
Steve Narofffa15fd92008-10-28 20:29:00 +00004991/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4992/// main file of the input.
4993void RewriteObjC::HandleDeclInMainFile(Decl *D) {
4994 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffcb735302008-12-17 00:20:22 +00004995 if (FD->isOverloadedOperator())
4996 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004997
Steve Narofffa15fd92008-10-28 20:29:00 +00004998 // Since function prototypes don't have ParmDecl's, we check the function
4999 // prototype. This enables us to rewrite function declarations and
5000 // definitions using the same code.
Douglas Gregor72564e72009-02-26 23:50:07 +00005001 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005002
Sebastian Redld3a413d2009-04-26 20:35:05 +00005003 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00005004 if (CompoundStmt *Body = FD->getCompoundBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005005 CurFunctionDef = FD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005006 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005007 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005008 Body =
5009 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5010 FD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005011 CurrentBody = 0;
5012 if (PropParentMap) {
5013 delete PropParentMap;
5014 PropParentMap = 0;
5015 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005016 // This synthesizes and inserts the block "impl" struct, invoke function,
5017 // and any copy/dispose helper functions.
5018 InsertBlockLiteralsWithinFunction(FD);
5019 CurFunctionDef = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00005020 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005021 return;
5022 }
5023 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00005024 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005025 CurMethodDef = MD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005026 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005027 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005028 Body =
5029 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5030 MD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005031 CurrentBody = 0;
5032 if (PropParentMap) {
5033 delete PropParentMap;
5034 PropParentMap = 0;
5035 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005036 InsertBlockLiteralsWithinMethod(MD);
5037 CurMethodDef = 0;
5038 }
5039 }
5040 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5041 ClassImplementation.push_back(CI);
5042 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5043 CategoryImplementation.push_back(CI);
5044 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
5045 RewriteForwardClassDecl(CD);
5046 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5047 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005048 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005049 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005050 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005051 CheckFunctionPointerDecl(VD->getType(), VD);
5052 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00005053 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005054 RewriteCastExpr(CE);
5055 }
5056 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00005057 } else if (VD->getType()->isRecordType()) {
5058 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5059 if (RD->isDefinition())
5060 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005061 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005062 if (VD->getInit()) {
5063 GlobalVarDecl = VD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005064 CollectPropertySetters(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005065 CurrentBody = VD->getInit();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005066 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005067 CurrentBody = 0;
5068 if (PropParentMap) {
5069 delete PropParentMap;
5070 PropParentMap = 0;
5071 }
Mike Stump1eb44332009-09-09 15:08:12 +00005072 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00005073 VD->getNameAsCString());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005074 GlobalVarDecl = 0;
5075
5076 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00005077 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005078 RewriteCastExpr(CE);
5079 }
5080 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005081 return;
5082 }
5083 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005084 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005085 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005086 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005087 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
Steve Naroff3d7e7862009-12-05 15:55:59 +00005088 else if (TD->getUnderlyingType()->isRecordType()) {
5089 RecordDecl *RD = TD->getUnderlyingType()->getAs<RecordType>()->getDecl();
5090 if (RD->isDefinition())
5091 RewriteRecordBody(RD);
5092 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005093 return;
5094 }
5095 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroff3d7e7862009-12-05 15:55:59 +00005096 if (RD->isDefinition())
5097 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005098 return;
5099 }
5100 // Nothing yet.
5101}
5102
Chris Lattnerdacbc5d2009-03-28 04:11:33 +00005103void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005104 // Get the top-level buffer that this corresponds to.
Mike Stump1eb44332009-09-09 15:08:12 +00005105
Steve Narofffa15fd92008-10-28 20:29:00 +00005106 // Rewrite tabs if we care.
5107 //RewriteTabs();
Mike Stump1eb44332009-09-09 15:08:12 +00005108
Steve Narofffa15fd92008-10-28 20:29:00 +00005109 if (Diags.hasErrorOccurred())
5110 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005111
Steve Narofffa15fd92008-10-28 20:29:00 +00005112 RewriteInclude();
Mike Stump1eb44332009-09-09 15:08:12 +00005113
Steve Naroff621edce2009-04-29 16:37:50 +00005114 // Here's a great place to add any extra declarations that may be needed.
5115 // Write out meta data for each @protocol(<expr>).
Mike Stump1eb44332009-09-09 15:08:12 +00005116 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00005117 E = ProtocolExprDecls.end(); I != E; ++I)
5118 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5119
Mike Stump1eb44332009-09-09 15:08:12 +00005120 InsertText(SM->getLocForStartOfFile(MainFileID),
Steve Narofffa15fd92008-10-28 20:29:00 +00005121 Preamble.c_str(), Preamble.size(), false);
Steve Naroff0aab7962008-11-14 14:10:01 +00005122 if (ClassImplementation.size() || CategoryImplementation.size())
5123 RewriteImplementations();
Steve Naroff621edce2009-04-29 16:37:50 +00005124
Steve Narofffa15fd92008-10-28 20:29:00 +00005125 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5126 // we are done.
Mike Stump1eb44332009-09-09 15:08:12 +00005127 if (const RewriteBuffer *RewriteBuf =
Steve Narofffa15fd92008-10-28 20:29:00 +00005128 Rewrite.getRewriteBufferFor(MainFileID)) {
5129 //printf("Changed:\n");
5130 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5131 } else {
5132 fprintf(stderr, "No changes\n");
5133 }
Steve Narofface66252008-11-13 20:07:04 +00005134
Steve Naroff621edce2009-04-29 16:37:50 +00005135 if (ClassImplementation.size() || CategoryImplementation.size() ||
5136 ProtocolExprDecls.size()) {
Steve Naroff0aab7962008-11-14 14:10:01 +00005137 // Rewrite Objective-c meta data*
5138 std::string ResultStr;
5139 SynthesizeMetaDataIntoBuffer(ResultStr);
5140 // Emit metadata.
5141 *OutFile << ResultStr;
5142 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005143 OutFile->flush();
5144}
5145