blob: 3000d7760554cd25334e2264e0728a3f85a85aad [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;
Fariborz Jahanianf292fcf2010-01-07 22:51:18 +0000117 bool objc_impl_method;
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000118
Steve Naroffba92b2e2008-03-27 22:29:16 +0000119 std::string Preamble;
Steve Naroff54055232008-10-27 17:20:55 +0000120
121 // Block expressions.
122 llvm::SmallVector<BlockExpr *, 32> Blocks;
123 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
124 llvm::DenseMap<BlockDeclRefExpr *, CallExpr *> BlockCallExprs;
Mike Stump1eb44332009-09-09 15:08:12 +0000125
Steve Naroff54055232008-10-27 17:20:55 +0000126 // Block related declarations.
127 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDecls;
128 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDecls;
129 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
130
131 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
132
Steve Naroffc77a6362008-12-04 16:24:46 +0000133 // This maps a property to it's assignment statement.
134 llvm::DenseMap<ObjCPropertyRefExpr *, BinaryOperator *> PropSetters;
Steve Naroff8599e7a2008-12-08 16:43:47 +0000135 // This maps a property to it's synthesied message expression.
136 // This allows us to rewrite chained getters (e.g. o.a.b.c).
137 llvm::DenseMap<ObjCPropertyRefExpr *, Stmt *> PropGetters;
Mike Stump1eb44332009-09-09 15:08:12 +0000138
Steve Naroff4c3580e2008-12-04 23:50:32 +0000139 // This maps an original source AST to it's rewritten form. This allows
140 // us to avoid rewriting the same node twice (which is very uncommon).
141 // This is needed to support some of the exotic property rewriting.
142 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Naroff15f081d2008-12-03 00:56:33 +0000143
Steve Naroff54055232008-10-27 17:20:55 +0000144 FunctionDecl *CurFunctionDef;
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000145 VarDecl *GlobalVarDecl;
Mike Stump1eb44332009-09-09 15:08:12 +0000146
Steve Naroffb619d952008-12-09 12:56:34 +0000147 bool DisableReplaceStmt;
Mike Stump1eb44332009-09-09 15:08:12 +0000148
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000149 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +0000150 public:
Ted Kremeneke3a61982008-05-31 20:11:04 +0000151 virtual void Initialize(ASTContext &context);
152
Chris Lattnerf04da132007-10-24 17:06:59 +0000153 // Top Level Driver code.
Chris Lattner682bf922009-03-29 16:50:03 +0000154 virtual void HandleTopLevelDecl(DeclGroupRef D) {
155 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I)
156 HandleTopLevelSingleDecl(*I);
157 }
158 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000159 void HandleDeclInMainFile(Decl *D);
Eli Friedman66d6f042009-05-18 22:20:00 +0000160 RewriteObjC(std::string inFile, llvm::raw_ostream *OS,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000161 Diagnostic &D, const LangOptions &LOpts,
162 bool silenceMacroWarn);
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000163
164 ~RewriteObjC() {}
Mike Stump1eb44332009-09-09 15:08:12 +0000165
Chris Lattnerdacbc5d2009-03-28 04:11:33 +0000166 virtual void HandleTranslationUnit(ASTContext &C);
Mike Stump1eb44332009-09-09 15:08:12 +0000167
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000168 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000169 Stmt *ReplacingStmt = ReplacedNodes[Old];
Mike Stump1eb44332009-09-09 15:08:12 +0000170
Steve Naroff4c3580e2008-12-04 23:50:32 +0000171 if (ReplacingStmt)
172 return; // We can't rewrite the same node twice.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000173
Steve Naroffb619d952008-12-09 12:56:34 +0000174 if (DisableReplaceStmt)
175 return; // Used when rewriting the assignment of a property setter.
176
Steve Naroff4c3580e2008-12-04 23:50:32 +0000177 // If replacement succeeded or warning disabled return with no warning.
178 if (!Rewrite.ReplaceStmt(Old, New)) {
179 ReplacedNodes[Old] = New;
180 return;
181 }
182 if (SilenceRewriteMacroWarning)
183 return;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000184 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
185 << Old->getSourceRange();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000186 }
Steve Naroffb619d952008-12-09 12:56:34 +0000187
188 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
189 // Measaure the old text.
190 int Size = Rewrite.getRangeSize(SrcRange);
191 if (Size == -1) {
192 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
193 << Old->getSourceRange();
194 return;
195 }
196 // Get the new text.
197 std::string SStr;
198 llvm::raw_string_ostream S(SStr);
Chris Lattnere4f21422009-06-30 01:26:17 +0000199 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
Steve Naroffb619d952008-12-09 12:56:34 +0000200 const std::string &Str = S.str();
201
202 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbard7407dc2009-08-19 19:10:30 +0000203 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroffb619d952008-12-09 12:56:34 +0000204 ReplacedNodes[Old] = New;
205 return;
206 }
207 if (SilenceRewriteMacroWarning)
208 return;
209 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
210 << Old->getSourceRange();
211 }
212
Steve Naroffba92b2e2008-03-27 22:29:16 +0000213 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
214 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000215 // If insertion succeeded or warning disabled return with no warning.
Daniel Dunbard7407dc2009-08-19 19:10:30 +0000216 if (!Rewrite.InsertText(Loc, llvm::StringRef(StrData, StrLen),
217 InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000218 SilenceRewriteMacroWarning)
219 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000220
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000221 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
222 }
Mike Stump1eb44332009-09-09 15:08:12 +0000223
Chris Lattneraadaf782008-01-31 19:51:04 +0000224 void RemoveText(SourceLocation Loc, unsigned StrLen) {
225 // If removal succeeded or warning disabled return with no warning.
226 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
227 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000228
Chris Lattneraadaf782008-01-31 19:51:04 +0000229 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
230 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000231
Chris Lattneraadaf782008-01-31 19:51:04 +0000232 void ReplaceText(SourceLocation Start, unsigned OrigLength,
233 const char *NewStr, unsigned NewLength) {
234 // If removal succeeded or warning disabled return with no warning.
Daniel Dunbard7407dc2009-08-19 19:10:30 +0000235 if (!Rewrite.ReplaceText(Start, OrigLength,
236 llvm::StringRef(NewStr, NewLength)) ||
Chris Lattneraadaf782008-01-31 19:51:04 +0000237 SilenceRewriteMacroWarning)
238 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000239
Chris Lattneraadaf782008-01-31 19:51:04 +0000240 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
241 }
Mike Stump1eb44332009-09-09 15:08:12 +0000242
Chris Lattnerf04da132007-10-24 17:06:59 +0000243 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000244 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000245 void RewriteInclude();
Chris Lattnerf04da132007-10-24 17:06:59 +0000246 void RewriteTabs();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000247 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffa0876e82008-12-02 17:36:43 +0000248 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
249 ObjCImplementationDecl *IMD,
250 ObjCCategoryImplDecl *CID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000251 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000252 void RewriteImplementationDecl(Decl *Dcl);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000253 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
254 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
255 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
256 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
257 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff6327e0d2009-01-11 01:06:09 +0000258 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff09b266e2007-10-30 23:14:51 +0000259 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000260 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroff4f95b752008-07-29 18:15:38 +0000261 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffd5255f52007-11-01 13:24:47 +0000262 bool needToScanForQualifiers(QualType T);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000263 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000264 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000265 QualType getConstantStringStructType();
Steve Naroffbaf58c32008-05-31 14:15:04 +0000266 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Mike Stump1eb44332009-09-09 15:08:12 +0000267
Chris Lattnerf04da132007-10-24 17:06:59 +0000268 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000269 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroffc77a6362008-12-04 16:24:46 +0000270 void CollectPropertySetters(Stmt *S);
Mike Stump1eb44332009-09-09 15:08:12 +0000271
Steve Naroff8599e7a2008-12-08 16:43:47 +0000272 Stmt *CurrentBody;
273 ParentMap *PropParentMap; // created lazily.
Mike Stump1eb44332009-09-09 15:08:12 +0000274
Chris Lattnere64b7772007-10-24 16:57:36 +0000275 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000276 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart);
Steve Naroffc77a6362008-12-04 16:24:46 +0000277 Stmt *RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr);
Mike Stump1eb44332009-09-09 15:08:12 +0000278 Stmt *RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroffb619d952008-12-09 12:56:34 +0000279 SourceRange SrcRange);
Steve Naroffb42f8412007-11-05 14:50:49 +0000280 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000281 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000282 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000283 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffb85e77a2009-12-05 21:43:12 +0000284 void WarnAboutReturnGotoStmts(Stmt *S);
285 void HasReturnStmts(Stmt *S, bool &hasReturns);
286 void RewriteTryReturnStmts(Stmt *S);
287 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000288 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000289 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000290 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
291 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
292 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000293 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
294 SourceLocation OrigEnd);
Mike Stump1eb44332009-09-09 15:08:12 +0000295 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
Steve Naroff934f2762007-10-24 22:48:43 +0000296 Expr **args, unsigned nargs);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000297 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000298 Stmt *RewriteBreakStmt(BreakStmt *S);
299 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000300 void SynthCountByEnumWithState(std::string &buf);
Mike Stump1eb44332009-09-09 15:08:12 +0000301
Steve Naroff09b266e2007-10-30 23:14:51 +0000302 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000303 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000304 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000305 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000306 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000307 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000308 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000309 void SynthSelGetUidFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000310 void SynthSuperContructorFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000311
Chris Lattnerf04da132007-10-24 17:06:59 +0000312 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000313 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000314 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000315
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000316 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000317 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000318
Douglas Gregor653f1b12009-04-23 01:02:12 +0000319 template<typename MethodIterator>
320 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
321 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000322 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000323 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000324 const char *ClassName,
325 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000326
Steve Naroff621edce2009-04-29 16:37:50 +0000327 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
328 const char *prefix,
329 const char *ClassName,
330 std::string &Result);
331 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
Mike Stump1eb44332009-09-09 15:08:12 +0000332 const char *prefix,
Steve Naroff621edce2009-04-29 16:37:50 +0000333 const char *ClassName,
334 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000335 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000336 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000337 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
338 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000339 std::string &Result);
Steve Narofface66252008-11-13 20:07:04 +0000340 void RewriteImplementations();
341 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000342
Steve Naroff54055232008-10-27 17:20:55 +0000343 // Block rewriting.
Mike Stump1eb44332009-09-09 15:08:12 +0000344 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff54055232008-10-27 17:20:55 +0000345 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
Mike Stump1eb44332009-09-09 15:08:12 +0000346
Steve Naroff54055232008-10-27 17:20:55 +0000347 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
348 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
Mike Stump1eb44332009-09-09 15:08:12 +0000349
350 // Block specific rewrite rules.
Steve Naroff54055232008-10-27 17:20:55 +0000351 void RewriteBlockCall(CallExpr *Exp);
352 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000353 void RewriteByRefVar(VarDecl *VD);
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +0000354 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +0000355 Stmt *RewriteBlockDeclRefExpr(Expr *VD);
Steve Naroff54055232008-10-27 17:20:55 +0000356 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Mike Stump1eb44332009-09-09 15:08:12 +0000357
358 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Steve Naroff54055232008-10-27 17:20:55 +0000359 const char *funcName, std::string Tag);
Mike Stump1eb44332009-09-09 15:08:12 +0000360 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Steve Naroff54055232008-10-27 17:20:55 +0000361 const char *funcName, std::string Tag);
Steve Naroff01aec112009-12-06 21:14:13 +0000362 std::string SynthesizeBlockImpl(BlockExpr *CE,
363 std::string Tag, std::string Desc);
364 std::string SynthesizeBlockDescriptor(std::string DescTag,
365 std::string ImplTag,
366 int i, const char *funcName,
367 unsigned hasCopy);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +0000368 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff54055232008-10-27 17:20:55 +0000369 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
370 const char *FunName);
Steve Naroff3d7e7862009-12-05 15:55:59 +0000371 void RewriteRecordBody(RecordDecl *RD);
Mike Stump1eb44332009-09-09 15:08:12 +0000372
Steve Naroff54055232008-10-27 17:20:55 +0000373 void CollectBlockDeclRefInfo(BlockExpr *Exp);
374 void GetBlockCallExprs(Stmt *S);
375 void GetBlockDeclRefExprs(Stmt *S);
Mike Stump1eb44332009-09-09 15:08:12 +0000376
Steve Naroff54055232008-10-27 17:20:55 +0000377 // We avoid calling Type::isBlockPointerType(), since it operates on the
378 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000379 bool isTopLevelBlockPointerType(QualType T) {
380 return isa<BlockPointerType>(T);
381 }
Mike Stump1eb44332009-09-09 15:08:12 +0000382
Steve Naroff54055232008-10-27 17:20:55 +0000383 // FIXME: This predicate seems like it would be useful to add to ASTContext.
384 bool isObjCType(QualType T) {
385 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
386 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000387
Steve Naroff54055232008-10-27 17:20:55 +0000388 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000389
Steve Naroff54055232008-10-27 17:20:55 +0000390 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
391 OCT == Context->getCanonicalType(Context->getObjCClassType()))
392 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000393
Ted Kremenek6217b802009-07-29 21:53:49 +0000394 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000395 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000396 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff54055232008-10-27 17:20:55 +0000397 return true;
398 }
399 return false;
400 }
401 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Ted Kremenek8189cde2009-02-07 01:47:29 +0000402 void GetExtentOfArgList(const char *Name, const char *&LParen,
403 const char *&RParen);
Steve Naroffb2f9e512008-11-03 23:29:32 +0000404 void RewriteCastExpr(CStyleCastExpr *CE);
Mike Stump1eb44332009-09-09 15:08:12 +0000405
Steve Narofffa15fd92008-10-28 20:29:00 +0000406 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000407 Stmt *SynthBlockInitExpr(BlockExpr *Exp);
Mike Stump1eb44332009-09-09 15:08:12 +0000408
Steve Naroff621edce2009-04-29 16:37:50 +0000409 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump1eb44332009-09-09 15:08:12 +0000410 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroff621edce2009-04-29 16:37:50 +0000411 if (From[i] == '"')
412 To += "\\\"";
413 else
414 To += From[i];
415 }
416 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000417 };
418}
419
Mike Stump1eb44332009-09-09 15:08:12 +0000420void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
421 NamedDecl *D) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000422 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000423 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +0000424 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000425 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff54055232008-10-27 17:20:55 +0000426 // All the args are checked/rewritten. Don't call twice!
427 RewriteBlockPointerDecl(D);
428 break;
429 }
430 }
431}
432
433void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000434 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +0000435 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor72564e72009-02-26 23:50:07 +0000436 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff54055232008-10-27 17:20:55 +0000437}
438
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000439static bool IsHeaderFile(const std::string &Filename) {
440 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump1eb44332009-09-09 15:08:12 +0000441
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000442 if (DotPos == std::string::npos) {
443 // no file extension
Mike Stump1eb44332009-09-09 15:08:12 +0000444 return false;
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000445 }
Mike Stump1eb44332009-09-09 15:08:12 +0000446
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000447 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
448 // C header: .h
449 // C++ header: .hh or .H;
450 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump1eb44332009-09-09 15:08:12 +0000451}
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000452
Eli Friedman66d6f042009-05-18 22:20:00 +0000453RewriteObjC::RewriteObjC(std::string inFile, llvm::raw_ostream* OS,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000454 Diagnostic &D, const LangOptions &LOpts,
455 bool silenceMacroWarn)
456 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
457 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Naroffa7b402d2008-03-28 22:26:09 +0000458 IsHeader = IsHeaderFile(inFile);
Mike Stump1eb44332009-09-09 15:08:12 +0000459 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000460 "rewriting sub-expression within a macro (may not be correct)");
Mike Stump1eb44332009-09-09 15:08:12 +0000461 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000462 "rewriter doesn't support user-specified control flow semantics "
463 "for @try/@finally (code may not execute properly)");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000464}
465
Eli Friedmanbce831b2009-05-18 22:29:17 +0000466ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
467 llvm::raw_ostream* OS,
Mike Stump1eb44332009-09-09 15:08:12 +0000468 Diagnostic &Diags,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000469 const LangOptions &LOpts,
470 bool SilenceRewriteMacroWarning) {
471 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere365c502007-11-30 22:25:36 +0000472}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000473
Steve Naroffb29b4272008-04-14 22:03:09 +0000474void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000475 Context = &context;
476 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000477 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000478 MsgSendFunctionDecl = 0;
479 MsgSendSuperFunctionDecl = 0;
480 MsgSendStretFunctionDecl = 0;
481 MsgSendSuperStretFunctionDecl = 0;
482 MsgSendFpretFunctionDecl = 0;
483 GetClassFunctionDecl = 0;
484 GetMetaClassFunctionDecl = 0;
485 SelGetUidFunctionDecl = 0;
486 CFStringFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000487 ConstantStringClassReference = 0;
488 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000489 CurMethodDef = 0;
490 CurFunctionDef = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000491 GlobalVarDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000492 SuperStructDecl = 0;
Steve Naroff621edce2009-04-29 16:37:50 +0000493 ProtocolTypeDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000494 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000495 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000496 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000497 NumObjCStringLiterals = 0;
Steve Naroff68272b82008-12-08 20:01:41 +0000498 PropParentMap = 0;
499 CurrentBody = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000500 DisableReplaceStmt = false;
Fariborz Jahanianf292fcf2010-01-07 22:51:18 +0000501 objc_impl_method = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000502
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000503 // Get the ID and start/end of the main file.
504 MainFileID = SM->getMainFileID();
505 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
506 MainFileStart = MainBuf->getBufferStart();
507 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000508
Chris Lattner2c78b872009-04-14 23:22:57 +0000509 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump1eb44332009-09-09 15:08:12 +0000510
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000511 // declaring objc_selector outside the parameter list removes a silly
512 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000513 if (IsHeader)
Steve Naroff62c26322009-02-03 20:39:18 +0000514 Preamble = "#pragma once\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000515 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff46a98a72008-12-23 20:11:22 +0000516 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000517 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000518 if (LangOpts.Microsoft) {
519 // Add a constructor for creating temporary objects.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000520 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
521 ": ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000522 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000523 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000524 Preamble += "};\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000525 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
526 Preamble += "typedef struct objc_object Protocol;\n";
527 Preamble += "#define _REWRITER_typedef_Protocol\n";
528 Preamble += "#endif\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000529 if (LangOpts.Microsoft) {
530 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
531 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
532 } else
533 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
534 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000535 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000536 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000537 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000538 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000539 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000540 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000541 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000542 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000543 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000544 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000545 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000546 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000547 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000548 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
549 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
550 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
551 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
552 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000553 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000554 // @synchronized hooks.
Steve Naroff4ebd7162008-12-08 17:30:33 +0000555 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
556 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
557 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000558 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
559 Preamble += "struct __objcFastEnumerationState {\n\t";
560 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000561 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000562 Preamble += "unsigned long *mutationsPtr;\n\t";
563 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000564 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000565 Preamble += "#define __FASTENUMERATIONSTATE\n";
566 Preamble += "#endif\n";
567 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
568 Preamble += "struct __NSConstantStringImpl {\n";
569 Preamble += " int *isa;\n";
570 Preamble += " int flags;\n";
571 Preamble += " char *str;\n";
572 Preamble += " long length;\n";
573 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000574 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
575 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
576 Preamble += "#else\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000577 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000578 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000579 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
580 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000581 // Blocks preamble.
582 Preamble += "#ifndef BLOCK_IMPL\n";
583 Preamble += "#define BLOCK_IMPL\n";
584 Preamble += "struct __block_impl {\n";
585 Preamble += " void *isa;\n";
586 Preamble += " int Flags;\n";
Steve Naroff01aec112009-12-06 21:14:13 +0000587 Preamble += " int Reserved;\n";
Steve Naroff54055232008-10-27 17:20:55 +0000588 Preamble += " void *FuncPtr;\n";
589 Preamble += "};\n";
Steve Naroff5bc60d02008-12-16 15:50:30 +0000590 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
Steve Naroffc9c1e9c2009-12-06 01:52:22 +0000591 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000592 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_assign(void *, const void *, const int);\n";
593 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
594 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
595 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
596 Preamble += "#else\n";
Steve Naroffcd826372010-01-05 18:09:31 +0000597 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
598 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000599 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
600 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
601 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000602 Preamble += "#endif\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000603 if (LangOpts.Microsoft) {
Steve Naroff4ebd7162008-12-08 17:30:33 +0000604 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
605 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000606 Preamble += "#define __attribute__(X)\n";
607 }
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000608 else {
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000609 Preamble += "#define __block\n";
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000610 Preamble += "#define __weak\n";
611 }
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000612}
613
614
Chris Lattnerf04da132007-10-24 17:06:59 +0000615//===----------------------------------------------------------------------===//
616// Top Level Driver Code
617//===----------------------------------------------------------------------===//
618
Chris Lattner682bf922009-03-29 16:50:03 +0000619void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000620 // Two cases: either the decl could be in the main file, or it could be in a
621 // #included file. If the former, rewrite it now. If the later, check to see
622 // if we rewrote the #include/#import.
623 SourceLocation Loc = D->getLocation();
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000624 Loc = SM->getInstantiationLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000625
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000626 // If this is for a builtin, ignore it.
627 if (Loc.isInvalid()) return;
628
Steve Naroffebf2b562007-10-23 23:50:29 +0000629 // Look for built-in declarations that we need to refer during the rewrite.
630 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000631 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000632 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000633 // declared in <Foundation/NSString.h>
Chris Lattner8ec03f52008-11-24 03:54:41 +0000634 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000635 ConstantStringClassReference = FVD;
636 return;
637 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000638 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000639 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000640 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000641 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000642 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000643 RewriteProtocolDecl(PD);
Mike Stump1eb44332009-09-09 15:08:12 +0000644 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000645 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000646 RewriteForwardProtocolDecl(FP);
Douglas Gregord0434102009-01-09 00:49:46 +0000647 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
648 // Recurse into linkage specifications
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000649 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
650 DIEnd = LSD->decls_end();
Douglas Gregord0434102009-01-09 00:49:46 +0000651 DI != DIEnd; ++DI)
Chris Lattner682bf922009-03-29 16:50:03 +0000652 HandleTopLevelSingleDecl(*DI);
Steve Naroffebf2b562007-10-23 23:50:29 +0000653 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000654 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000655 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000656 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000657}
658
Chris Lattnerf04da132007-10-24 17:06:59 +0000659//===----------------------------------------------------------------------===//
660// Syntactic (non-AST) Rewriting Code
661//===----------------------------------------------------------------------===//
662
Steve Naroffb29b4272008-04-14 22:03:09 +0000663void RewriteObjC::RewriteInclude() {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000664 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000665 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
666 const char *MainBufStart = MainBuf.first;
667 const char *MainBufEnd = MainBuf.second;
668 size_t ImportLen = strlen("import");
669 size_t IncludeLen = strlen("include");
Mike Stump1eb44332009-09-09 15:08:12 +0000670
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000671 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000672 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
673 if (*BufPtr == '#') {
674 if (++BufPtr == MainBufEnd)
675 return;
676 while (*BufPtr == ' ' || *BufPtr == '\t')
677 if (++BufPtr == MainBufEnd)
678 return;
679 if (!strncmp(BufPtr, "import", ImportLen)) {
680 // replace import with include
Mike Stump1eb44332009-09-09 15:08:12 +0000681 SourceLocation ImportLoc =
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000682 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattneraadaf782008-01-31 19:51:04 +0000683 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000684 BufPtr += ImportLen;
685 }
686 }
687 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000688}
689
Steve Naroffb29b4272008-04-14 22:03:09 +0000690void RewriteObjC::RewriteTabs() {
Chris Lattnerf04da132007-10-24 17:06:59 +0000691 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
692 const char *MainBufStart = MainBuf.first;
693 const char *MainBufEnd = MainBuf.second;
Mike Stump1eb44332009-09-09 15:08:12 +0000694
Chris Lattnerf04da132007-10-24 17:06:59 +0000695 // Loop over the whole file, looking for tabs.
696 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
697 if (*BufPtr != '\t')
698 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000699
Chris Lattnerf04da132007-10-24 17:06:59 +0000700 // Okay, we found a tab. This tab will turn into at least one character,
701 // but it depends on which 'virtual column' it is in. Compute that now.
702 unsigned VCol = 0;
703 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
704 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
705 ++VCol;
Mike Stump1eb44332009-09-09 15:08:12 +0000706
Chris Lattnerf04da132007-10-24 17:06:59 +0000707 // Okay, now that we know the virtual column, we know how many spaces to
708 // insert. We assume 8-character tab-stops.
709 unsigned Spaces = 8-(VCol & 7);
Mike Stump1eb44332009-09-09 15:08:12 +0000710
Chris Lattnerf04da132007-10-24 17:06:59 +0000711 // Get the location of the tab.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000712 SourceLocation TabLoc = SM->getLocForStartOfFile(MainFileID);
713 TabLoc = TabLoc.getFileLocWithOffset(BufPtr-MainBufStart);
Mike Stump1eb44332009-09-09 15:08:12 +0000714
Chris Lattnerf04da132007-10-24 17:06:59 +0000715 // Rewrite the single tab character into a sequence of spaces.
Chris Lattneraadaf782008-01-31 19:51:04 +0000716 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerf04da132007-10-24 17:06:59 +0000717 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000718}
719
Steve Naroffeb0646c2008-12-02 15:48:25 +0000720static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
721 ObjCIvarDecl *OID) {
722 std::string S;
723 S = "((struct ";
724 S += ClassDecl->getIdentifier()->getName();
725 S += "_IMPL *)self)->";
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +0000726 S += OID->getName();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000727 return S;
728}
729
Steve Naroffa0876e82008-12-02 17:36:43 +0000730void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
731 ObjCImplementationDecl *IMD,
732 ObjCCategoryImplDecl *CID) {
Steve Naroffd40910b2008-12-01 20:33:01 +0000733 SourceLocation startLoc = PID->getLocStart();
734 InsertText(startLoc, "// ", 3);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000735 const char *startBuf = SM->getCharacterData(startLoc);
736 assert((*startBuf == '@') && "bogus @synthesize location");
737 const char *semiBuf = strchr(startBuf, ';');
738 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek8189cde2009-02-07 01:47:29 +0000739 SourceLocation onePastSemiLoc =
740 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000741
742 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
743 return; // FIXME: is this correct?
Mike Stump1eb44332009-09-09 15:08:12 +0000744
Steve Naroffeb0646c2008-12-02 15:48:25 +0000745 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000746 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000747 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000748 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000749
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000750 if (!OID)
751 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000752
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000753 std::string Getr;
754 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
755 Getr += "{ ";
756 // Synthesize an explicit cast to gain access to the ivar.
Mike Stump1eb44332009-09-09 15:08:12 +0000757 // FIXME: deal with code generation implications for various property
758 // attributes (copy, retain, nonatomic).
Steve Naroff3539cdb2008-12-02 17:54:50 +0000759 // See objc-act.c:objc_synthesize_new_getter() for details.
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000760 Getr += "return " + getIvarAccessString(ClassDecl, OID);
761 Getr += "; }";
Steve Naroffeb0646c2008-12-02 15:48:25 +0000762 InsertText(onePastSemiLoc, Getr.c_str(), Getr.size());
Steve Naroffeb0646c2008-12-02 15:48:25 +0000763 if (PD->isReadOnly())
764 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000765
Steve Naroffeb0646c2008-12-02 15:48:25 +0000766 // Generate the 'setter' function.
767 std::string Setr;
768 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000769 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000770 // Synthesize an explicit cast to initialize the ivar.
Mike Stump1eb44332009-09-09 15:08:12 +0000771 // FIXME: deal with code generation implications for various property
772 // attributes (copy, retain, nonatomic).
Steve Naroff15f081d2008-12-03 00:56:33 +0000773 // See objc-act.c:objc_synthesize_new_setter() for details.
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000774 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
Steve Narofff4312dc2008-12-11 19:29:16 +0000775 Setr += PD->getNameAsCString();
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000776 Setr += "; }";
Steve Naroffeb0646c2008-12-02 15:48:25 +0000777 InsertText(onePastSemiLoc, Setr.c_str(), Setr.size());
Steve Naroffd40910b2008-12-01 20:33:01 +0000778}
Chris Lattner8a12c272007-10-11 18:38:32 +0000779
Steve Naroffb29b4272008-04-14 22:03:09 +0000780void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000781 // Get the start location and compute the semi location.
782 SourceLocation startLoc = ClassDecl->getLocation();
783 const char *startBuf = SM->getCharacterData(startLoc);
784 const char *semiPtr = strchr(startBuf, ';');
Mike Stump1eb44332009-09-09 15:08:12 +0000785
Chris Lattnerf04da132007-10-24 17:06:59 +0000786 // Translate to typedef's that forward reference structs with the same name
787 // as the class. As a convenience, we include the original declaration
788 // as a comment.
789 std::string typedefString;
790 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000791 typedefString.append(startBuf, semiPtr-startBuf+1);
792 typedefString += "\n";
Chris Lattner67956052009-02-20 18:04:31 +0000793 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
794 I != E; ++I) {
Ted Kremenek321c22f2009-11-18 00:28:11 +0000795 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
Steve Naroff32174822007-11-09 12:50:28 +0000796 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000797 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000798 typedefString += "\n";
799 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000800 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000801 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000802 typedefString += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000803 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000804 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000805 }
Mike Stump1eb44332009-09-09 15:08:12 +0000806
Steve Naroff934f2762007-10-24 22:48:43 +0000807 // Replace the @class with typedefs corresponding to the classes.
Mike Stump1eb44332009-09-09 15:08:12 +0000808 ReplaceText(startLoc, semiPtr-startBuf+1,
Chris Lattneraadaf782008-01-31 19:51:04 +0000809 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000810}
811
Steve Naroffb29b4272008-04-14 22:03:09 +0000812void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000813 SourceLocation LocStart = Method->getLocStart();
814 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000815
Chris Lattner30fc9332009-02-04 01:06:56 +0000816 if (SM->getInstantiationLineNumber(LocEnd) >
817 SM->getInstantiationLineNumber(LocStart)) {
Steve Naroff94ac21e2008-10-21 13:37:27 +0000818 InsertText(LocStart, "#if 0\n", 6);
819 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000820 } else {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000821 InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000822 }
823}
824
Mike Stump1eb44332009-09-09 15:08:12 +0000825void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Steve Naroff6327e0d2009-01-11 01:06:09 +0000826 SourceLocation Loc = prop->getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000827
Steve Naroff6327e0d2009-01-11 01:06:09 +0000828 ReplaceText(Loc, 0, "// ", 3);
Mike Stump1eb44332009-09-09 15:08:12 +0000829
Steve Naroff6327e0d2009-01-11 01:06:09 +0000830 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000831}
832
Steve Naroffb29b4272008-04-14 22:03:09 +0000833void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000834 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000835
Steve Naroff423cb562007-10-30 13:30:57 +0000836 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000837 ReplaceText(LocStart, 0, "// ", 3);
Mike Stump1eb44332009-09-09 15:08:12 +0000838
839 for (ObjCCategoryDecl::instmeth_iterator
840 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000841 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000842 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +0000843 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000844 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000845 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000846 RewriteMethodDeclaration(*I);
847
Steve Naroff423cb562007-10-30 13:30:57 +0000848 // Lastly, comment out the @end.
Ted Kremenek782f2f52010-01-07 01:20:12 +0000849 ReplaceText(CatDecl->getAtEndRange().getBegin(), 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000850}
851
Steve Naroffb29b4272008-04-14 22:03:09 +0000852void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000853 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Mike Stump1eb44332009-09-09 15:08:12 +0000854
Steve Naroff752d6ef2007-10-30 16:42:30 +0000855 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000856
Steve Naroff752d6ef2007-10-30 16:42:30 +0000857 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000858 ReplaceText(LocStart, 0, "// ", 3);
Mike Stump1eb44332009-09-09 15:08:12 +0000859
860 for (ObjCProtocolDecl::instmeth_iterator
861 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000862 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000863 RewriteMethodDeclaration(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000864 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000865 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000866 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000867 RewriteMethodDeclaration(*I);
868
Steve Naroff752d6ef2007-10-30 16:42:30 +0000869 // Lastly, comment out the @end.
Ted Kremenek782f2f52010-01-07 01:20:12 +0000870 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Chris Lattneraadaf782008-01-31 19:51:04 +0000871 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000872
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000873 // Must comment out @optional/@required
874 const char *startBuf = SM->getCharacterData(LocStart);
875 const char *endBuf = SM->getCharacterData(LocEnd);
876 for (const char *p = startBuf; p < endBuf; p++) {
877 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
878 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000879 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000880 ReplaceText(OptionalLoc, strlen("@optional"),
881 CommentedOptional.c_str(), CommentedOptional.size());
Mike Stump1eb44332009-09-09 15:08:12 +0000882
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000883 }
884 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
885 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000886 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000887 ReplaceText(OptionalLoc, strlen("@required"),
888 CommentedRequired.c_str(), CommentedRequired.size());
Mike Stump1eb44332009-09-09 15:08:12 +0000889
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000890 }
891 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000892}
893
Steve Naroffb29b4272008-04-14 22:03:09 +0000894void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000895 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000896 if (LocStart.isInvalid())
897 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000898 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000899 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000900}
901
Mike Stump1eb44332009-09-09 15:08:12 +0000902void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000903 std::string &ResultStr) {
Steve Naroffced80a82008-10-30 12:09:33 +0000904 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroff76e429d2008-07-16 14:40:40 +0000905 const FunctionType *FPRetType = 0;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000906 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000907 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000908 ResultStr += "id";
Steve Narofff4312dc2008-12-11 19:29:16 +0000909 else if (OMD->getResultType()->isFunctionPointerType() ||
910 OMD->getResultType()->isBlockPointerType()) {
Steve Naroff76e429d2008-07-16 14:40:40 +0000911 // needs special handling, since pointer-to-functions have special
912 // syntax (where a decaration models use).
913 QualType retType = OMD->getResultType();
Steve Narofff4312dc2008-12-11 19:29:16 +0000914 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +0000915 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +0000916 PointeeTy = PT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000917 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +0000918 PointeeTy = BPT->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +0000919 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Steve Narofff4312dc2008-12-11 19:29:16 +0000920 ResultStr += FPRetType->getResultType().getAsString();
921 ResultStr += "(*";
Steve Naroff76e429d2008-07-16 14:40:40 +0000922 }
923 } else
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000924 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000925 ResultStr += " ";
Mike Stump1eb44332009-09-09 15:08:12 +0000926
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000927 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000928 std::string NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +0000929
Douglas Gregorf8d49f62009-01-09 17:18:27 +0000930 if (OMD->isInstanceMethod())
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000931 NameStr += "_I_";
932 else
933 NameStr += "_C_";
Mike Stump1eb44332009-09-09 15:08:12 +0000934
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000935 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000936 NameStr += "_";
Mike Stump1eb44332009-09-09 15:08:12 +0000937
938 if (ObjCCategoryImplDecl *CID =
Steve Naroff3e0a5402009-01-08 19:41:02 +0000939 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000940 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000941 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000942 }
Mike Stump1eb44332009-09-09 15:08:12 +0000943 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +0000944 {
945 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000946 int len = selString.size();
947 for (int i = 0; i < len; i++)
948 if (selString[i] == ':')
949 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000950 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000951 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000952 // Remember this name for metadata emission
953 MethodInternalNames[OMD] = NameStr;
954 ResultStr += NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +0000955
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000956 // Rewrite arguments
957 ResultStr += "(";
Mike Stump1eb44332009-09-09 15:08:12 +0000958
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000959 // invisible arguments
Douglas Gregorf8d49f62009-01-09 17:18:27 +0000960 if (OMD->isInstanceMethod()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000961 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000962 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +0000963 if (!LangOpts.Microsoft) {
964 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
965 ResultStr += "struct ";
966 }
967 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000968 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000969 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000970 }
971 else
Steve Naroff621edce2009-04-29 16:37:50 +0000972 ResultStr += Context->getObjCClassType().getAsString();
Mike Stump1eb44332009-09-09 15:08:12 +0000973
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000974 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000975 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000976 ResultStr += " _cmd";
Mike Stump1eb44332009-09-09 15:08:12 +0000977
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000978 // Method arguments.
Chris Lattner89951a82009-02-20 18:43:26 +0000979 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
980 E = OMD->param_end(); PI != E; ++PI) {
981 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000982 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +0000983 if (PDecl->getType()->isObjCQualifiedIdType()) {
984 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000985 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +0000986 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000987 std::string Name = PDecl->getNameAsString();
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000988 if (isTopLevelBlockPointerType(PDecl->getType())) {
Steve Naroffc8ad87b2008-10-30 14:45:29 +0000989 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Ted Kremenek6217b802009-07-29 21:53:49 +0000990 const BlockPointerType *BPT = PDecl->getType()->getAs<BlockPointerType>();
Douglas Gregord249e1d1f2009-05-29 20:38:28 +0000991 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name,
992 Context->PrintingPolicy);
Steve Naroffc8ad87b2008-10-30 14:45:29 +0000993 } else
Douglas Gregord249e1d1f2009-05-29 20:38:28 +0000994 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroff543409e2008-04-18 21:13:19 +0000995 ResultStr += Name;
996 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000997 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +0000998 if (OMD->isVariadic())
999 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001000 ResultStr += ") ";
Mike Stump1eb44332009-09-09 15:08:12 +00001001
Steve Naroff76e429d2008-07-16 14:40:40 +00001002 if (FPRetType) {
1003 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump1eb44332009-09-09 15:08:12 +00001004
Steve Naroff76e429d2008-07-16 14:40:40 +00001005 // Now, emit the argument types (if any).
Douglas Gregor72564e72009-02-26 23:50:07 +00001006 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001007 ResultStr += "(";
1008 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1009 if (i) ResultStr += ", ";
1010 std::string ParamStr = FT->getArgType(i).getAsString();
1011 ResultStr += ParamStr;
1012 }
1013 if (FT->isVariadic()) {
1014 if (FT->getNumArgs()) ResultStr += ", ";
1015 ResultStr += "...";
1016 }
1017 ResultStr += ")";
1018 } else {
1019 ResultStr += "()";
1020 }
1021 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001022}
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001023void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001024 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1025 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump1eb44332009-09-09 15:08:12 +00001026
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001027 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001028 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001029 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001030 InsertText(CID->getLocStart(), "// ", 3);
Mike Stump1eb44332009-09-09 15:08:12 +00001031
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001032 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001033 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1034 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001035 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001036 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001037 ObjCMethodDecl *OMD = *I;
1038 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001039 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001040 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redld3a413d2009-04-26 20:35:05 +00001041
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001042 const char *startBuf = SM->getCharacterData(LocStart);
1043 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +00001044 ReplaceText(LocStart, endBuf-startBuf,
1045 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001046 }
Mike Stump1eb44332009-09-09 15:08:12 +00001047
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001048 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001049 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1050 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001051 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001052 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001053 ObjCMethodDecl *OMD = *I;
1054 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001055 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001056 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001057
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001058 const char *startBuf = SM->getCharacterData(LocStart);
1059 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +00001060 ReplaceText(LocStart, endBuf-startBuf,
Mike Stump1eb44332009-09-09 15:08:12 +00001061 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001062 }
Steve Naroffd40910b2008-12-01 20:33:01 +00001063 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001064 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001065 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001066 I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +00001067 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001068 }
1069
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001070 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001071 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001072 else
Mike Stump1eb44332009-09-09 15:08:12 +00001073 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001074}
1075
Steve Naroffb29b4272008-04-14 22:03:09 +00001076void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001077 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001078 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001079 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001080 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001081 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001082 ResultStr += "\n";
1083 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001084 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001085 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001086 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001087 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001088 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001089 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001090 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001091 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001092 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump1eb44332009-09-09 15:08:12 +00001093
1094 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001095 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff6327e0d2009-01-11 01:06:09 +00001096 RewriteProperty(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001097 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001098 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001099 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001100 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001101 for (ObjCInterfaceDecl::classmeth_iterator
1102 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001103 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001104 RewriteMethodDeclaration(*I);
1105
Steve Naroff2feac5e2007-10-30 03:43:13 +00001106 // Lastly, comment out the @end.
Ted Kremenek782f2f52010-01-07 01:20:12 +00001107 ReplaceText(ClassDecl->getAtEndRange().getBegin(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +00001108}
1109
Steve Naroffb619d952008-12-09 12:56:34 +00001110Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1111 SourceRange SrcRange) {
Steve Naroffc77a6362008-12-04 16:24:46 +00001112 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1113 // This allows us to reuse all the fun and games in SynthMessageExpr().
1114 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1115 ObjCMessageExpr *MsgExpr;
1116 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1117 llvm::SmallVector<Expr *, 1> ExprVec;
1118 ExprVec.push_back(newStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001119
Steve Naroff8599e7a2008-12-08 16:43:47 +00001120 Stmt *Receiver = PropRefExpr->getBase();
1121 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1122 if (PRE && PropGetters[PRE]) {
1123 // This allows us to handle chain/nested property getters.
1124 Receiver = PropGetters[PRE];
1125 }
Mike Stump1eb44332009-09-09 15:08:12 +00001126 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
1127 PDecl->getSetterName(), PDecl->getType(),
1128 PDecl->getSetterMethodDecl(),
1129 SourceLocation(), SourceLocation(),
Steve Naroffc77a6362008-12-04 16:24:46 +00001130 &ExprVec[0], 1);
1131 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001132
Steve Naroffc77a6362008-12-04 16:24:46 +00001133 // Now do the actual rewrite.
Steve Naroffb619d952008-12-09 12:56:34 +00001134 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffe58ee0c2008-12-10 14:53:27 +00001135 //delete BinOp;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001136 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1137 // to things that stay around.
1138 Context->Deallocate(MsgExpr);
Steve Naroffc77a6362008-12-04 16:24:46 +00001139 return ReplacingStmt;
Steve Naroff15f081d2008-12-03 00:56:33 +00001140}
1141
Steve Naroffc77a6362008-12-04 16:24:46 +00001142Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Naroff15f081d2008-12-03 00:56:33 +00001143 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1144 // This allows us to reuse all the fun and games in SynthMessageExpr().
1145 ObjCMessageExpr *MsgExpr;
1146 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
Mike Stump1eb44332009-09-09 15:08:12 +00001147
Steve Naroff8599e7a2008-12-08 16:43:47 +00001148 Stmt *Receiver = PropRefExpr->getBase();
Mike Stump1eb44332009-09-09 15:08:12 +00001149
Steve Naroff8599e7a2008-12-08 16:43:47 +00001150 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1151 if (PRE && PropGetters[PRE]) {
1152 // This allows us to handle chain/nested property getters.
1153 Receiver = PropGetters[PRE];
1154 }
Mike Stump1eb44332009-09-09 15:08:12 +00001155 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
1156 PDecl->getGetterName(), PDecl->getType(),
1157 PDecl->getGetterMethodDecl(),
1158 SourceLocation(), SourceLocation(),
Steve Naroff15f081d2008-12-03 00:56:33 +00001159 0, 0);
1160
Steve Naroff4c3580e2008-12-04 23:50:32 +00001161 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001162
1163 if (!PropParentMap)
1164 PropParentMap = new ParentMap(CurrentBody);
1165
1166 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1167 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1168 // We stash away the ReplacingStmt since actually doing the
1169 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1170 PropGetters[PropRefExpr] = ReplacingStmt;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001171 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1172 // to things that stay around.
1173 Context->Deallocate(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001174 return PropRefExpr; // return the original...
1175 } else {
1176 ReplaceStmt(PropRefExpr, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001177 // delete PropRefExpr; elsewhere...
Ted Kremenek8189cde2009-02-07 01:47:29 +00001178 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1179 // to things that stay around.
1180 Context->Deallocate(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001181 return ReplacingStmt;
1182 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001183}
1184
Mike Stump1eb44332009-09-09 15:08:12 +00001185Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001186 SourceLocation OrigStart) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001187 ObjCIvarDecl *D = IV->getDecl();
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001188 const Expr *BaseExpr = IV->getBase();
Steve Naroff54055232008-10-27 17:20:55 +00001189 if (CurMethodDef) {
Fariborz Jahaniand83658d2010-01-07 22:15:31 +00001190 if (IV->isArrow() && isa<DeclRefExpr>(BaseExpr)) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001191 ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001192 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Narofff0757612008-05-08 17:52:16 +00001193 // lookup which class implements the instance variable.
1194 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001195 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001196 clsDeclared);
Steve Narofff0757612008-05-08 17:52:16 +00001197 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001198
Steve Narofff0757612008-05-08 17:52:16 +00001199 // Synthesize an explicit cast to gain access to the ivar.
1200 std::string RecName = clsDeclared->getIdentifier()->getName();
1201 RecName += "_IMPL";
1202 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001203 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001204 SourceLocation(), II);
Steve Narofff0757612008-05-08 17:52:16 +00001205 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1206 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Mike Stump1eb44332009-09-09 15:08:12 +00001207 CastExpr *castExpr = new (Context) CStyleCastExpr(castT,
Anders Carlssoncdef2b72009-07-31 00:48:10 +00001208 CastExpr::CK_Unknown,
1209 IV->getBase(),
1210 castT,SourceLocation(),
1211 SourceLocation());
Steve Narofff0757612008-05-08 17:52:16 +00001212 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001213 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1214 IV->getBase()->getLocEnd(),
1215 castExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001216 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +00001217 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001218 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1219 IV->getLocation(),
1220 D->getType());
Steve Narofff0757612008-05-08 17:52:16 +00001221 ReplaceStmt(IV, ME);
Steve Naroff4c3580e2008-12-04 23:50:32 +00001222 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Narofff0757612008-05-08 17:52:16 +00001223 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001224 }
Mike Stump1eb44332009-09-09 15:08:12 +00001225
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001226 ReplaceStmt(IV->getBase(), PE);
1227 // Cannot delete IV->getBase(), since PE points to it.
1228 // Replace the old base with the cast. This is important when doing
1229 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001230 IV->setBase(PE);
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001231 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001232 }
Steve Naroff84472a82008-04-18 21:55:08 +00001233 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001234 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump1eb44332009-09-09 15:08:12 +00001235
Steve Naroff9f525972008-05-06 23:20:07 +00001236 // Explicit ivar refs need to have a cast inserted.
1237 // FIXME: consider sharing some of this code with the code above.
Ted Kremenek6217b802009-07-29 21:53:49 +00001238 if (const PointerType *pType = IV->getBase()->getType()->getAs<PointerType>()) {
Steve Narofff0757612008-05-08 17:52:16 +00001239 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001240 // lookup which class implements the instance variable.
1241 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001242 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001243 clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001244 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001245
Steve Naroff9f525972008-05-06 23:20:07 +00001246 // Synthesize an explicit cast to gain access to the ivar.
1247 std::string RecName = clsDeclared->getIdentifier()->getName();
1248 RecName += "_IMPL";
1249 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001250 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001251 SourceLocation(), II);
Steve Naroff9f525972008-05-06 23:20:07 +00001252 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1253 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Mike Stump1eb44332009-09-09 15:08:12 +00001254 CastExpr *castExpr = new (Context) CStyleCastExpr(castT,
Anders Carlssoncdef2b72009-07-31 00:48:10 +00001255 CastExpr::CK_Unknown,
1256 IV->getBase(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00001257 castT, SourceLocation(),
1258 SourceLocation());
Steve Naroff9f525972008-05-06 23:20:07 +00001259 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001260 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner8d366162008-05-28 16:38:23 +00001261 IV->getBase()->getLocEnd(), castExpr);
Steve Naroff9f525972008-05-06 23:20:07 +00001262 ReplaceStmt(IV->getBase(), PE);
1263 // Cannot delete IV->getBase(), since PE points to it.
1264 // Replace the old base with the cast. This is important when doing
1265 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001266 IV->setBase(PE);
Steve Naroff9f525972008-05-06 23:20:07 +00001267 return IV;
1268 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001269 }
Steve Naroff84472a82008-04-18 21:55:08 +00001270 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +00001271}
1272
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001273/// SynthCountByEnumWithState - To print:
1274/// ((unsigned int (*)
1275/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001276/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001277/// sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001278/// "countByEnumeratingWithState:objects:count:"),
1279/// &enumState,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001280/// (id *)items, (unsigned int)16)
1281///
Steve Naroffb29b4272008-04-14 22:03:09 +00001282void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001283 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1284 "id *, unsigned int))(void *)objc_msgSend)";
1285 buf += "\n\t\t";
1286 buf += "((id)l_collection,\n\t\t";
1287 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1288 buf += "\n\t\t";
1289 buf += "&enumState, "
1290 "(id *)items, (unsigned int)16)";
1291}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001292
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001293/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1294/// statement to exit to its outer synthesized loop.
1295///
Steve Naroffb29b4272008-04-14 22:03:09 +00001296Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001297 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1298 return S;
1299 // replace break with goto __break_label
1300 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001301
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001302 SourceLocation startLoc = S->getLocStart();
1303 buf = "goto __break_label_";
1304 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001305 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001306
1307 return 0;
1308}
1309
1310/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1311/// statement to continue with its inner synthesized loop.
1312///
Steve Naroffb29b4272008-04-14 22:03:09 +00001313Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001314 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1315 return S;
1316 // replace continue with goto __continue_label
1317 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001318
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001319 SourceLocation startLoc = S->getLocStart();
1320 buf = "goto __continue_label_";
1321 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001322 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001323
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001324 return 0;
1325}
1326
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001327/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001328/// It rewrites:
1329/// for ( type elem in collection) { stmts; }
Mike Stump1eb44332009-09-09 15:08:12 +00001330
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001331/// Into:
1332/// {
Mike Stump1eb44332009-09-09 15:08:12 +00001333/// type elem;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001334/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001335/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001336/// id l_collection = (id)collection;
Mike Stump1eb44332009-09-09 15:08:12 +00001337/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001338/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001339/// if (limit) {
1340/// unsigned long startMutations = *enumState.mutationsPtr;
1341/// do {
1342/// unsigned long counter = 0;
1343/// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001344/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001345/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001346/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001347/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001348/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001349/// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001350/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001351/// objects:items count:16]);
1352/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001353/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001354/// }
1355/// else
1356/// elem = nil;
1357/// }
1358///
Steve Naroffb29b4272008-04-14 22:03:09 +00001359Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001360 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001361 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001362 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001363 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump1eb44332009-09-09 15:08:12 +00001364 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001365 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001366
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001367 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001368 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001369 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001370 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001371 std::string buf;
1372 buf = "\n{\n\t";
1373 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1374 // type elem;
Chris Lattner7e24e822009-03-28 06:33:19 +00001375 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001376 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001377 if (ElementType->isObjCQualifiedIdType() ||
1378 ElementType->isObjCQualifiedInterfaceType())
1379 // Simply use 'id' for all qualified types.
1380 elementTypeAsString = "id";
1381 else
1382 elementTypeAsString = ElementType.getAsString();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001383 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001384 buf += " ";
Chris Lattner8ec03f52008-11-24 03:54:41 +00001385 elementName = D->getNameAsCString();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001386 buf += elementName;
1387 buf += ";\n\t";
1388 }
Chris Lattner06767512008-04-08 05:52:18 +00001389 else {
1390 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner8ec03f52008-11-24 03:54:41 +00001391 elementName = DR->getDecl()->getNameAsCString();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001392 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1393 if (VD->getType()->isObjCQualifiedIdType() ||
1394 VD->getType()->isObjCQualifiedInterfaceType())
1395 // Simply use 'id' for all qualified types.
1396 elementTypeAsString = "id";
1397 else
1398 elementTypeAsString = VD->getType().getAsString();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001399 }
Mike Stump1eb44332009-09-09 15:08:12 +00001400
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001401 // struct __objcFastEnumerationState enumState = { 0 };
1402 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1403 // id items[16];
1404 buf += "id items[16];\n\t";
1405 // id l_collection = (id)
1406 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001407 // Find start location of 'collection' the hard way!
1408 const char *startCollectionBuf = startBuf;
1409 startCollectionBuf += 3; // skip 'for'
1410 startCollectionBuf = strchr(startCollectionBuf, '(');
1411 startCollectionBuf++; // skip '('
1412 // find 'in' and skip it.
1413 while (*startCollectionBuf != ' ' ||
1414 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1415 (*(startCollectionBuf+3) != ' ' &&
1416 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1417 startCollectionBuf++;
1418 startCollectionBuf += 3;
Mike Stump1eb44332009-09-09 15:08:12 +00001419
1420 // Replace: "for (type element in" with string constructed thus far.
Chris Lattneraadaf782008-01-31 19:51:04 +00001421 ReplaceText(startLoc, startCollectionBuf - startBuf,
1422 buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001423 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001424 SourceLocation rightParenLoc = S->getRParenLoc();
1425 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1426 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001427 buf = ";\n\t";
Mike Stump1eb44332009-09-09 15:08:12 +00001428
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001429 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1430 // objects:items count:16];
1431 // which is synthesized into:
Mike Stump1eb44332009-09-09 15:08:12 +00001432 // unsigned int limit =
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001433 // ((unsigned int (*)
1434 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001435 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001436 // sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001437 // "countByEnumeratingWithState:objects:count:"),
1438 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001439 // (id *)items, (unsigned int)16);
1440 buf += "unsigned long limit =\n\t\t";
1441 SynthCountByEnumWithState(buf);
1442 buf += ";\n\t";
1443 /// if (limit) {
1444 /// unsigned long startMutations = *enumState.mutationsPtr;
1445 /// do {
1446 /// unsigned long counter = 0;
1447 /// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001448 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001449 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001450 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001451 buf += "if (limit) {\n\t";
1452 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1453 buf += "do {\n\t\t";
1454 buf += "unsigned long counter = 0;\n\t\t";
1455 buf += "do {\n\t\t\t";
1456 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1457 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1458 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001459 buf += " = (";
1460 buf += elementTypeAsString;
1461 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001462 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattneraadaf782008-01-31 19:51:04 +00001463 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001464
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001465 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001466 /// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001467 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001468 /// objects:items count:16]);
1469 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001470 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001471 /// }
1472 /// else
1473 /// elem = nil;
1474 /// }
Mike Stump1eb44332009-09-09 15:08:12 +00001475 ///
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001476 buf = ";\n\t";
1477 buf += "__continue_label_";
1478 buf += utostr(ObjCBcLabelNo.back());
1479 buf += ": ;";
1480 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001481 buf += "} while (counter < limit);\n\t";
1482 buf += "} while (limit = ";
1483 SynthCountByEnumWithState(buf);
1484 buf += ");\n\t";
1485 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001486 buf += " = ((";
1487 buf += elementTypeAsString;
1488 buf += ")0);\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001489 buf += "__break_label_";
1490 buf += utostr(ObjCBcLabelNo.back());
1491 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001492 buf += "}\n\t";
1493 buf += "else\n\t\t";
1494 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001495 buf += " = ((";
1496 buf += elementTypeAsString;
1497 buf += ")0);\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001498 buf += "}\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001499
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001500 // Insert all these *after* the statement body.
Sebastian Redld3a413d2009-04-26 20:35:05 +00001501 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Naroff600e4e82008-07-21 18:26:02 +00001502 if (isa<CompoundStmt>(S->getBody())) {
1503 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1504 InsertText(endBodyLoc, buf.c_str(), buf.size());
1505 } else {
1506 /* Need to treat single statements specially. For example:
1507 *
1508 * for (A *a in b) if (stuff()) break;
1509 * for (A *a in b) xxxyy;
1510 *
1511 * The following code simply scans ahead to the semi to find the actual end.
1512 */
1513 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1514 const char *semiBuf = strchr(stmtBuf, ';');
1515 assert(semiBuf && "Can't find ';'");
1516 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1517 InsertText(endBodyLoc, buf.c_str(), buf.size());
1518 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001519 Stmts.pop_back();
1520 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001521 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001522}
1523
Mike Stump1eb44332009-09-09 15:08:12 +00001524/// RewriteObjCSynchronizedStmt -
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001525/// This routine rewrites @synchronized(expr) stmt;
1526/// into:
1527/// objc_sync_enter(expr);
1528/// @try stmt @finally { objc_sync_exit(expr); }
1529///
Steve Naroffb29b4272008-04-14 22:03:09 +00001530Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001531 // Get the start location and compute the semi location.
1532 SourceLocation startLoc = S->getLocStart();
1533 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001534
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001535 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump1eb44332009-09-09 15:08:12 +00001536
1537 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001538 buf = "objc_sync_enter((id)";
1539 const char *lparenBuf = startBuf;
1540 while (*lparenBuf != '(') lparenBuf++;
1541 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001542 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1543 // the sync expression is typically a message expression that's already
Steve Naroffc7089f12008-08-19 13:04:19 +00001544 // been rewritten! (which implies the SourceLocation's are invalid).
1545 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001546 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001547 while (*endBuf != ')') endBuf--;
1548 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001549 buf = ");\n";
1550 // declare a new scope with two variables, _stack and _rethrow.
1551 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1552 buf += "int buf[18/*32-bit i386*/];\n";
1553 buf += "char *pointers[4];} _stack;\n";
1554 buf += "id volatile _rethrow = 0;\n";
1555 buf += "objc_exception_try_enter(&_stack);\n";
1556 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00001557 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001558 startLoc = S->getSynchBody()->getLocEnd();
1559 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001560
Steve Naroffc7089f12008-08-19 13:04:19 +00001561 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001562 SourceLocation lastCurlyLoc = startLoc;
1563 buf = "}\nelse {\n";
1564 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroff621edce2009-04-29 16:37:50 +00001565 buf += "}\n";
1566 buf += "{ /* implicit finally clause */\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001567 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb85e77a2009-12-05 21:43:12 +00001568
1569 std::string syncBuf;
1570 syncBuf += " objc_sync_exit(";
Mike Stump1eb44332009-09-09 15:08:12 +00001571 Expr *syncExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssoncdef2b72009-07-31 00:48:10 +00001572 CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00001573 S->getSynchExpr(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00001574 Context->getObjCIdType(),
1575 SourceLocation(),
1576 SourceLocation());
Ted Kremeneka95d3752008-09-13 05:16:45 +00001577 std::string syncExprBufS;
1578 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00001579 syncExpr->printPretty(syncExprBuf, *Context, 0,
1580 PrintingPolicy(LangOpts));
Steve Naroffb85e77a2009-12-05 21:43:12 +00001581 syncBuf += syncExprBuf.str();
1582 syncBuf += ");";
1583
1584 buf += syncBuf;
1585 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001586 buf += "}\n";
1587 buf += "}";
Mike Stump1eb44332009-09-09 15:08:12 +00001588
Chris Lattneraadaf782008-01-31 19:51:04 +00001589 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffb85e77a2009-12-05 21:43:12 +00001590
1591 bool hasReturns = false;
1592 HasReturnStmts(S->getSynchBody(), hasReturns);
1593 if (hasReturns)
1594 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1595
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001596 return 0;
1597}
1598
Steve Naroffb85e77a2009-12-05 21:43:12 +00001599void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1600{
Steve Naroff8c565152008-12-05 17:03:39 +00001601 // Perform a bottom up traversal of all children.
1602 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1603 CI != E; ++CI)
1604 if (*CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001605 WarnAboutReturnGotoStmts(*CI);
Steve Naroff8c565152008-12-05 17:03:39 +00001606
Steve Naroffb85e77a2009-12-05 21:43:12 +00001607 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001608 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff8c565152008-12-05 17:03:39 +00001609 TryFinallyContainsReturnDiag);
1610 }
1611 return;
1612}
1613
Steve Naroffb85e77a2009-12-05 21:43:12 +00001614void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1615{
1616 // Perform a bottom up traversal of all children.
1617 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1618 CI != E; ++CI)
1619 if (*CI)
1620 HasReturnStmts(*CI, hasReturns);
1621
1622 if (isa<ReturnStmt>(S))
1623 hasReturns = true;
1624 return;
1625}
1626
1627void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1628 // Perform a bottom up traversal of all children.
1629 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1630 CI != E; ++CI)
1631 if (*CI) {
1632 RewriteTryReturnStmts(*CI);
1633 }
1634 if (isa<ReturnStmt>(S)) {
1635 SourceLocation startLoc = S->getLocStart();
1636 const char *startBuf = SM->getCharacterData(startLoc);
1637
1638 const char *semiBuf = strchr(startBuf, ';');
1639 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1640 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1641
1642 std::string buf;
1643 buf = "{ objc_exception_try_exit(&_stack); return";
1644
1645 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
1646 InsertText(onePastSemiLoc, "}", 1);
1647 }
1648 return;
1649}
1650
1651void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1652 // Perform a bottom up traversal of all children.
1653 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1654 CI != E; ++CI)
1655 if (*CI) {
1656 RewriteSyncReturnStmts(*CI, syncExitBuf);
1657 }
1658 if (isa<ReturnStmt>(S)) {
1659 SourceLocation startLoc = S->getLocStart();
1660 const char *startBuf = SM->getCharacterData(startLoc);
1661
1662 const char *semiBuf = strchr(startBuf, ';');
1663 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1664 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1665
1666 std::string buf;
1667 buf = "{ objc_exception_try_exit(&_stack);";
1668 buf += syncExitBuf;
1669 buf += " return";
1670
1671 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
1672 InsertText(onePastSemiLoc, "}", 1);
1673 }
1674 return;
1675}
1676
Steve Naroffb29b4272008-04-14 22:03:09 +00001677Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001678 // Get the start location and compute the semi location.
1679 SourceLocation startLoc = S->getLocStart();
1680 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001681
Steve Naroff75730982007-11-07 04:08:17 +00001682 assert((*startBuf == '@') && "bogus @try location");
1683
1684 std::string buf;
1685 // declare a new scope with two variables, _stack and _rethrow.
1686 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1687 buf += "int buf[18/*32-bit i386*/];\n";
1688 buf += "char *pointers[4];} _stack;\n";
1689 buf += "id volatile _rethrow = 0;\n";
1690 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001691 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001692
Chris Lattneraadaf782008-01-31 19:51:04 +00001693 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001694
Steve Naroff75730982007-11-07 04:08:17 +00001695 startLoc = S->getTryBody()->getLocEnd();
1696 startBuf = SM->getCharacterData(startLoc);
1697
1698 assert((*startBuf == '}') && "bogus @try block");
Mike Stump1eb44332009-09-09 15:08:12 +00001699
Steve Naroff75730982007-11-07 04:08:17 +00001700 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffc9ba1722008-07-16 15:31:30 +00001701 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1702 if (catchList) {
1703 startLoc = startLoc.getFileLocWithOffset(1);
1704 buf = " /* @catch begin */ else {\n";
1705 buf += " id _caught = objc_exception_extract(&_stack);\n";
1706 buf += " objc_exception_try_enter (&_stack);\n";
1707 buf += " if (_setjmp(_stack.buf))\n";
1708 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1709 buf += " else { /* @catch continue */";
Mike Stump1eb44332009-09-09 15:08:12 +00001710
Steve Naroffc9ba1722008-07-16 15:31:30 +00001711 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001712 } else { /* no catch list */
1713 buf = "}\nelse {\n";
1714 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1715 buf += "}";
1716 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffc9ba1722008-07-16 15:31:30 +00001717 }
Steve Naroff75730982007-11-07 04:08:17 +00001718 bool sawIdTypedCatch = false;
1719 Stmt *lastCatchBody = 0;
Steve Naroff75730982007-11-07 04:08:17 +00001720 while (catchList) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00001721 ParmVarDecl *catchDecl = catchList->getCatchParamDecl();
Steve Naroff75730982007-11-07 04:08:17 +00001722
Mike Stump1eb44332009-09-09 15:08:12 +00001723 if (catchList == S->getCatchStmts())
Steve Naroff75730982007-11-07 04:08:17 +00001724 buf = "if ("; // we are generating code for the first catch clause
1725 else
1726 buf = "else if (";
1727 startLoc = catchList->getLocStart();
1728 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001729
Steve Naroff75730982007-11-07 04:08:17 +00001730 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump1eb44332009-09-09 15:08:12 +00001731
Steve Naroff75730982007-11-07 04:08:17 +00001732 const char *lParenLoc = strchr(startBuf, '(');
1733
Steve Naroffbe4b3332008-02-01 22:08:12 +00001734 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001735 // Now rewrite the body...
1736 lastCatchBody = catchList->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001737 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1738 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner06767512008-04-08 05:52:18 +00001739 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1740 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001741 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001742
Steve Naroffe12e6922008-02-01 20:02:07 +00001743 buf += "1) { id _tmp = _caught;";
Daniel Dunbard7407dc2009-08-19 19:10:30 +00001744 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff7ba138a2009-03-03 19:52:17 +00001745 } else if (catchDecl) {
1746 QualType t = catchDecl->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001747 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001748 buf += "1) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001749 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001750 sawIdTypedCatch = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001751 } else if (const PointerType *pType = t->getAs<PointerType>()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001752 ObjCInterfaceType *cls; // Should be a pointer to a class.
Mike Stump1eb44332009-09-09 15:08:12 +00001753
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001754 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001755 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001756 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001757 buf += cls->getDecl()->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001758 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001759 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001760 }
1761 }
1762 // Now rewrite the body...
1763 lastCatchBody = catchList->getCatchBody();
1764 SourceLocation rParenLoc = catchList->getRParenLoc();
1765 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1766 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1767 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1768 assert((*rParenBuf == ')') && "bogus @catch paren location");
1769 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001770
Steve Naroff75730982007-11-07 04:08:17 +00001771 buf = " = _caught;";
Mike Stump1eb44332009-09-09 15:08:12 +00001772 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroff75730982007-11-07 04:08:17 +00001773 // declares the @catch parameter).
Chris Lattneraadaf782008-01-31 19:51:04 +00001774 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff7ba138a2009-03-03 19:52:17 +00001775 } else {
Steve Naroff75730982007-11-07 04:08:17 +00001776 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001777 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001778 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001779 catchList = catchList->getNextCatchStmt();
1780 }
1781 // Complete the catch list...
1782 if (lastCatchBody) {
1783 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001784 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1785 "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001786
Steve Naroff378f47a2008-09-11 15:29:03 +00001787 // Insert the last (implicit) else clause *before* the right curly brace.
1788 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1789 buf = "} /* last catch end */\n";
1790 buf += "else {\n";
1791 buf += " _rethrow = _caught;\n";
1792 buf += " objc_exception_try_exit(&_stack);\n";
1793 buf += "} } /* @catch end */\n";
1794 if (!S->getFinallyStmt())
1795 buf += "}\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001796 InsertText(bodyLoc, buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001797
Steve Naroff75730982007-11-07 04:08:17 +00001798 // Set lastCurlyLoc
1799 lastCurlyLoc = lastCatchBody->getLocEnd();
1800 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001801 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001802 startLoc = finalStmt->getLocStart();
1803 startBuf = SM->getCharacterData(startLoc);
1804 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump1eb44332009-09-09 15:08:12 +00001805
Steve Naroff75730982007-11-07 04:08:17 +00001806 buf = "/* @finally */";
Chris Lattneraadaf782008-01-31 19:51:04 +00001807 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001808
Steve Naroff75730982007-11-07 04:08:17 +00001809 Stmt *body = finalStmt->getFinallyBody();
1810 SourceLocation startLoc = body->getLocStart();
1811 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001812 assert(*SM->getCharacterData(startLoc) == '{' &&
1813 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001814 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner06767512008-04-08 05:52:18 +00001815 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001816
Steve Naroff75730982007-11-07 04:08:17 +00001817 startLoc = startLoc.getFileLocWithOffset(1);
1818 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001819 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001820 endLoc = endLoc.getFileLocWithOffset(-1);
1821 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001822 InsertText(endLoc, buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001823
Steve Naroff75730982007-11-07 04:08:17 +00001824 // Set lastCurlyLoc
1825 lastCurlyLoc = body->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00001826
Steve Naroff8c565152008-12-05 17:03:39 +00001827 // Now check for any return/continue/go statements within the @try.
Steve Naroffb85e77a2009-12-05 21:43:12 +00001828 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00001829 } else { /* no finally clause - make sure we synthesize an implicit one */
1830 buf = "{ /* implicit finally clause */\n";
1831 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1832 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1833 buf += "}";
1834 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffb85e77a2009-12-05 21:43:12 +00001835
1836 // Now check for any return/continue/go statements within the @try.
1837 // The implicit finally clause won't called if the @try contains any
1838 // jump statements.
1839 bool hasReturns = false;
1840 HasReturnStmts(S->getTryBody(), hasReturns);
1841 if (hasReturns)
1842 RewriteTryReturnStmts(S->getTryBody());
Steve Naroff75730982007-11-07 04:08:17 +00001843 }
1844 // Now emit the final closing curly brace...
1845 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1846 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001847 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001848 return 0;
1849}
1850
Steve Naroffb29b4272008-04-14 22:03:09 +00001851Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001852 return 0;
1853}
1854
Steve Naroffb29b4272008-04-14 22:03:09 +00001855Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001856 return 0;
1857}
1858
Mike Stump1eb44332009-09-09 15:08:12 +00001859// This can't be done with ReplaceStmt(S, ThrowExpr), since
1860// the throw expression is typically a message expression that's already
Steve Naroff2bd03922007-11-07 15:32:26 +00001861// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001862Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001863 // Get the start location and compute the semi location.
1864 SourceLocation startLoc = S->getLocStart();
1865 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001866
Steve Naroff2bd03922007-11-07 15:32:26 +00001867 assert((*startBuf == '@') && "bogus @throw location");
1868
1869 std::string buf;
1870 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001871 if (S->getThrowExpr())
1872 buf = "objc_exception_throw(";
1873 else // add an implicit argument
1874 buf = "objc_exception_throw(_caught";
Mike Stump1eb44332009-09-09 15:08:12 +00001875
Steve Naroff4ba0acb2008-07-25 15:41:30 +00001876 // handle "@ throw" correctly.
1877 const char *wBuf = strchr(startBuf, 'w');
1878 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1879 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001880
Steve Naroff2bd03922007-11-07 15:32:26 +00001881 const char *semiBuf = strchr(startBuf, ';');
1882 assert((*semiBuf == ';') && "@throw: can't find ';'");
1883 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1884 buf = ");";
Chris Lattneraadaf782008-01-31 19:51:04 +00001885 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001886 return 0;
1887}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001888
Steve Naroffb29b4272008-04-14 22:03:09 +00001889Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001890 // Create a new string expression.
1891 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001892 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001893 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattner2085fd62009-02-18 06:40:38 +00001894 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
1895 StrEncoding.length(), false,StrType,
1896 SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001897 ReplaceStmt(Exp, Replacement);
Mike Stump1eb44332009-09-09 15:08:12 +00001898
Chris Lattner07506182007-11-30 22:53:43 +00001899 // Replace this subexpr in the parent.
Steve Naroff4c3580e2008-12-04 23:50:32 +00001900 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00001901 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001902}
1903
Steve Naroffb29b4272008-04-14 22:03:09 +00001904Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff1a937642008-12-22 22:16:07 +00001905 if (!SelGetUidFunctionDecl)
1906 SynthSelGetUidFunctionDecl();
Steve Naroffb42f8412007-11-05 14:50:49 +00001907 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1908 // Create a call to sel_registerName("selName").
1909 llvm::SmallVector<Expr*, 8> SelExprs;
1910 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001911 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00001912 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00001913 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00001914 false, argType, SourceLocation()));
Steve Naroffb42f8412007-11-05 14:50:49 +00001915 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1916 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001917 ReplaceStmt(Exp, SelExp);
Steve Naroff4c3580e2008-12-04 23:50:32 +00001918 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00001919 return SelExp;
1920}
1921
Steve Naroffb29b4272008-04-14 22:03:09 +00001922CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff934f2762007-10-24 22:48:43 +00001923 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001924 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001925 QualType msgSendType = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001926
Steve Naroffebf2b562007-10-23 23:50:29 +00001927 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001928 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001929
Steve Naroffebf2b562007-10-23 23:50:29 +00001930 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001931 QualType pToFunc = Context->getPointerType(msgSendType);
Mike Stump1eb44332009-09-09 15:08:12 +00001932 ImplicitCastExpr *ICE = new (Context) ImplicitCastExpr(pToFunc,
Anders Carlssoncdef2b72009-07-31 00:48:10 +00001933 CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00001934 DRE,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001935 /*isLvalue=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00001936
John McCall183700f2009-09-21 23:43:11 +00001937 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001938
Ted Kremenek668bf912009-02-09 20:51:47 +00001939 return new (Context) CallExpr(*Context, ICE, args, nargs, FT->getResultType(),
1940 SourceLocation());
Steve Naroff934f2762007-10-24 22:48:43 +00001941}
1942
Steve Naroffd5255f52007-11-01 13:24:47 +00001943static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1944 const char *&startRef, const char *&endRef) {
1945 while (startBuf < endBuf) {
1946 if (*startBuf == '<')
1947 startRef = startBuf; // mark the start.
1948 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001949 if (startRef && *startRef == '<') {
1950 endRef = startBuf; // mark the end.
1951 return true;
1952 }
1953 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001954 }
1955 startBuf++;
1956 }
1957 return false;
1958}
1959
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001960static void scanToNextArgument(const char *&argRef) {
1961 int angle = 0;
1962 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1963 if (*argRef == '<')
1964 angle++;
1965 else if (*argRef == '>')
1966 angle--;
1967 argRef++;
1968 }
1969 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1970}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001971
Steve Naroffb29b4272008-04-14 22:03:09 +00001972bool RewriteObjC::needToScanForQualifiers(QualType T) {
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001973 return T->isObjCQualifiedIdType() || T->isObjCQualifiedInterfaceType();
Steve Naroffd5255f52007-11-01 13:24:47 +00001974}
1975
Steve Naroff4f95b752008-07-29 18:15:38 +00001976void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1977 QualType Type = E->getType();
1978 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00001979 SourceLocation Loc, EndLoc;
Mike Stump1eb44332009-09-09 15:08:12 +00001980
Steve Naroffcda658e2008-11-19 21:15:47 +00001981 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
1982 Loc = ECE->getLParenLoc();
1983 EndLoc = ECE->getRParenLoc();
1984 } else {
1985 Loc = E->getLocStart();
1986 EndLoc = E->getLocEnd();
1987 }
1988 // This will defend against trying to rewrite synthesized expressions.
1989 if (Loc.isInvalid() || EndLoc.isInvalid())
1990 return;
1991
Steve Naroff4f95b752008-07-29 18:15:38 +00001992 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00001993 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00001994 const char *startRef = 0, *endRef = 0;
1995 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1996 // Get the locations of the startRef, endRef.
1997 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1998 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1999 // Comment out the protocol references.
2000 InsertText(LessLoc, "/*", 2);
2001 InsertText(GreaterLoc, "*/", 2);
2002 }
2003 }
2004}
2005
Steve Naroffb29b4272008-04-14 22:03:09 +00002006void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002007 SourceLocation Loc;
2008 QualType Type;
Douglas Gregor72564e72009-02-26 23:50:07 +00002009 const FunctionProtoType *proto = 0;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002010 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2011 Loc = VD->getLocation();
2012 Type = VD->getType();
2013 }
2014 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2015 Loc = FD->getLocation();
2016 // Check for ObjC 'id' and class types that have been adorned with protocol
2017 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall183700f2009-09-21 23:43:11 +00002018 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002019 assert(funcType && "missing function type");
Douglas Gregor72564e72009-02-26 23:50:07 +00002020 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002021 if (!proto)
2022 return;
2023 Type = proto->getResultType();
2024 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00002025 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2026 Loc = FD->getLocation();
2027 Type = FD->getType();
2028 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002029 else
2030 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002031
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002032 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00002033 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002034
Steve Naroffd5255f52007-11-01 13:24:47 +00002035 const char *endBuf = SM->getCharacterData(Loc);
2036 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00002037 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00002038 startBuf--; // scan backward (from the decl location) for return type.
2039 const char *startRef = 0, *endRef = 0;
2040 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2041 // Get the locations of the startRef, endRef.
2042 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2043 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2044 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002045 InsertText(LessLoc, "/*", 2);
2046 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00002047 }
2048 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002049 if (!proto)
2050 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00002051 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002052 const char *startBuf = SM->getCharacterData(Loc);
2053 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00002054 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2055 if (needToScanForQualifiers(proto->getArgType(i))) {
2056 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002057
Steve Naroffd5255f52007-11-01 13:24:47 +00002058 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002059 // scan forward (from the decl location) for argument types.
2060 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00002061 const char *startRef = 0, *endRef = 0;
2062 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2063 // Get the locations of the startRef, endRef.
Mike Stump1eb44332009-09-09 15:08:12 +00002064 SourceLocation LessLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002065 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002066 SourceLocation GreaterLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002067 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002068 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002069 InsertText(LessLoc, "/*", 2);
2070 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00002071 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002072 startBuf = ++endBuf;
2073 }
2074 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00002075 // If the function name is derived from a macro expansion, then the
2076 // argument buffer will not follow the name. Need to speak with Chris.
2077 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002078 startBuf++; // scan forward (from the decl location) for argument types.
2079 startBuf++;
2080 }
Steve Naroffd5255f52007-11-01 13:24:47 +00002081 }
Steve Naroff9165ad32007-10-31 04:38:33 +00002082}
2083
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002084// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00002085void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002086 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2087 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002088 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002089 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002090 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002091 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002092 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002093 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002094 SelGetUidIdent, getFuncType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002095 FunctionDecl::Extern, false);
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002096}
2097
Steve Naroffb29b4272008-04-14 22:03:09 +00002098void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002099 // declared in <objc/objc.h>
Douglas Gregor51efe562009-01-09 01:47:02 +00002100 if (FD->getIdentifier() &&
2101 strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002102 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00002103 return;
2104 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002105 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00002106}
2107
Steve Naroffc0a123c2008-03-11 17:37:02 +00002108// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00002109void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002110 if (SuperContructorFunctionDecl)
2111 return;
Steve Naroff46a98a72008-12-23 20:11:22 +00002112 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroffc0a123c2008-03-11 17:37:02 +00002113 llvm::SmallVector<QualType, 16> ArgTys;
2114 QualType argT = Context->getObjCIdType();
2115 assert(!argT.isNull() && "Can't find 'id' type");
2116 ArgTys.push_back(argT);
2117 ArgTys.push_back(argT);
2118 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2119 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002120 false, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002121 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002122 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002123 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002124 FunctionDecl::Extern, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002125}
2126
Steve Naroff09b266e2007-10-30 23:14:51 +00002127// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002128void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002129 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2130 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002131 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002132 assert(!argT.isNull() && "Can't find 'id' type");
2133 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002134 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002135 assert(!argT.isNull() && "Can't find 'SEL' type");
2136 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002137 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002138 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002139 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002140 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002141 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002142 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002143 FunctionDecl::Extern, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002144}
2145
Steve Naroff874e2322007-11-15 10:28:18 +00002146// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002147void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00002148 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2149 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002150 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002151 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002152 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002153 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2154 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2155 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002156 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002157 assert(!argT.isNull() && "Can't find 'SEL' type");
2158 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002159 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00002160 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002161 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002162 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002163 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002164 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002165 FunctionDecl::Extern, false);
Steve Naroff874e2322007-11-15 10:28:18 +00002166}
2167
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002168// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002169void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002170 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2171 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002172 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002173 assert(!argT.isNull() && "Can't find 'id' type");
2174 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002175 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002176 assert(!argT.isNull() && "Can't find 'SEL' type");
2177 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002178 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002179 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002180 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002181 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002182 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002183 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002184 FunctionDecl::Extern, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002185}
2186
Mike Stump1eb44332009-09-09 15:08:12 +00002187// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002188// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002189void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump1eb44332009-09-09 15:08:12 +00002190 IdentifierInfo *msgSendIdent =
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002191 &Context->Idents.get("objc_msgSendSuper_stret");
2192 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002193 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002194 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002195 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002196 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2197 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2198 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002199 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002200 assert(!argT.isNull() && "Can't find 'SEL' type");
2201 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002202 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002203 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002204 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002205 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002206 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002207 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002208 FunctionDecl::Extern, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002209}
2210
Steve Naroff1284db82008-05-08 22:02:18 +00002211// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002212void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002213 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2214 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002215 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002216 assert(!argT.isNull() && "Can't find 'id' type");
2217 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002218 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002219 assert(!argT.isNull() && "Can't find 'SEL' type");
2220 ArgTys.push_back(argT);
Steve Naroff1284db82008-05-08 22:02:18 +00002221 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002222 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002223 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002224 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002225 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002226 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002227 FunctionDecl::Extern, false);
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002228}
2229
Steve Naroff09b266e2007-10-30 23:14:51 +00002230// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002231void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002232 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2233 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002234 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002235 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002236 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002237 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002238 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002239 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002240 getClassIdent, getClassType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002241 FunctionDecl::Extern, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002242}
2243
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002244// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002245void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002246 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2247 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002248 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002249 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002250 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002251 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002252 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002253 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002254 getClassIdent, getClassType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002255 FunctionDecl::Extern, false);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002256}
2257
Steve Naroffb29b4272008-04-14 22:03:09 +00002258Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002259 QualType strType = getConstantStringStructType();
2260
2261 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002262
2263 std::string tmpName = InFileName;
2264 unsigned i;
2265 for (i=0; i < tmpName.length(); i++) {
2266 char c = tmpName.at(i);
2267 // replace any non alphanumeric characters with '_'.
2268 if (!isalpha(c) && (c < '0' || c > '9'))
2269 tmpName[i] = '_';
2270 }
2271 S += tmpName;
2272 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002273 S += utostr(NumObjCStringLiterals++);
2274
Steve Naroffba92b2e2008-03-27 22:29:16 +00002275 Preamble += "static __NSConstantStringImpl " + S;
2276 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2277 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002278 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002279 std::string prettyBufS;
2280 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00002281 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2282 PrintingPolicy(LangOpts));
Steve Naroffba92b2e2008-03-27 22:29:16 +00002283 Preamble += prettyBuf.str();
2284 Preamble += ",";
Steve Narofffd5b76f2009-12-06 01:48:44 +00002285 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002286
2287 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2288 &Context->Idents.get(S.c_str()), strType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002289 VarDecl::Static);
Ted Kremenek8189cde2009-02-07 01:47:29 +00002290 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
2291 Expr *Unop = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002292 Context->getPointerType(DRE->getType()),
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002293 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002294 // cast to NSConstantString *
Mike Stump1eb44332009-09-09 15:08:12 +00002295 CastExpr *cast = new (Context) CStyleCastExpr(Exp->getType(),
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002296 CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00002297 Unop, Exp->getType(),
2298 SourceLocation(),
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002299 SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002300 ReplaceStmt(Exp, cast);
Steve Naroff4c3580e2008-12-04 23:50:32 +00002301 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002302 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002303}
2304
Steve Naroffb29b4272008-04-14 22:03:09 +00002305ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002306 // check if we are sending a message to 'super'
Douglas Gregorf8d49f62009-01-09 17:18:27 +00002307 if (!CurMethodDef || !CurMethodDef->isInstanceMethod()) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002308
Douglas Gregorcd9b46e2008-11-04 14:56:14 +00002309 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002310 const ObjCObjectPointerType *OPT =
John McCall183700f2009-09-21 23:43:11 +00002311 Super->getType()->getAs<ObjCObjectPointerType>();
Steve Naroff14108da2009-07-10 23:34:53 +00002312 assert(OPT);
2313 const ObjCInterfaceType *IT = OPT->getInterfaceType();
Chris Lattner0d17f6f2008-06-21 18:04:54 +00002314 return IT->getDecl();
2315 }
2316 return 0;
Steve Naroff874e2322007-11-15 10:28:18 +00002317}
2318
2319// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002320QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002321 if (!SuperStructDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002322 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002323 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002324 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002325 QualType FieldTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00002326
Steve Naroff874e2322007-11-15 10:28:18 +00002327 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002328 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002329 // struct objc_class *super;
Mike Stump1eb44332009-09-09 15:08:12 +00002330 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor44b43212008-12-11 16:49:14 +00002331
Steve Naroff874e2322007-11-15 10:28:18 +00002332 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002333 for (unsigned i = 0; i < 2; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002334 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2335 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002336 FieldTypes[i], 0,
2337 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002338 /*Mutable=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002339 }
Mike Stump1eb44332009-09-09 15:08:12 +00002340
Douglas Gregor44b43212008-12-11 16:49:14 +00002341 SuperStructDecl->completeDefinition(*Context);
Steve Naroff874e2322007-11-15 10:28:18 +00002342 }
2343 return Context->getTagDeclType(SuperStructDecl);
2344}
2345
Steve Naroffb29b4272008-04-14 22:03:09 +00002346QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002347 if (!ConstantStringDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002348 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002349 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002350 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002351 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002352
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002353 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002354 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002355 // int flags;
Mike Stump1eb44332009-09-09 15:08:12 +00002356 FieldTypes[1] = Context->IntTy;
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002357 // char *str;
Mike Stump1eb44332009-09-09 15:08:12 +00002358 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002359 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002360 FieldTypes[3] = Context->LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002361
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002362 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002363 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002364 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2365 ConstantStringDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00002366 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002367 FieldTypes[i], 0,
Douglas Gregor44b43212008-12-11 16:49:14 +00002368 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002369 /*Mutable=*/true));
Douglas Gregor44b43212008-12-11 16:49:14 +00002370 }
2371
2372 ConstantStringDecl->completeDefinition(*Context);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002373 }
2374 return Context->getTagDeclType(ConstantStringDecl);
2375}
2376
Steve Naroffb29b4272008-04-14 22:03:09 +00002377Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002378 if (!SelGetUidFunctionDecl)
2379 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002380 if (!MsgSendFunctionDecl)
2381 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002382 if (!MsgSendSuperFunctionDecl)
2383 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002384 if (!MsgSendStretFunctionDecl)
2385 SynthMsgSendStretFunctionDecl();
2386 if (!MsgSendSuperStretFunctionDecl)
2387 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002388 if (!MsgSendFpretFunctionDecl)
2389 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002390 if (!GetClassFunctionDecl)
2391 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002392 if (!GetMetaClassFunctionDecl)
2393 SynthGetMetaClassFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002394
Steve Naroff874e2322007-11-15 10:28:18 +00002395 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002396 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2397 // May need to use objc_msgSend_stret() as well.
2398 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroff621edce2009-04-29 16:37:50 +00002399 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2400 QualType resultType = mDecl->getResultType();
Chris Lattner8b51fd72008-07-26 22:36:27 +00002401 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002402 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002403 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002404 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002405 }
Mike Stump1eb44332009-09-09 15:08:12 +00002406
Steve Naroff934f2762007-10-24 22:48:43 +00002407 // Synthesize a call to objc_msgSend().
2408 llvm::SmallVector<Expr*, 8> MsgExprs;
2409 IdentifierInfo *clsName = Exp->getClassName();
Mike Stump1eb44332009-09-09 15:08:12 +00002410
Steve Naroff934f2762007-10-24 22:48:43 +00002411 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2412 if (clsName) { // class message.
Steve Narofffc93d522008-07-24 19:44:33 +00002413 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2414 // the 'super' idiom within a class method.
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00002415 if (clsName->getName() == "super") {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002416 MsgSendFlavor = MsgSendSuperFunctionDecl;
2417 if (MsgSendStretFlavor)
2418 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2419 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump1eb44332009-09-09 15:08:12 +00002420
2421 ObjCInterfaceDecl *SuperDecl =
Steve Naroff54055232008-10-27 17:20:55 +00002422 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002423
2424 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00002425
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002426 // set the receiver to self, the first argument to all methods.
Steve Naroff621edce2009-04-29 16:37:50 +00002427 InitExprs.push_back(
Mike Stump1eb44332009-09-09 15:08:12 +00002428 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002429 CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00002430 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroff621edce2009-04-29 16:37:50 +00002431 Context->getObjCIdType(),
2432 SourceLocation()),
2433 Context->getObjCIdType(),
2434 SourceLocation(), SourceLocation())); // set the 'receiver'.
2435
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002436 llvm::SmallVector<Expr*, 8> ClsExprs;
2437 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner2085fd62009-02-18 06:40:38 +00002438 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbare013d682009-10-18 20:26:12 +00002439 SuperDecl->getIdentifier()->getNameStart(),
2440 SuperDecl->getIdentifier()->getLength(),
2441 false, argType, SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002442 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002443 &ClsExprs[0],
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002444 ClsExprs.size());
2445 // To turn off a warning, type-cast to 'id'
Douglas Gregor49badde2008-10-27 19:41:14 +00002446 InitExprs.push_back( // set 'super class', using objc_getClass().
Mike Stump1eb44332009-09-09 15:08:12 +00002447 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002448 CastExpr::CK_Unknown,
Douglas Gregor49badde2008-10-27 19:41:14 +00002449 Cls, Context->getObjCIdType(),
Mike Stump1eb44332009-09-09 15:08:12 +00002450 SourceLocation(), SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002451 // struct objc_super
2452 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00002453 Expr *SuperRep;
Mike Stump1eb44332009-09-09 15:08:12 +00002454
Steve Naroff23f41272008-03-11 18:14:26 +00002455 if (LangOpts.Microsoft) {
2456 SynthSuperContructorFunctionDecl();
2457 // Simulate a contructor call...
Mike Stump1eb44332009-09-09 15:08:12 +00002458 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff23f41272008-03-11 18:14:26 +00002459 superType, SourceLocation());
Ted Kremenek668bf912009-02-09 20:51:47 +00002460 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00002461 InitExprs.size(),
Ted Kremenek668bf912009-02-09 20:51:47 +00002462 superType, SourceLocation());
Steve Naroff46a98a72008-12-23 20:11:22 +00002463 // The code for super is a little tricky to prevent collision with
2464 // the structure definition in the header. The rewriter has it's own
2465 // internal definition (__rw_objc_super) that is uses. This is why
2466 // we need the cast below. For example:
2467 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2468 //
Ted Kremenek8189cde2009-02-07 01:47:29 +00002469 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002470 Context->getPointerType(SuperRep->getType()),
Steve Naroff46a98a72008-12-23 20:11:22 +00002471 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002472 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
2473 CastExpr::CK_Unknown, SuperRep,
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002474 Context->getPointerType(superType),
Mike Stump1eb44332009-09-09 15:08:12 +00002475 SourceLocation(), SourceLocation());
2476 } else {
Steve Naroff23f41272008-03-11 18:14:26 +00002477 // (struct objc_super) { <exprs from above> }
Mike Stump1eb44332009-09-09 15:08:12 +00002478 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2479 &InitExprs[0], InitExprs.size(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002480 SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00002481 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE,
Chris Lattner418f6c72008-10-26 23:43:26 +00002482 false);
Steve Naroff46a98a72008-12-23 20:11:22 +00002483 // struct objc_super *
Ted Kremenek8189cde2009-02-07 01:47:29 +00002484 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002485 Context->getPointerType(SuperRep->getType()),
Steve Naroff46a98a72008-12-23 20:11:22 +00002486 SourceLocation());
Steve Naroff23f41272008-03-11 18:14:26 +00002487 }
Steve Naroff46a98a72008-12-23 20:11:22 +00002488 MsgExprs.push_back(SuperRep);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002489 } else {
2490 llvm::SmallVector<Expr*, 8> ClsExprs;
2491 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner2085fd62009-02-18 06:40:38 +00002492 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbare013d682009-10-18 20:26:12 +00002493 clsName->getNameStart(),
Chris Lattner2085fd62009-02-18 06:40:38 +00002494 clsName->getLength(),
2495 false, argType,
2496 SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002497 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002498 &ClsExprs[0],
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002499 ClsExprs.size());
2500 MsgExprs.push_back(Cls);
2501 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002502 } else { // instance message.
2503 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00002504
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002505 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00002506 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002507 if (MsgSendStretFlavor)
2508 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00002509 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump1eb44332009-09-09 15:08:12 +00002510
Steve Naroff874e2322007-11-15 10:28:18 +00002511 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00002512
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002513 InitExprs.push_back(
Mike Stump1eb44332009-09-09 15:08:12 +00002514 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002515 CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00002516 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Narofff616ebb2008-07-16 22:35:27 +00002517 Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002518 SourceLocation()),
2519 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002520 SourceLocation(), SourceLocation())); // set the 'receiver'.
Mike Stump1eb44332009-09-09 15:08:12 +00002521
Steve Naroff874e2322007-11-15 10:28:18 +00002522 llvm::SmallVector<Expr*, 8> ClsExprs;
2523 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002524 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbare013d682009-10-18 20:26:12 +00002525 SuperDecl->getIdentifier()->getNameStart(),
2526 SuperDecl->getIdentifier()->getLength(),
2527 false, argType, SourceLocation()));
Steve Naroff874e2322007-11-15 10:28:18 +00002528 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002529 &ClsExprs[0],
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002530 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00002531 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002532 InitExprs.push_back(
Douglas Gregor49badde2008-10-27 19:41:14 +00002533 // set 'super class', using objc_getClass().
Mike Stump1eb44332009-09-09 15:08:12 +00002534 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002535 CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00002536 Cls, Context->getObjCIdType(), SourceLocation(), SourceLocation()));
Steve Naroff874e2322007-11-15 10:28:18 +00002537 // struct objc_super
2538 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00002539 Expr *SuperRep;
Mike Stump1eb44332009-09-09 15:08:12 +00002540
Steve Naroffc0a123c2008-03-11 17:37:02 +00002541 if (LangOpts.Microsoft) {
2542 SynthSuperContructorFunctionDecl();
2543 // Simulate a contructor call...
Mike Stump1eb44332009-09-09 15:08:12 +00002544 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroffc0a123c2008-03-11 17:37:02 +00002545 superType, SourceLocation());
Ted Kremenek668bf912009-02-09 20:51:47 +00002546 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00002547 InitExprs.size(),
Ted Kremenek668bf912009-02-09 20:51:47 +00002548 superType, SourceLocation());
Steve Naroff46a98a72008-12-23 20:11:22 +00002549 // The code for super is a little tricky to prevent collision with
2550 // the structure definition in the header. The rewriter has it's own
2551 // internal definition (__rw_objc_super) that is uses. This is why
2552 // we need the cast below. For example:
2553 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2554 //
Ted Kremenek8189cde2009-02-07 01:47:29 +00002555 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002556 Context->getPointerType(SuperRep->getType()),
Steve Naroff46a98a72008-12-23 20:11:22 +00002557 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002558 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002559 CastExpr::CK_Unknown,
Steve Naroff46a98a72008-12-23 20:11:22 +00002560 SuperRep, Context->getPointerType(superType),
Mike Stump1eb44332009-09-09 15:08:12 +00002561 SourceLocation(), SourceLocation());
Steve Naroffc0a123c2008-03-11 17:37:02 +00002562 } else {
2563 // (struct objc_super) { <exprs from above> }
Mike Stump1eb44332009-09-09 15:08:12 +00002564 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2565 &InitExprs[0], InitExprs.size(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002566 SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00002567 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002568 }
Steve Naroff46a98a72008-12-23 20:11:22 +00002569 MsgExprs.push_back(SuperRep);
Steve Naroff874e2322007-11-15 10:28:18 +00002570 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002571 // Remove all type-casts because it may contain objc-style types; e.g.
2572 // Foo<Proto> *.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002573 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002574 recExpr = CE->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00002575 recExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002576 CastExpr::CK_Unknown, recExpr,
Mike Stump1eb44332009-09-09 15:08:12 +00002577 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002578 SourceLocation(), SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00002579 MsgExprs.push_back(recExpr);
2580 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002581 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00002582 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002583 llvm::SmallVector<Expr*, 8> SelExprs;
2584 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002585 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002586 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00002587 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00002588 false, argType, SourceLocation()));
Steve Naroff934f2762007-10-24 22:48:43 +00002589 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2590 &SelExprs[0], SelExprs.size());
2591 MsgExprs.push_back(SelExp);
Mike Stump1eb44332009-09-09 15:08:12 +00002592
Steve Naroff934f2762007-10-24 22:48:43 +00002593 // Now push any user supplied arguments.
2594 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002595 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002596 // Make all implicit casts explicit...ICE comes in handy:-)
2597 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2598 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregor49badde2008-10-27 19:41:14 +00002599 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002600 ? Context->getObjCIdType()
Douglas Gregor49badde2008-10-27 19:41:14 +00002601 : ICE->getType();
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002602 userExpr = new (Context) CStyleCastExpr(type, CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00002603 userExpr, type, SourceLocation(),
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002604 SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002605 }
2606 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002607 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002608 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002609 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002610 userExpr = CE->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00002611 userExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002612 CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00002613 userExpr, Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002614 SourceLocation(), SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002615 }
Mike Stump1eb44332009-09-09 15:08:12 +00002616 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002617 MsgExprs.push_back(userExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00002618 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2619 // out the argument in the original expression (since we aren't deleting
2620 // the ObjCMessageExpr). See RewritePropertySetter() usage for more info.
2621 //Exp->setArg(i, 0);
Steve Naroff934f2762007-10-24 22:48:43 +00002622 }
Steve Naroffab972d32007-11-04 22:37:50 +00002623 // Generate the funky cast.
2624 CastExpr *cast;
2625 llvm::SmallVector<QualType, 8> ArgTypes;
2626 QualType returnType;
Mike Stump1eb44332009-09-09 15:08:12 +00002627
Steve Naroffab972d32007-11-04 22:37:50 +00002628 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002629 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2630 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2631 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002632 ArgTypes.push_back(Context->getObjCIdType());
2633 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner89951a82009-02-20 18:43:26 +00002634 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002635 // Push any user argument types.
Chris Lattner89951a82009-02-20 18:43:26 +00002636 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2637 E = OMD->param_end(); PI != E; ++PI) {
2638 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump1eb44332009-09-09 15:08:12 +00002639 ? Context->getObjCIdType()
Chris Lattner89951a82009-02-20 18:43:26 +00002640 : (*PI)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00002641 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroff01f2ffa2008-12-11 21:05:33 +00002642 if (isTopLevelBlockPointerType(t)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002643 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroffa206b062008-10-29 14:49:46 +00002644 t = Context->getPointerType(BPT->getPointeeType());
2645 }
Steve Naroff352336b2007-11-05 14:36:37 +00002646 ArgTypes.push_back(t);
2647 }
Chris Lattner89951a82009-02-20 18:43:26 +00002648 returnType = OMD->getResultType()->isObjCQualifiedIdType()
2649 ? Context->getObjCIdType() : OMD->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00002650 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002651 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002652 }
2653 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002654 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002655
Steve Naroffab972d32007-11-04 22:37:50 +00002656 // Create a reference to the objc_msgSend() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00002657 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002658 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002659
Mike Stump1eb44332009-09-09 15:08:12 +00002660 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Naroffab972d32007-11-04 22:37:50 +00002661 // If we don't do this cast, we get the following bizarre warning/note:
2662 // xx.m:13: warning: function called through a non-compatible type
2663 // xx.m:13: note: if this code is reached, the program will abort
Mike Stump1eb44332009-09-09 15:08:12 +00002664 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy),
2665 CastExpr::CK_Unknown, DRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002666 Context->getPointerType(Context->VoidTy),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002667 SourceLocation(), SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002668
Steve Naroffab972d32007-11-04 22:37:50 +00002669 // Now do the "normal" pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00002670 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002671 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00002672 // If we don't have a method decl, force a variadic cast.
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002673 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Naroffab972d32007-11-04 22:37:50 +00002674 castType = Context->getPointerType(castType);
Mike Stump1eb44332009-09-09 15:08:12 +00002675 cast = new (Context) CStyleCastExpr(castType, CastExpr::CK_Unknown, cast,
2676 castType, SourceLocation(),
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002677 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002678
2679 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002680 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump1eb44332009-09-09 15:08:12 +00002681
John McCall183700f2009-09-21 23:43:11 +00002682 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00002683 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00002684 MsgExprs.size(),
Ted Kremenek668bf912009-02-09 20:51:47 +00002685 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002686 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002687 if (MsgSendStretFlavor) {
2688 // We have the method which returns a struct/union. Must also generate
2689 // call to objc_msgSend_stret and hang both varieties on a conditional
2690 // expression which dictate which one to envoke depending on size of
2691 // method's return type.
Mike Stump1eb44332009-09-09 15:08:12 +00002692
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002693 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00002694 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002695 SourceLocation());
2696 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Mike Stump1eb44332009-09-09 15:08:12 +00002697 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy),
2698 CastExpr::CK_Unknown, STDRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002699 Context->getPointerType(Context->VoidTy),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002700 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002701 // Now do the "normal" pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00002702 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002703 &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002704 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002705 castType = Context->getPointerType(castType);
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002706 cast = new (Context) CStyleCastExpr(castType, CastExpr::CK_Unknown,
2707 cast, castType, SourceLocation(), SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002708
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002709 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002710 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump1eb44332009-09-09 15:08:12 +00002711
John McCall183700f2009-09-21 23:43:11 +00002712 FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00002713 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00002714 MsgExprs.size(),
Ted Kremenek668bf912009-02-09 20:51:47 +00002715 FT->getResultType(), SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002716
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002717 // Build sizeof(returnType)
Mike Stump1eb44332009-09-09 15:08:12 +00002718 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
John McCalla93c9342009-12-07 02:54:59 +00002719 Context->getTrivialTypeSourceInfo(returnType),
Sebastian Redl05189992008-11-11 17:56:53 +00002720 Context->getSizeType(),
2721 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002722 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2723 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2724 // For X86 it is more complicated and some kind of target specific routine
2725 // is needed to decide what to do.
Mike Stump1eb44332009-09-09 15:08:12 +00002726 unsigned IntSize =
Chris Lattner98be4942008-03-05 18:54:05 +00002727 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Mike Stump1eb44332009-09-09 15:08:12 +00002728 IntegerLiteral *limit = new (Context) IntegerLiteral(llvm::APInt(IntSize, 8),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002729 Context->IntTy,
2730 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002731 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
2732 BinaryOperator::LE,
2733 Context->IntTy,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002734 SourceLocation());
2735 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump1eb44332009-09-09 15:08:12 +00002736 ConditionalOperator *CondExpr =
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00002737 new (Context) ConditionalOperator(lessThanExpr,
2738 SourceLocation(), CE,
2739 SourceLocation(), STCE, returnType);
Ted Kremenek8189cde2009-02-07 01:47:29 +00002740 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002741 }
Mike Stump1eb44332009-09-09 15:08:12 +00002742 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002743 return ReplacingStmt;
2744}
2745
Steve Naroffb29b4272008-04-14 22:03:09 +00002746Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002747 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Mike Stump1eb44332009-09-09 15:08:12 +00002748
Steve Naroff934f2762007-10-24 22:48:43 +00002749 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002750 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00002751
2752 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002753 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002754}
2755
Steve Naroff621edce2009-04-29 16:37:50 +00002756// typedef struct objc_object Protocol;
2757QualType RewriteObjC::getProtocolType() {
2758 if (!ProtocolTypeDecl) {
John McCalla93c9342009-12-07 02:54:59 +00002759 TypeSourceInfo *TInfo
2760 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroff621edce2009-04-29 16:37:50 +00002761 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002762 SourceLocation(),
Steve Naroff621edce2009-04-29 16:37:50 +00002763 &Context->Idents.get("Protocol"),
John McCalla93c9342009-12-07 02:54:59 +00002764 TInfo);
Steve Naroff621edce2009-04-29 16:37:50 +00002765 }
2766 return Context->getTypeDeclType(ProtocolTypeDecl);
2767}
2768
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002769/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroff621edce2009-04-29 16:37:50 +00002770/// a synthesized/forward data reference (to the protocol's metadata).
2771/// The forward references (and metadata) are generated in
2772/// RewriteObjC::HandleTranslationUnit().
Steve Naroffb29b4272008-04-14 22:03:09 +00002773Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroff621edce2009-04-29 16:37:50 +00002774 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
2775 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00002776 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Douglas Gregor0da76df2009-11-23 11:41:28 +00002777 ID, getProtocolType(), 0, VarDecl::Extern);
Steve Naroff621edce2009-04-29 16:37:50 +00002778 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), SourceLocation());
2779 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
2780 Context->getPointerType(DRE->getType()),
2781 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002782 CastExpr *castExpr = new (Context) CStyleCastExpr(DerefExpr->getType(),
2783 CastExpr::CK_Unknown,
2784 DerefExpr, DerefExpr->getType(),
Steve Naroff621edce2009-04-29 16:37:50 +00002785 SourceLocation(), SourceLocation());
2786 ReplaceStmt(Exp, castExpr);
2787 ProtocolExprDecls.insert(Exp->getProtocol());
Mike Stump1eb44332009-09-09 15:08:12 +00002788 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00002789 return castExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00002790
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002791}
2792
Mike Stump1eb44332009-09-09 15:08:12 +00002793bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffbaf58c32008-05-31 14:15:04 +00002794 const char *endBuf) {
2795 while (startBuf < endBuf) {
2796 if (*startBuf == '#') {
2797 // Skip whitespace.
2798 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2799 ;
2800 if (!strncmp(startBuf, "if", strlen("if")) ||
2801 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2802 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2803 !strncmp(startBuf, "define", strlen("define")) ||
2804 !strncmp(startBuf, "undef", strlen("undef")) ||
2805 !strncmp(startBuf, "else", strlen("else")) ||
2806 !strncmp(startBuf, "elif", strlen("elif")) ||
2807 !strncmp(startBuf, "endif", strlen("endif")) ||
2808 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2809 !strncmp(startBuf, "include", strlen("include")) ||
2810 !strncmp(startBuf, "import", strlen("import")) ||
2811 !strncmp(startBuf, "include_next", strlen("include_next")))
2812 return true;
2813 }
2814 startBuf++;
2815 }
2816 return false;
2817}
2818
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002819/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002820/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00002821void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002822 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002823 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Mike Stump1eb44332009-09-09 15:08:12 +00002824 assert(CDecl->getNameAsCString() &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002825 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002826 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002827 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002828 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002829 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002830 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00002831 SourceLocation LocStart = CDecl->getLocStart();
2832 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00002833
Steve Narofffea763e82007-11-14 19:25:57 +00002834 const char *startBuf = SM->getCharacterData(LocStart);
2835 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump1eb44332009-09-09 15:08:12 +00002836
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002837 // If no ivars and no root or if its root, directly or indirectly,
2838 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002839 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2840 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner2c78b872009-04-14 23:22:57 +00002841 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Chris Lattneraadaf782008-01-31 19:51:04 +00002842 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002843 return;
2844 }
Mike Stump1eb44332009-09-09 15:08:12 +00002845
2846 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002847 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002848 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002849 Result += CDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002850 if (LangOpts.Microsoft)
2851 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00002852
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002853 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002854 const char *cursor = strchr(startBuf, '{');
Mike Stump1eb44332009-09-09 15:08:12 +00002855 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002856 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00002857 // If the buffer contains preprocessor directives, we do more fine-grained
2858 // rewrites. This is intended to fix code that looks like (which occurs in
2859 // NSURL.h, for example):
2860 //
2861 // #ifdef XYZ
2862 // @interface Foo : NSObject
2863 // #else
2864 // @interface FooBar : NSObject
2865 // #endif
2866 // {
2867 // int i;
2868 // }
2869 // @end
2870 //
2871 // This clause is segregated to avoid breaking the common case.
2872 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002873 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffbaf58c32008-05-31 14:15:04 +00002874 CDecl->getClassLoc();
2875 const char *endHeader = SM->getCharacterData(L);
Chris Lattner2c78b872009-04-14 23:22:57 +00002876 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffbaf58c32008-05-31 14:15:04 +00002877
Chris Lattnercafeb352009-02-20 18:18:36 +00002878 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00002879 // advance to the end of the referenced protocols.
2880 while (endHeader < cursor && *endHeader != '>') endHeader++;
2881 endHeader++;
2882 }
2883 // rewrite the original header
2884 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2885 } else {
2886 // rewrite the original header *without* disturbing the '{'
Steve Naroff17c87782009-12-04 21:36:32 +00002887 ReplaceText(LocStart, cursor-startBuf, Result.c_str(), Result.size());
Steve Naroffbaf58c32008-05-31 14:15:04 +00002888 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002889 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002890 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002891 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002892 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002893 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00002894 Result += "_IVARS;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002895
Steve Narofffea763e82007-11-14 19:25:57 +00002896 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002897 SourceLocation OnePastCurly =
2898 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2899 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002900 }
2901 cursor++; // past '{'
Mike Stump1eb44332009-09-09 15:08:12 +00002902
Steve Narofffea763e82007-11-14 19:25:57 +00002903 // Now comment out any visibility specifiers.
2904 while (cursor < endBuf) {
2905 if (*cursor == '@') {
2906 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002907 // Skip whitespace.
2908 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2909 /*scan*/;
2910
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002911 // FIXME: presence of @public, etc. inside comment results in
2912 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002913 if (!strncmp(cursor, "public", strlen("public")) ||
2914 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00002915 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002916 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002917 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002918 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002919 // FIXME: If there are cases where '<' is used in ivar declaration part
2920 // of user code, then scan the ivar list and use needToScanForQualifiers
2921 // for type checking.
2922 else if (*cursor == '<') {
2923 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002924 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002925 cursor = strchr(cursor, '>');
2926 cursor++;
2927 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002928 InsertText(atLoc, " */", 3);
Steve Naroffced80a82008-10-30 12:09:33 +00002929 } else if (*cursor == '^') { // rewrite block specifier.
2930 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2931 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002932 }
Steve Narofffea763e82007-11-14 19:25:57 +00002933 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002934 }
Steve Narofffea763e82007-11-14 19:25:57 +00002935 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002936 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00002937 } else { // we don't have any instance variables - insert super struct.
Chris Lattner2c78b872009-04-14 23:22:57 +00002938 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Narofffea763e82007-11-14 19:25:57 +00002939 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002940 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002941 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002942 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00002943 Result += "_IVARS;\n};\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00002944 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002945 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002946 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002947 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00002948 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002949}
2950
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002951// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002952/// class methods.
Douglas Gregor653f1b12009-04-23 01:02:12 +00002953template<typename MethodIterator>
2954void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
2955 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002956 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002957 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002958 const char *ClassName,
2959 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002960 if (MethodBegin == MethodEnd) return;
Mike Stump1eb44332009-09-09 15:08:12 +00002961
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002962 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002963 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002964 SEL _cmd;
2965 char *method_types;
2966 void *_imp;
2967 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002968 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002969 Result += "\nstruct _objc_method {\n";
2970 Result += "\tSEL _cmd;\n";
2971 Result += "\tchar *method_types;\n";
2972 Result += "\tvoid *_imp;\n";
2973 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002974
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002975 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002976 }
Mike Stump1eb44332009-09-09 15:08:12 +00002977
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002978 // Build _objc_method_list for class's methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00002979
Steve Naroff946a6932008-03-11 00:12:29 +00002980 /* struct {
2981 struct _objc_method_list *next_method;
2982 int method_count;
2983 struct _objc_method method_list[];
2984 }
2985 */
Douglas Gregor653f1b12009-04-23 01:02:12 +00002986 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroff946a6932008-03-11 00:12:29 +00002987 Result += "\nstatic struct {\n";
2988 Result += "\tstruct _objc_method_list *next_method;\n";
2989 Result += "\tint method_count;\n";
2990 Result += "\tstruct _objc_method method_list[";
Douglas Gregor653f1b12009-04-23 01:02:12 +00002991 Result += utostr(NumMethods);
Steve Naroff946a6932008-03-11 00:12:29 +00002992 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002993 Result += prefix;
2994 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2995 Result += "_METHODS_";
2996 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002997 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002998 Result += IsInstanceMethod ? "inst" : "cls";
2999 Result += "_meth\")))= ";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003000 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003001
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003002 Result += "\t,{{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003003 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003004 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003005 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003006 Result += "\", \"";
3007 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003008 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003009 Result += MethodInternalNames[*MethodBegin];
3010 Result += "}\n";
3011 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3012 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003013 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003014 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003015 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003016 Result += "\", \"";
3017 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003018 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003019 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00003020 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003021 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003022 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003023}
3024
Steve Naroff621edce2009-04-29 16:37:50 +00003025/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00003026void RewriteObjC::
Steve Naroff621edce2009-04-29 16:37:50 +00003027RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, const char *prefix,
3028 const char *ClassName, std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003029 static bool objc_protocol_methods = false;
Steve Naroff621edce2009-04-29 16:37:50 +00003030
3031 // Output struct protocol_methods holder of method selector and type.
3032 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3033 /* struct protocol_methods {
3034 SEL _cmd;
3035 char *method_types;
3036 }
3037 */
3038 Result += "\nstruct _protocol_methods {\n";
3039 Result += "\tstruct objc_selector *_cmd;\n";
3040 Result += "\tchar *method_types;\n";
3041 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003042
Steve Naroff621edce2009-04-29 16:37:50 +00003043 objc_protocol_methods = true;
3044 }
3045 // Do not synthesize the protocol more than once.
3046 if (ObjCSynthesizedProtocols.count(PDecl))
3047 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003048
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003049 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3050 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3051 PDecl->instmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003052 /* struct _objc_protocol_method_list {
3053 int protocol_method_count;
3054 struct protocol_methods protocols[];
3055 }
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003056 */
Steve Naroff621edce2009-04-29 16:37:50 +00003057 Result += "\nstatic struct {\n";
3058 Result += "\tint protocol_method_count;\n";
3059 Result += "\tstruct _protocol_methods protocol_methods[";
3060 Result += utostr(NumMethods);
3061 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3062 Result += PDecl->getNameAsString();
3063 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3064 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003065
Steve Naroff621edce2009-04-29 16:37:50 +00003066 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003067 for (ObjCProtocolDecl::instmeth_iterator
3068 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003069 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003070 if (I == PDecl->instmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003071 Result += "\t ,{{(struct objc_selector *)\"";
3072 else
3073 Result += "\t ,{(struct objc_selector *)\"";
3074 Result += (*I)->getSelector().getAsString().c_str();
3075 std::string MethodTypeString;
3076 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3077 Result += "\", \"";
3078 Result += MethodTypeString;
3079 Result += "\"}\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003080 }
Steve Naroff621edce2009-04-29 16:37:50 +00003081 Result += "\t }\n};\n";
3082 }
Mike Stump1eb44332009-09-09 15:08:12 +00003083
Steve Naroff621edce2009-04-29 16:37:50 +00003084 // Output class methods declared in this protocol.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003085 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3086 PDecl->classmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003087 if (NumMethods > 0) {
3088 /* struct _objc_protocol_method_list {
3089 int protocol_method_count;
3090 struct protocol_methods protocols[];
3091 }
3092 */
3093 Result += "\nstatic struct {\n";
3094 Result += "\tint protocol_method_count;\n";
3095 Result += "\tstruct _protocol_methods protocol_methods[";
3096 Result += utostr(NumMethods);
3097 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3098 Result += PDecl->getNameAsString();
3099 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3100 "{\n\t";
3101 Result += utostr(NumMethods);
3102 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003103
Steve Naroff621edce2009-04-29 16:37:50 +00003104 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003105 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003106 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003107 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003108 if (I == PDecl->classmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003109 Result += "\t ,{{(struct objc_selector *)\"";
3110 else
3111 Result += "\t ,{(struct objc_selector *)\"";
3112 Result += (*I)->getSelector().getAsString().c_str();
3113 std::string MethodTypeString;
3114 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3115 Result += "\", \"";
3116 Result += MethodTypeString;
3117 Result += "\"}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003118 }
Steve Naroff621edce2009-04-29 16:37:50 +00003119 Result += "\t }\n};\n";
3120 }
3121
3122 // Output:
3123 /* struct _objc_protocol {
3124 // Objective-C 1.0 extensions
3125 struct _objc_protocol_extension *isa;
3126 char *protocol_name;
3127 struct _objc_protocol **protocol_list;
3128 struct _objc_protocol_method_list *instance_methods;
3129 struct _objc_protocol_method_list *class_methods;
Mike Stump1eb44332009-09-09 15:08:12 +00003130 };
Steve Naroff621edce2009-04-29 16:37:50 +00003131 */
3132 static bool objc_protocol = false;
3133 if (!objc_protocol) {
3134 Result += "\nstruct _objc_protocol {\n";
3135 Result += "\tstruct _objc_protocol_extension *isa;\n";
3136 Result += "\tchar *protocol_name;\n";
3137 Result += "\tstruct _objc_protocol **protocol_list;\n";
3138 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3139 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003140 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003141
Steve Naroff621edce2009-04-29 16:37:50 +00003142 objc_protocol = true;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003143 }
Mike Stump1eb44332009-09-09 15:08:12 +00003144
Steve Naroff621edce2009-04-29 16:37:50 +00003145 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3146 Result += PDecl->getNameAsString();
3147 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3148 "{\n\t0, \"";
3149 Result += PDecl->getNameAsString();
3150 Result += "\", 0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003151 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003152 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3153 Result += PDecl->getNameAsString();
3154 Result += ", ";
3155 }
3156 else
3157 Result += "0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003158 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003159 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3160 Result += PDecl->getNameAsString();
3161 Result += "\n";
3162 }
3163 else
3164 Result += "0\n";
3165 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003166
Steve Naroff621edce2009-04-29 16:37:50 +00003167 // Mark this protocol as having been generated.
3168 if (!ObjCSynthesizedProtocols.insert(PDecl))
3169 assert(false && "protocol already synthesized");
3170
3171}
3172
3173void RewriteObjC::
3174RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
3175 const char *prefix, const char *ClassName,
3176 std::string &Result) {
3177 if (Protocols.empty()) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003178
Steve Naroff621edce2009-04-29 16:37:50 +00003179 for (unsigned i = 0; i != Protocols.size(); i++)
3180 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3181
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003182 // Output the top lovel protocol meta-data for the class.
3183 /* struct _objc_protocol_list {
3184 struct _objc_protocol_list *next;
3185 int protocol_count;
3186 struct _objc_protocol *class_protocols[];
3187 }
3188 */
3189 Result += "\nstatic struct {\n";
3190 Result += "\tstruct _objc_protocol_list *next;\n";
3191 Result += "\tint protocol_count;\n";
3192 Result += "\tstruct _objc_protocol *class_protocols[";
3193 Result += utostr(Protocols.size());
3194 Result += "];\n} _OBJC_";
3195 Result += prefix;
3196 Result += "_PROTOCOLS_";
3197 Result += ClassName;
3198 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3199 "{\n\t0, ";
3200 Result += utostr(Protocols.size());
3201 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003202
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003203 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003204 Result += Protocols[0]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003205 Result += " \n";
Mike Stump1eb44332009-09-09 15:08:12 +00003206
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003207 for (unsigned i = 1; i != Protocols.size(); i++) {
3208 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003209 Result += Protocols[i]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003210 Result += "\n";
3211 }
3212 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003213}
3214
Steve Naroff621edce2009-04-29 16:37:50 +00003215
Mike Stump1eb44332009-09-09 15:08:12 +00003216/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003217/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00003218void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003219 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003220 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003221 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003222 ObjCCategoryDecl *CDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00003223 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003224 CDecl = CDecl->getNextClassCategory())
3225 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3226 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003227
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003228 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00003229 FullCategoryName += '_';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003230 FullCategoryName += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003231
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003232 // Build _objc_method_list for class's instance methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003233 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003234 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003235
3236 // If any of our property implementations have associated getters or
3237 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003238 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3239 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003240 Prop != PropEnd; ++Prop) {
3241 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3242 continue;
3243 if (!(*Prop)->getPropertyIvarDecl())
3244 continue;
3245 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3246 if (!PD)
3247 continue;
3248 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3249 InstanceMethods.push_back(Getter);
3250 if (PD->isReadOnly())
3251 continue;
3252 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3253 InstanceMethods.push_back(Setter);
3254 }
3255 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003256 true, "CATEGORY_", FullCategoryName.c_str(),
3257 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003258
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003259 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003260 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003261 false, "CATEGORY_", FullCategoryName.c_str(),
3262 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003263
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003264 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00003265 // Null CDecl is case of a category implementation with no category interface
3266 if (CDecl)
Steve Naroff621edce2009-04-29 16:37:50 +00003267 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
3268 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003269 /* struct _objc_category {
3270 char *category_name;
3271 char *class_name;
3272 struct _objc_method_list *instance_methods;
3273 struct _objc_method_list *class_methods;
3274 struct _objc_protocol_list *protocols;
3275 // Objective-C 1.0 extensions
3276 uint32_t size; // sizeof (struct _objc_category)
Mike Stump1eb44332009-09-09 15:08:12 +00003277 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003278 // @property decl.
Mike Stump1eb44332009-09-09 15:08:12 +00003279 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003280 */
Mike Stump1eb44332009-09-09 15:08:12 +00003281
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003282 static bool objc_category = false;
3283 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003284 Result += "\nstruct _objc_category {\n";
3285 Result += "\tchar *category_name;\n";
3286 Result += "\tchar *class_name;\n";
3287 Result += "\tstruct _objc_method_list *instance_methods;\n";
3288 Result += "\tstruct _objc_method_list *class_methods;\n";
3289 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003290 Result += "\tunsigned int size;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003291 Result += "\tstruct _objc_property_list *instance_properties;\n";
3292 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003293 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003294 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003295 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3296 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003297 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003298 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003299 Result += "\"\n\t, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003300 Result += ClassDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003301 Result += "\"\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003302
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003303 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003304 Result += "\t, (struct _objc_method_list *)"
3305 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3306 Result += FullCategoryName;
3307 Result += "\n";
3308 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003309 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003310 Result += "\t, 0\n";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003311 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003312 Result += "\t, (struct _objc_method_list *)"
3313 "&_OBJC_CATEGORY_CLASS_METHODS_";
3314 Result += FullCategoryName;
3315 Result += "\n";
3316 }
3317 else
3318 Result += "\t, 0\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003319
Chris Lattnercafeb352009-02-20 18:18:36 +00003320 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003321 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003322 Result += FullCategoryName;
3323 Result += "\n";
3324 }
3325 else
3326 Result += "\t, 0\n";
3327 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003328}
3329
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003330/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3331/// ivar offset.
Mike Stump1eb44332009-09-09 15:08:12 +00003332void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
3333 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003334 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00003335 if (ivar->isBitField()) {
3336 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3337 // place all bitfields at offset 0.
3338 Result += "0";
3339 } else {
3340 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003341 Result += IDecl->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003342 if (LangOpts.Microsoft)
3343 Result += "_IMPL";
3344 Result += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003345 Result += ivar->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003346 Result += ")";
3347 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003348}
3349
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003350//===----------------------------------------------------------------------===//
3351// Meta Data Emission
3352//===----------------------------------------------------------------------===//
3353
Steve Naroffb29b4272008-04-14 22:03:09 +00003354void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003355 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003356 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00003357
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003358 // Explictly declared @interface's are already synthesized.
Steve Naroff33feeb02009-04-20 20:09:33 +00003359 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003360 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003361 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003362 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003363 }
Mike Stump1eb44332009-09-09 15:08:12 +00003364
Chris Lattnerbe6df082007-12-12 07:56:42 +00003365 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003366 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump1eb44332009-09-09 15:08:12 +00003367 ? IDecl->ivar_size()
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003368 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003369 if (NumIvars > 0) {
3370 static bool objc_ivar = false;
3371 if (!objc_ivar) {
3372 /* struct _objc_ivar {
3373 char *ivar_name;
3374 char *ivar_type;
3375 int ivar_offset;
Mike Stump1eb44332009-09-09 15:08:12 +00003376 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003377 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003378 Result += "\nstruct _objc_ivar {\n";
3379 Result += "\tchar *ivar_name;\n";
3380 Result += "\tchar *ivar_type;\n";
3381 Result += "\tint ivar_offset;\n";
3382 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003383
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003384 objc_ivar = true;
3385 }
3386
Steve Naroff946a6932008-03-11 00:12:29 +00003387 /* struct {
3388 int ivar_count;
3389 struct _objc_ivar ivar_list[nIvars];
Mike Stump1eb44332009-09-09 15:08:12 +00003390 };
Steve Naroff946a6932008-03-11 00:12:29 +00003391 */
Mike Stump1eb44332009-09-09 15:08:12 +00003392 Result += "\nstatic struct {\n";
Steve Naroff946a6932008-03-11 00:12:29 +00003393 Result += "\tint ivar_count;\n";
3394 Result += "\tstruct _objc_ivar ivar_list[";
3395 Result += utostr(NumIvars);
3396 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003397 Result += IDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003398 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003399 "{\n\t";
3400 Result += utostr(NumIvars);
3401 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003402
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003403 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003404 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003405 if (!IDecl->ivar_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003406 for (ObjCImplementationDecl::ivar_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003407 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003408 IV != IVEnd; ++IV)
3409 IVars.push_back(*IV);
3410 IVI = IVars.begin();
3411 IVE = IVars.end();
Chris Lattnerbe6df082007-12-12 07:56:42 +00003412 } else {
3413 IVI = CDecl->ivar_begin();
3414 IVE = CDecl->ivar_end();
3415 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003416 Result += "\t,{{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003417 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003418 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003419 std::string TmpString, StrEncoding;
3420 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3421 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003422 Result += StrEncoding;
3423 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003424 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003425 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003426 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003427 Result += "\t ,{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003428 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003429 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003430 std::string TmpString, StrEncoding;
3431 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3432 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003433 Result += StrEncoding;
3434 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003435 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003436 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003437 }
Mike Stump1eb44332009-09-09 15:08:12 +00003438
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003439 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003440 }
Mike Stump1eb44332009-09-09 15:08:12 +00003441
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003442 // Build _objc_method_list for class's instance methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003443 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003444 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003445
3446 // If any of our property implementations have associated getters or
3447 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003448 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3449 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003450 Prop != PropEnd; ++Prop) {
3451 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3452 continue;
3453 if (!(*Prop)->getPropertyIvarDecl())
3454 continue;
3455 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3456 if (!PD)
3457 continue;
3458 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3459 InstanceMethods.push_back(Getter);
3460 if (PD->isReadOnly())
3461 continue;
3462 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3463 InstanceMethods.push_back(Setter);
3464 }
3465 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003466 true, "", IDecl->getNameAsCString(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003467
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003468 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003469 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003470 false, "", IDecl->getNameAsCString(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003471
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003472 // Protocols referenced in class declaration?
Steve Naroff621edce2009-04-29 16:37:50 +00003473 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
3474 "CLASS", CDecl->getNameAsCString(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003475
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003476 // Declaration of class/meta-class metadata
3477 /* struct _objc_class {
3478 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003479 const char *super_class_name;
3480 char *name;
3481 long version;
3482 long info;
3483 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003484 struct _objc_ivar_list *ivars;
3485 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003486 struct objc_cache *cache;
3487 struct objc_protocol_list *protocols;
3488 const char *ivar_layout;
3489 struct _objc_class_ext *ext;
Mike Stump1eb44332009-09-09 15:08:12 +00003490 };
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003491 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003492 static bool objc_class = false;
3493 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003494 Result += "\nstruct _objc_class {\n";
3495 Result += "\tstruct _objc_class *isa;\n";
3496 Result += "\tconst char *super_class_name;\n";
3497 Result += "\tchar *name;\n";
3498 Result += "\tlong version;\n";
3499 Result += "\tlong info;\n";
3500 Result += "\tlong instance_size;\n";
3501 Result += "\tstruct _objc_ivar_list *ivars;\n";
3502 Result += "\tstruct _objc_method_list *methods;\n";
3503 Result += "\tstruct objc_cache *cache;\n";
3504 Result += "\tstruct _objc_protocol_list *protocols;\n";
3505 Result += "\tconst char *ivar_layout;\n";
3506 Result += "\tstruct _objc_class_ext *ext;\n";
3507 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003508 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003509 }
Mike Stump1eb44332009-09-09 15:08:12 +00003510
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003511 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003512 ObjCInterfaceDecl *RootClass = 0;
3513 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003514 while (SuperClass) {
3515 RootClass = SuperClass;
3516 SuperClass = SuperClass->getSuperClass();
3517 }
3518 SuperClass = CDecl->getSuperClass();
Mike Stump1eb44332009-09-09 15:08:12 +00003519
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003520 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003521 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003522 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003523 "{\n\t(struct _objc_class *)\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003524 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003525 Result += "\"";
3526
3527 if (SuperClass) {
3528 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003529 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003530 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003531 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003532 Result += "\"";
3533 }
3534 else {
3535 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003536 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003537 Result += "\"";
3538 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003539 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003540 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003541 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003542 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff23f41272008-03-11 18:14:26 +00003543 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003544 Result += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003545 Result += "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003546 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003547 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003548 Result += ", 0\n";
Chris Lattnercafeb352009-02-20 18:18:36 +00003549 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003550 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003551 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003552 Result += ",0,0\n";
3553 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003554 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003555 Result += "\t,0,0,0,0\n";
3556 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003557
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003558 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003559 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003560 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003561 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003562 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003563 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003564 if (SuperClass) {
3565 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003566 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003567 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003568 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003569 Result += "\"";
3570 }
3571 else {
3572 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003573 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003574 Result += "\"";
3575 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003576 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003577 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003578 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003579 Result += ",0";
3580 else {
3581 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003582 Result += ",sizeof(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003583 Result += CDecl->getNameAsString();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003584 if (LangOpts.Microsoft)
3585 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003586 Result += ")";
3587 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003588 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00003589 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003590 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003591 Result += "\n\t";
3592 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003593 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003594 Result += ",0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003595 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroff946a6932008-03-11 00:12:29 +00003596 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003597 Result += CDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003598 Result += ", 0\n\t";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003599 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003600 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003601 Result += ",0,0";
Chris Lattnercafeb352009-02-20 18:18:36 +00003602 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003603 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003604 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003605 Result += ", 0,0\n";
3606 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003607 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003608 Result += ",0,0,0\n";
3609 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003610}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003611
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003612/// RewriteImplementations - This routine rewrites all method implementations
3613/// and emits meta-data.
3614
Steve Narofface66252008-11-13 20:07:04 +00003615void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003616 int ClsDefCount = ClassImplementation.size();
3617 int CatDefCount = CategoryImplementation.size();
Mike Stump1eb44332009-09-09 15:08:12 +00003618
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003619 // Rewrite implemented methods
3620 for (int i = 0; i < ClsDefCount; i++)
3621 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00003622
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003623 for (int i = 0; i < CatDefCount; i++)
3624 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00003625}
Mike Stump1eb44332009-09-09 15:08:12 +00003626
Steve Narofface66252008-11-13 20:07:04 +00003627void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3628 int ClsDefCount = ClassImplementation.size();
3629 int CatDefCount = CategoryImplementation.size();
3630
Steve Naroff5df5b762008-05-07 21:23:49 +00003631 // This is needed for determining instance variable offsets.
Fariborz Jahanianc98cbb42010-01-07 18:31:42 +00003632 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003633 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003634 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003635 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003636
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003637 // For each implemented category, write out all its meta data.
3638 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003639 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroff621edce2009-04-29 16:37:50 +00003640
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003641 // Write objc_symtab metadata
3642 /*
3643 struct _objc_symtab
3644 {
3645 long sel_ref_cnt;
3646 SEL *refs;
3647 short cls_def_cnt;
3648 short cat_def_cnt;
3649 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump1eb44332009-09-09 15:08:12 +00003650 };
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003651 */
Mike Stump1eb44332009-09-09 15:08:12 +00003652
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003653 Result += "\nstruct _objc_symtab {\n";
3654 Result += "\tlong sel_ref_cnt;\n";
3655 Result += "\tSEL *refs;\n";
3656 Result += "\tshort cls_def_cnt;\n";
3657 Result += "\tshort cat_def_cnt;\n";
3658 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3659 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003660
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003661 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00003662 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003663 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003664 + ", " + utostr(CatDefCount) + "\n";
3665 for (int i = 0; i < ClsDefCount; i++) {
3666 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003667 Result += ClassImplementation[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 for (int i = 0; i < CatDefCount; i++) {
3672 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003673 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003674 Result += "_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003675 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003676 Result += "\n";
3677 }
Mike Stump1eb44332009-09-09 15:08:12 +00003678
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003679 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003680
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003681 // Write objc_module metadata
Mike Stump1eb44332009-09-09 15:08:12 +00003682
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003683 /*
3684 struct _objc_module {
3685 long version;
3686 long size;
3687 const char *name;
3688 struct _objc_symtab *symtab;
3689 }
3690 */
Mike Stump1eb44332009-09-09 15:08:12 +00003691
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003692 Result += "\nstruct _objc_module {\n";
3693 Result += "\tlong version;\n";
3694 Result += "\tlong size;\n";
3695 Result += "\tconst char *name;\n";
3696 Result += "\tstruct _objc_symtab *symtab;\n";
3697 Result += "};\n\n";
3698 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00003699 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003700 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003701 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003702 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003703
3704 if (LangOpts.Microsoft) {
Steve Naroff621edce2009-04-29 16:37:50 +00003705 if (ProtocolExprDecls.size()) {
3706 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
3707 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003708 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00003709 E = ProtocolExprDecls.end(); I != E; ++I) {
3710 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
3711 Result += (*I)->getNameAsString();
3712 Result += " = &_OBJC_PROTOCOL_";
3713 Result += (*I)->getNameAsString();
3714 Result += ";\n";
3715 }
3716 Result += "#pragma data_seg(pop)\n\n";
3717 }
Steve Naroff4f943c22008-03-10 20:43:59 +00003718 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00003719 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003720 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3721 Result += "&_OBJC_MODULES;\n";
3722 Result += "#pragma data_seg(pop)\n\n";
3723 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003724}
Chris Lattner311ff022007-10-16 22:36:42 +00003725
Steve Naroff54055232008-10-27 17:20:55 +00003726std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3727 const char *funcName,
3728 std::string Tag) {
3729 const FunctionType *AFT = CE->getFunctionType();
3730 QualType RT = AFT->getResultType();
3731 std::string StructRef = "struct " + Tag;
3732 std::string S = "static " + RT.getAsString() + " __" +
3733 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003734
Steve Naroff54055232008-10-27 17:20:55 +00003735 BlockDecl *BD = CE->getBlockDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00003736
Douglas Gregor72564e72009-02-26 23:50:07 +00003737 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003738 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Naroffdf8570d2009-02-02 17:19:26 +00003739 // block (to reference imported block decl refs).
3740 S += "(" + StructRef + " *__cself)";
Steve Naroff54055232008-10-27 17:20:55 +00003741 } else if (BD->param_empty()) {
3742 S += "(" + StructRef + " *__cself)";
3743 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00003744 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff54055232008-10-27 17:20:55 +00003745 assert(FT && "SynthesizeBlockFunc: No function proto");
3746 S += '(';
3747 // first add the implicit argument.
3748 S += StructRef + " *__cself, ";
3749 std::string ParamStr;
3750 for (BlockDecl::param_iterator AI = BD->param_begin(),
3751 E = BD->param_end(); AI != E; ++AI) {
3752 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003753 ParamStr = (*AI)->getNameAsString();
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00003754 (*AI)->getType().getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00003755 S += ParamStr;
3756 }
3757 if (FT->isVariadic()) {
3758 if (!BD->param_empty()) S += ", ";
3759 S += "...";
3760 }
3761 S += ')';
3762 }
3763 S += " {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003764
Steve Naroff54055232008-10-27 17:20:55 +00003765 // Create local declarations to avoid rewriting all closure decl ref exprs.
3766 // First, emit a declaration for all "by ref" decls.
Mike Stump1eb44332009-09-09 15:08:12 +00003767 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003768 E = BlockByRefDecls.end(); I != E; ++I) {
3769 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003770 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00003771 std::string TypeString = "struct __Block_byref_" + Name + " *";
3772 Name = TypeString + Name;
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003773 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003774 }
Steve Naroff54055232008-10-27 17:20:55 +00003775 // Next, emit a declaration for all "by copy" declarations.
Mike Stump1eb44332009-09-09 15:08:12 +00003776 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003777 E = BlockByCopyDecls.end(); I != E; ++I) {
3778 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003779 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003780 // Handle nested closure invocation. For example:
3781 //
3782 // void (^myImportedClosure)(void);
3783 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00003784 //
Steve Naroff54055232008-10-27 17:20:55 +00003785 // void (^anotherClosure)(void);
3786 // anotherClosure = ^(void) {
3787 // myImportedClosure(); // import and invoke the closure
3788 // };
3789 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003790 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00003791 S += "struct __block_impl *";
3792 else
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00003793 (*I)->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003794 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff54055232008-10-27 17:20:55 +00003795 }
3796 std::string RewrittenStr = RewrittenBlockExprs[CE];
3797 const char *cstr = RewrittenStr.c_str();
3798 while (*cstr++ != '{') ;
3799 S += cstr;
3800 S += "\n";
3801 return S;
3802}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003803
Steve Naroff54055232008-10-27 17:20:55 +00003804std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3805 const char *funcName,
3806 std::string Tag) {
3807 std::string StructRef = "struct " + Tag;
3808 std::string S = "static void __";
Mike Stump1eb44332009-09-09 15:08:12 +00003809
Steve Naroff54055232008-10-27 17:20:55 +00003810 S += funcName;
3811 S += "_block_copy_" + utostr(i);
3812 S += "(" + StructRef;
3813 S += "*dst, " + StructRef;
3814 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00003815 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003816 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00003817 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003818 S += (*I)->getNameAsString();
Steve Naroff47a24222008-12-11 20:51:38 +00003819 S += ", (void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003820 S += (*I)->getNameAsString();
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00003821 if (BlockByRefDecls.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00003822 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00003823 else
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00003824 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00003825 }
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00003826 S += "}\n";
3827
Steve Naroff54055232008-10-27 17:20:55 +00003828 S += "\nstatic void __";
3829 S += funcName;
3830 S += "_block_dispose_" + utostr(i);
3831 S += "(" + StructRef;
3832 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00003833 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003834 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00003835 S += "_Block_object_dispose((void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003836 S += (*I)->getNameAsString();
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00003837 if (BlockByRefDecls.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00003838 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00003839 else
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00003840 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00003841 }
Mike Stump1eb44332009-09-09 15:08:12 +00003842 S += "}\n";
Steve Naroff54055232008-10-27 17:20:55 +00003843 return S;
3844}
3845
Steve Naroff01aec112009-12-06 21:14:13 +00003846std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3847 std::string Desc) {
Steve Naroffced80a82008-10-30 12:09:33 +00003848 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00003849 std::string Constructor = " " + Tag;
Mike Stump1eb44332009-09-09 15:08:12 +00003850
Steve Naroff54055232008-10-27 17:20:55 +00003851 S += " {\n struct __block_impl impl;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003852 S += " struct " + Desc;
3853 S += "* Desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003854
Steve Naroff01aec112009-12-06 21:14:13 +00003855 Constructor += "(void *fp, "; // Invoke function pointer.
3856 Constructor += "struct " + Desc; // Descriptor pointer.
3857 Constructor += " *desc";
Mike Stump1eb44332009-09-09 15:08:12 +00003858
Steve Naroff54055232008-10-27 17:20:55 +00003859 if (BlockDeclRefs.size()) {
3860 // Output all "by copy" declarations.
Mike Stump1eb44332009-09-09 15:08:12 +00003861 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003862 E = BlockByCopyDecls.end(); I != E; ++I) {
3863 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003864 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003865 std::string ArgName = "_" + FieldName;
3866 // Handle nested closure invocation. For example:
3867 //
3868 // void (^myImportedBlock)(void);
3869 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00003870 //
Steve Naroff54055232008-10-27 17:20:55 +00003871 // void (^anotherBlock)(void);
3872 // anotherBlock = ^(void) {
3873 // myImportedBlock(); // import and invoke the closure
3874 // };
3875 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003876 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00003877 S += "struct __block_impl *";
3878 Constructor += ", void *" + ArgName;
3879 } else {
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00003880 (*I)->getType().getAsStringInternal(FieldName, Context->PrintingPolicy);
3881 (*I)->getType().getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00003882 Constructor += ", " + ArgName;
3883 }
3884 S += FieldName + ";\n";
3885 }
3886 // Output all "by ref" declarations.
Mike Stump1eb44332009-09-09 15:08:12 +00003887 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003888 E = BlockByRefDecls.end(); I != E; ++I) {
3889 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003890 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003891 std::string ArgName = "_" + FieldName;
3892 // Handle nested closure invocation. For example:
3893 //
3894 // void (^myImportedBlock)(void);
3895 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00003896 //
Steve Naroff54055232008-10-27 17:20:55 +00003897 // void (^anotherBlock)(void);
3898 // anotherBlock = ^(void) {
3899 // myImportedBlock(); // import and invoke the closure
3900 // };
3901 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003902 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00003903 S += "struct __block_impl *";
3904 Constructor += ", void *" + ArgName;
3905 } else {
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00003906 std::string TypeString = "struct __Block_byref_" + FieldName;
3907 TypeString += " *";
3908 FieldName = TypeString + FieldName;
3909 ArgName = TypeString + ArgName;
Steve Naroff54055232008-10-27 17:20:55 +00003910 Constructor += ", " + ArgName;
3911 }
3912 S += FieldName + "; // by ref\n";
3913 }
3914 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00003915 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00003916 if (GlobalVarDecl)
3917 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3918 else
3919 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003920 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003921
Steve Naroff01aec112009-12-06 21:14:13 +00003922 Constructor += " Desc = desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003923
Steve Naroff54055232008-10-27 17:20:55 +00003924 // Initialize all "by copy" arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00003925 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003926 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003927 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003928 Constructor += " ";
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003929 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00003930 Constructor += Name + " = (struct __block_impl *)_";
3931 else
3932 Constructor += Name + " = _";
3933 Constructor += Name + ";\n";
3934 }
3935 // Initialize all "by ref" arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00003936 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003937 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003938 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003939 Constructor += " ";
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003940 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00003941 Constructor += Name + " = (struct __block_impl *)_";
3942 else
3943 Constructor += Name + " = _";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00003944 Constructor += Name + "->__forwarding;\n";
Steve Naroff54055232008-10-27 17:20:55 +00003945 }
3946 } else {
3947 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00003948 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00003949 if (GlobalVarDecl)
3950 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3951 else
3952 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003953 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3954 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00003955 }
3956 Constructor += " ";
3957 Constructor += "}\n";
3958 S += Constructor;
3959 S += "};\n";
3960 return S;
3961}
3962
Steve Naroff01aec112009-12-06 21:14:13 +00003963std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
3964 std::string ImplTag, int i,
3965 const char *FunName,
3966 unsigned hasCopy) {
3967 std::string S = "\nstatic struct " + DescTag;
3968
3969 S += " {\n unsigned long reserved;\n";
3970 S += " unsigned long Block_size;\n";
3971 if (hasCopy) {
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00003972 S += " void (*copy)(struct ";
3973 S += ImplTag; S += "*, struct ";
3974 S += ImplTag; S += "*);\n";
3975
3976 S += " void (*dispose)(struct ";
3977 S += ImplTag; S += "*);\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003978 }
3979 S += "} ";
3980
3981 S += DescTag + "_DATA = { 0, sizeof(struct ";
3982 S += ImplTag + ")";
3983 if (hasCopy) {
3984 S += ", __" + std::string(FunName) + "_block_copy_" + utostr(i);
3985 S += ", __" + std::string(FunName) + "_block_dispose_" + utostr(i);
3986 }
3987 S += "};\n";
3988 return S;
3989}
3990
Steve Naroff54055232008-10-27 17:20:55 +00003991void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3992 const char *FunName) {
3993 // Insert closures that were part of the function.
3994 for (unsigned i = 0; i < Blocks.size(); i++) {
3995
3996 CollectBlockDeclRefInfo(Blocks[i]);
3997
Steve Naroff01aec112009-12-06 21:14:13 +00003998 std::string ImplTag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
3999 std::string DescTag = "__" + std::string(FunName) + "_block_desc_" + utostr(i);
Mike Stump1eb44332009-09-09 15:08:12 +00004000
Steve Naroff01aec112009-12-06 21:14:13 +00004001 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff54055232008-10-27 17:20:55 +00004002
4003 InsertText(FunLocStart, CI.c_str(), CI.size());
4004
Steve Naroff01aec112009-12-06 21:14:13 +00004005 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump1eb44332009-09-09 15:08:12 +00004006
Steve Naroff54055232008-10-27 17:20:55 +00004007 InsertText(FunLocStart, CF.c_str(), CF.size());
4008
4009 if (ImportedBlockDecls.size()) {
Steve Naroff01aec112009-12-06 21:14:13 +00004010 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Steve Naroff54055232008-10-27 17:20:55 +00004011 InsertText(FunLocStart, HF.c_str(), HF.size());
4012 }
Steve Naroff01aec112009-12-06 21:14:13 +00004013 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4014 ImportedBlockDecls.size() > 0);
4015 InsertText(FunLocStart, BD.c_str(), BD.size());
Mike Stump1eb44332009-09-09 15:08:12 +00004016
Steve Naroff54055232008-10-27 17:20:55 +00004017 BlockDeclRefs.clear();
4018 BlockByRefDecls.clear();
4019 BlockByCopyDecls.clear();
4020 BlockCallExprs.clear();
4021 ImportedBlockDecls.clear();
4022 }
4023 Blocks.clear();
4024 RewrittenBlockExprs.clear();
4025}
4026
4027void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4028 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner8ec03f52008-11-24 03:54:41 +00004029 const char *FuncName = FD->getNameAsCString();
Mike Stump1eb44332009-09-09 15:08:12 +00004030
Steve Naroff54055232008-10-27 17:20:55 +00004031 SynthesizeBlockLiterals(FunLocStart, FuncName);
4032}
4033
4034void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00004035 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4036 //SourceLocation FunLocStart = MD->getLocStart();
4037 // FIXME: This hack works around a bug in Rewrite.InsertText().
4038 SourceLocation FunLocStart = MD->getLocStart().getFileLocWithOffset(-1);
Chris Lattner077bf5e2008-11-24 03:33:13 +00004039 std::string FuncName = MD->getSelector().getAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004040 // Convert colons to underscores.
4041 std::string::size_type loc = 0;
4042 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4043 FuncName.replace(loc, 1, "_");
Mike Stump1eb44332009-09-09 15:08:12 +00004044
Steve Naroff54055232008-10-27 17:20:55 +00004045 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
4046}
4047
4048void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
4049 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4050 CI != E; ++CI)
4051 if (*CI) {
4052 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4053 GetBlockDeclRefExprs(CBE->getBody());
4054 else
4055 GetBlockDeclRefExprs(*CI);
4056 }
4057 // Handle specific things.
4058 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
4059 // FIXME: Handle enums.
4060 if (!isa<FunctionDecl>(CDRE->getDecl()))
4061 BlockDeclRefs.push_back(CDRE);
4062 return;
4063}
4064
4065void RewriteObjC::GetBlockCallExprs(Stmt *S) {
4066 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4067 CI != E; ++CI)
4068 if (*CI) {
4069 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4070 GetBlockCallExprs(CBE->getBody());
4071 else
4072 GetBlockCallExprs(*CI);
4073 }
Mike Stump1eb44332009-09-09 15:08:12 +00004074
Steve Naroff54055232008-10-27 17:20:55 +00004075 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
4076 if (CE->getCallee()->getType()->isBlockPointerType()) {
4077 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
4078 }
4079 }
4080 return;
4081}
4082
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004083Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff54055232008-10-27 17:20:55 +00004084 // Navigate to relevant type information.
Steve Naroff54055232008-10-27 17:20:55 +00004085 const BlockPointerType *CPT = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004086
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004087 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004088 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004089 } else if (const BlockDeclRefExpr *CDRE =
4090 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004091 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004092 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004093 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004094 }
4095 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4096 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4097 }
4098 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4099 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4100 else if (const ConditionalOperator *CEXPR =
4101 dyn_cast<ConditionalOperator>(BlockExp)) {
4102 Expr *LHSExp = CEXPR->getLHS();
4103 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4104 Expr *RHSExp = CEXPR->getRHS();
4105 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4106 Expr *CONDExp = CEXPR->getCond();
4107 ConditionalOperator *CondExpr =
4108 new (Context) ConditionalOperator(CONDExp,
4109 SourceLocation(), cast<Expr>(LHSStmt),
4110 SourceLocation(), cast<Expr>(RHSStmt),
4111 Exp->getType());
4112 return CondExpr;
Fariborz Jahaniane24b22b2009-12-18 01:15:21 +00004113 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4114 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004115 } else {
4116 assert(1 && "RewriteBlockClass: Bad type");
4117 }
4118 assert(CPT && "RewriteBlockClass: Bad type");
John McCall183700f2009-09-21 23:43:11 +00004119 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff54055232008-10-27 17:20:55 +00004120 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor72564e72009-02-26 23:50:07 +00004121 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff54055232008-10-27 17:20:55 +00004122 // FTP will be null for closures that don't take arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004123
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004124 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
4125 SourceLocation(),
4126 &Context->Idents.get("__block_impl"));
4127 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00004128
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004129 // Generate a funky cast.
4130 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00004131
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004132 // Push the block argument type.
4133 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00004134 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004135 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004136 E = FTP->arg_type_end(); I && (I != E); ++I) {
4137 QualType t = *I;
4138 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004139 if (isTopLevelBlockPointerType(t)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004140 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004141 t = Context->getPointerType(BPT->getPointeeType());
4142 }
4143 ArgTypes.push_back(t);
4144 }
Steve Naroff54055232008-10-27 17:20:55 +00004145 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004146 // Now do the pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00004147 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004148 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00004149
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004150 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump1eb44332009-09-09 15:08:12 +00004151
4152 CastExpr *BlkCast = new (Context) CStyleCastExpr(PtrBlock,
Anders Carlssoncdef2b72009-07-31 00:48:10 +00004153 CastExpr::CK_Unknown,
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004154 const_cast<Expr*>(BlockExp),
Ted Kremenek8189cde2009-02-07 01:47:29 +00004155 PtrBlock, SourceLocation(),
4156 SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004157 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004158 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4159 BlkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004160 //PE->dump();
Mike Stump1eb44332009-09-09 15:08:12 +00004161
Douglas Gregor44b43212008-12-11 16:49:14 +00004162 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00004163 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004164 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004165 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4166 FD->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00004167
Anders Carlssoncdef2b72009-07-31 00:48:10 +00004168 CastExpr *FunkCast = new (Context) CStyleCastExpr(PtrToFuncCastType,
4169 CastExpr::CK_Unknown, ME,
Ted Kremenek8189cde2009-02-07 01:47:29 +00004170 PtrToFuncCastType,
4171 SourceLocation(),
4172 SourceLocation());
4173 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump1eb44332009-09-09 15:08:12 +00004174
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004175 llvm::SmallVector<Expr*, 8> BlkExprs;
4176 // Add the implicit argument.
4177 BlkExprs.push_back(BlkCast);
4178 // Add the user arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004179 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004180 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004181 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00004182 }
Ted Kremenek668bf912009-02-09 20:51:47 +00004183 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4184 BlkExprs.size(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00004185 Exp->getType(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004186 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00004187}
4188
4189void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004190 Stmt *BlockCall = SynthesizeBlockCall(Exp, Exp->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004191 ReplaceStmt(Exp, BlockCall);
Steve Naroff54055232008-10-27 17:20:55 +00004192}
4193
Steve Naroff621edce2009-04-29 16:37:50 +00004194// We need to return the rewritten expression to handle cases where the
4195// BlockDeclRefExpr is embedded in another expression being rewritten.
4196// For example:
4197//
4198// int main() {
4199// __block Foo *f;
4200// __block int i;
Mike Stump1eb44332009-09-09 15:08:12 +00004201//
Steve Naroff621edce2009-04-29 16:37:50 +00004202// void (^myblock)() = ^() {
4203// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4204// i = 77;
4205// };
4206//}
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004207Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanianbbf37e22009-12-23 19:26:34 +00004208 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004209 // for each DeclRefExp where BYREFVAR is name of the variable.
4210 ValueDecl *VD;
4211 bool isArrow = true;
4212 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4213 VD = BDRE->getDecl();
4214 else {
4215 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4216 isArrow = false;
4217 }
4218
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004219 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4220 &Context->Idents.get("__forwarding"),
4221 Context->VoidPtrTy, 0,
4222 /*BitWidth=*/0, /*Mutable=*/true);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004223 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4224 FD, SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004225 FD->getType());
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004226
4227 const char *Name = VD->getNameAsCString();
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004228 FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4229 &Context->Idents.get(Name),
4230 Context->VoidPtrTy, 0,
4231 /*BitWidth=*/0, /*Mutable=*/true);
4232 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004233 DeclRefExp->getType());
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004234
4235
4236
Steve Naroffdf8570d2009-02-02 17:19:26 +00004237 // Need parens to enforce precedence.
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004238 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4239 ME);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004240 ReplaceStmt(DeclRefExp, PE);
Steve Naroff621edce2009-04-29 16:37:50 +00004241 return PE;
Steve Naroff54055232008-10-27 17:20:55 +00004242}
4243
Steve Naroffb2f9e512008-11-03 23:29:32 +00004244void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4245 SourceLocation LocStart = CE->getLParenLoc();
4246 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00004247
4248 // Need to avoid trying to rewrite synthesized casts.
4249 if (LocStart.isInvalid())
4250 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00004251 // Need to avoid trying to rewrite casts contained in macros.
4252 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4253 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004254
Steve Naroff54055232008-10-27 17:20:55 +00004255 const char *startBuf = SM->getCharacterData(LocStart);
4256 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump1eb44332009-09-09 15:08:12 +00004257
Steve Naroff54055232008-10-27 17:20:55 +00004258 // advance the location to startArgList.
4259 const char *argPtr = startBuf;
Mike Stump1eb44332009-09-09 15:08:12 +00004260
Steve Naroff54055232008-10-27 17:20:55 +00004261 while (*argPtr++ && (argPtr < endBuf)) {
4262 switch (*argPtr) {
Mike Stump1eb44332009-09-09 15:08:12 +00004263 case '^':
Steve Naroff54055232008-10-27 17:20:55 +00004264 // Replace the '^' with '*'.
4265 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
4266 ReplaceText(LocStart, 1, "*", 1);
4267 break;
4268 }
4269 }
4270 return;
4271}
4272
4273void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4274 SourceLocation DeclLoc = FD->getLocation();
4275 unsigned parenCount = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004276
Steve Naroff54055232008-10-27 17:20:55 +00004277 // We have 1 or more arguments that have closure pointers.
4278 const char *startBuf = SM->getCharacterData(DeclLoc);
4279 const char *startArgList = strchr(startBuf, '(');
Mike Stump1eb44332009-09-09 15:08:12 +00004280
Steve Naroff54055232008-10-27 17:20:55 +00004281 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004282
Steve Naroff54055232008-10-27 17:20:55 +00004283 parenCount++;
4284 // advance the location to startArgList.
4285 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4286 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump1eb44332009-09-09 15:08:12 +00004287
Steve Naroff54055232008-10-27 17:20:55 +00004288 const char *argPtr = startArgList;
Mike Stump1eb44332009-09-09 15:08:12 +00004289
Steve Naroff54055232008-10-27 17:20:55 +00004290 while (*argPtr++ && parenCount) {
4291 switch (*argPtr) {
Mike Stump1eb44332009-09-09 15:08:12 +00004292 case '^':
Steve Naroff54055232008-10-27 17:20:55 +00004293 // Replace the '^' with '*'.
4294 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
4295 ReplaceText(DeclLoc, 1, "*", 1);
4296 break;
Mike Stump1eb44332009-09-09 15:08:12 +00004297 case '(':
4298 parenCount++;
Steve Naroff54055232008-10-27 17:20:55 +00004299 break;
Mike Stump1eb44332009-09-09 15:08:12 +00004300 case ')':
Steve Naroff54055232008-10-27 17:20:55 +00004301 parenCount--;
4302 break;
4303 }
4304 }
4305 return;
4306}
4307
4308bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004309 const FunctionProtoType *FTP;
Ted Kremenek6217b802009-07-29 21:53:49 +00004310 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004311 if (PT) {
John McCall183700f2009-09-21 23:43:11 +00004312 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004313 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00004314 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004315 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall183700f2009-09-21 23:43:11 +00004316 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004317 }
4318 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004319 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004320 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004321 if (isTopLevelBlockPointerType(*I))
Steve Naroff54055232008-10-27 17:20:55 +00004322 return true;
4323 }
4324 return false;
4325}
4326
Ted Kremenek8189cde2009-02-07 01:47:29 +00004327void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4328 const char *&RParen) {
Steve Naroff54055232008-10-27 17:20:55 +00004329 const char *argPtr = strchr(Name, '(');
4330 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004331
Steve Naroff54055232008-10-27 17:20:55 +00004332 LParen = argPtr; // output the start.
4333 argPtr++; // skip past the left paren.
4334 unsigned parenCount = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004335
Steve Naroff54055232008-10-27 17:20:55 +00004336 while (*argPtr && parenCount) {
4337 switch (*argPtr) {
4338 case '(': parenCount++; break;
4339 case ')': parenCount--; break;
4340 default: break;
4341 }
4342 if (parenCount) argPtr++;
4343 }
4344 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4345 RParen = argPtr; // output the end
4346}
4347
4348void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4349 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4350 RewriteBlockPointerFunctionArgs(FD);
4351 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004352 }
Steve Naroff54055232008-10-27 17:20:55 +00004353 // Handle Variables and Typedefs.
4354 SourceLocation DeclLoc = ND->getLocation();
4355 QualType DeclT;
4356 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4357 DeclT = VD->getType();
4358 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4359 DeclT = TDD->getUnderlyingType();
4360 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4361 DeclT = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00004362 else
Steve Naroff54055232008-10-27 17:20:55 +00004363 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump1eb44332009-09-09 15:08:12 +00004364
Steve Naroff54055232008-10-27 17:20:55 +00004365 const char *startBuf = SM->getCharacterData(DeclLoc);
4366 const char *endBuf = startBuf;
4367 // scan backward (from the decl location) for the end of the previous decl.
4368 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4369 startBuf--;
Mike Stump1eb44332009-09-09 15:08:12 +00004370
Steve Naroff54055232008-10-27 17:20:55 +00004371 // *startBuf != '^' if we are dealing with a pointer to function that
4372 // may take block argument types (which will be handled below).
4373 if (*startBuf == '^') {
4374 // Replace the '^' with '*', computing a negative offset.
4375 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
4376 ReplaceText(DeclLoc, 1, "*", 1);
4377 }
4378 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4379 // Replace the '^' with '*' for arguments.
4380 DeclLoc = ND->getLocation();
4381 startBuf = SM->getCharacterData(DeclLoc);
4382 const char *argListBegin, *argListEnd;
4383 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4384 while (argListBegin < argListEnd) {
4385 if (*argListBegin == '^') {
4386 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
4387 ReplaceText(CaretLoc, 1, "*", 1);
4388 }
4389 argListBegin++;
4390 }
4391 }
4392 return;
4393}
4394
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004395
4396/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4397/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4398/// struct Block_byref_id_object *src) {
4399/// _Block_object_assign (&_dest->object, _src->object,
4400/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4401/// [|BLOCK_FIELD_IS_WEAK]) // object
4402/// _Block_object_assign(&_dest->object, _src->object,
4403/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4404/// [|BLOCK_FIELD_IS_WEAK]) // block
4405/// }
4406/// And:
4407/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4408/// _Block_object_dispose(_src->object,
4409/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4410/// [|BLOCK_FIELD_IS_WEAK]) // object
4411/// _Block_object_dispose(_src->object,
4412/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4413/// [|BLOCK_FIELD_IS_WEAK]) // block
4414/// }
4415
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004416std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4417 int flag) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004418 std::string S;
Benjamin Kramer1211a712010-01-10 19:57:50 +00004419 if (CopyDestroyCache.count(flag))
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004420 return S;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004421 CopyDestroyCache.insert(flag);
4422 S = "static void __Block_byref_id_object_copy_";
4423 S += utostr(flag);
4424 S += "(void *dst, void *src) {\n";
4425
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004426 // offset into the object pointer is computed as:
4427 // void * + void* + int + int + void* + void *
4428 unsigned IntSize =
4429 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4430 unsigned VoidPtrSize =
4431 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4432
4433 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/8;
4434 S += " _Block_object_assign((char*)dst + ";
4435 S += utostr(offset);
4436 S += ", *(void * *) ((char*)src + ";
4437 S += utostr(offset);
4438 S += "), ";
4439 S += utostr(flag);
4440 S += ");\n}\n";
4441
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004442 S += "static void __Block_byref_id_object_dispose_";
4443 S += utostr(flag);
4444 S += "(void *src) {\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004445 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4446 S += utostr(offset);
4447 S += "), ";
4448 S += utostr(flag);
4449 S += ");\n}\n";
4450 return S;
4451}
4452
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004453/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4454/// the declaration into:
4455/// struct __Block_byref_ND {
4456/// void *__isa; // NULL for everything except __weak pointers
4457/// struct __Block_byref_ND *__forwarding;
4458/// int32_t __flags;
4459/// int32_t __size;
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004460/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4461/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004462/// typex ND;
4463/// };
4464///
4465/// It then replaces declaration of ND variable with:
4466/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4467/// __size=sizeof(struct __Block_byref_ND),
4468/// ND=initializer-if-any};
4469///
4470///
4471void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004472 int flag = 0;
4473 int isa = 0;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004474 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4475 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00004476 SourceLocation X = ND->getLocEnd();
4477 X = SM->getInstantiationLoc(X);
4478 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004479 std::string Name(ND->getNameAsString());
4480 std::string ByrefType = "struct __Block_byref_";
4481 ByrefType += Name;
4482 ByrefType += " {\n";
4483 ByrefType += " void *__isa;\n";
4484 ByrefType += " struct __Block_byref_" + Name + " *__forwarding;\n";
4485 ByrefType += " int __flags;\n";
4486 ByrefType += " int __size;\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004487 // Add void *__Block_byref_id_object_copy;
4488 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004489 QualType Ty = ND->getType();
4490 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4491 if (HasCopyAndDispose) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004492 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4493 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004494 }
4495
4496 Ty.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004497 ByrefType += " " + Name + ";\n";
4498 ByrefType += "};\n";
4499 // Insert this type in global scope. It is needed by helper function.
4500 assert(CurFunctionDef && "RewriteByRefVar - CurFunctionDef is null");
4501 SourceLocation FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4502 InsertText(FunLocStart, ByrefType.c_str(), ByrefType.size());
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004503 if (Ty.isObjCGCWeak()) {
4504 flag |= BLOCK_FIELD_IS_WEAK;
4505 isa = 1;
4506 }
4507
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004508 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004509 flag = BLOCK_BYREF_CALLER;
4510 QualType Ty = ND->getType();
4511 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4512 if (Ty->isBlockPointerType())
4513 flag |= BLOCK_FIELD_IS_BLOCK;
4514 else
4515 flag |= BLOCK_FIELD_IS_OBJECT;
4516 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004517 if (!HF.empty())
4518 InsertText(FunLocStart, HF.c_str(), HF.size());
4519 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004520
4521 // struct __Block_byref_ND ND =
4522 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4523 // initializer-if-any};
4524 bool hasInit = (ND->getInit() != 0);
Fariborz Jahaniane1f84f82010-01-05 18:15:57 +00004525 unsigned flags = 0;
4526 if (HasCopyAndDispose)
4527 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004528 Name = ND->getNameAsString();
4529 ByrefType = "struct __Block_byref_" + Name;
4530 if (!hasInit) {
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004531 ByrefType += " " + Name + " = {(void*)";
4532 ByrefType += utostr(isa);
4533 ByrefType += ", &" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004534 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004535 ByrefType += ", ";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004536 ByrefType += "sizeof(struct __Block_byref_" + Name + ")";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004537 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004538 ByrefType += ", __Block_byref_id_object_copy_";
4539 ByrefType += utostr(flag);
4540 ByrefType += ", __Block_byref_id_object_dispose_";
4541 ByrefType += utostr(flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004542 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004543 ByrefType += "};\n";
4544 ReplaceText(DeclLoc, endBuf-startBuf+Name.size(),
4545 ByrefType.c_str(), ByrefType.size());
4546 }
4547 else {
4548 SourceLocation startLoc = ND->getInit()->getLocStart();
Fariborz Jahanian791b10d2010-01-05 23:06:29 +00004549 startLoc = SM->getInstantiationLoc(startLoc);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004550 ByrefType += " " + Name;
4551 ReplaceText(DeclLoc, endBuf-startBuf,
4552 ByrefType.c_str(), ByrefType.size());
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004553 ByrefType = " = {(void*)";
4554 ByrefType += utostr(isa);
4555 ByrefType += ", &" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004556 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004557 ByrefType += ", ";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004558 ByrefType += "sizeof(struct __Block_byref_" + Name + "), ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004559 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004560 ByrefType += "__Block_byref_id_object_copy_";
4561 ByrefType += utostr(flag);
4562 ByrefType += ", __Block_byref_id_object_dispose_";
4563 ByrefType += utostr(flag);
4564 ByrefType += ", ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004565 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004566 InsertText(startLoc, ByrefType.c_str(), ByrefType.size());
Steve Naroffc5143c52009-12-23 17:24:33 +00004567
4568 // Complete the newly synthesized compound expression by inserting a right
4569 // curly brace before the end of the declaration.
4570 // FIXME: This approach avoids rewriting the initializer expression. It
4571 // also assumes there is only one declarator. For example, the following
4572 // isn't currently supported by this routine (in general):
4573 //
4574 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4575 //
4576 const char *startBuf = SM->getCharacterData(startLoc);
4577 const char *semiBuf = strchr(startBuf, ';');
4578 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4579 SourceLocation semiLoc =
4580 startLoc.getFileLocWithOffset(semiBuf-startBuf);
4581
4582 InsertText(semiLoc, "}", 1);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004583 }
Fariborz Jahanian1be6b462009-12-22 00:48:54 +00004584 return;
4585}
4586
Mike Stump1eb44332009-09-09 15:08:12 +00004587void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00004588 // Add initializers for any closure decl refs.
4589 GetBlockDeclRefExprs(Exp->getBody());
4590 if (BlockDeclRefs.size()) {
4591 // Unique all "by copy" declarations.
4592 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4593 if (!BlockDeclRefs[i]->isByRef())
4594 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
4595 // Unique all "by ref" declarations.
4596 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4597 if (BlockDeclRefs[i]->isByRef()) {
4598 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
4599 }
4600 // Find any imported blocks...they will need special attention.
4601 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00004602 if (BlockDeclRefs[i]->isByRef() ||
4603 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4604 BlockDeclRefs[i]->getType()->isBlockPointerType()) {
Steve Naroff00072682008-11-13 17:40:07 +00004605 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff54055232008-10-27 17:20:55 +00004606 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4607 }
4608 }
4609}
4610
Steve Narofffa15fd92008-10-28 20:29:00 +00004611FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
4612 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor72564e72009-02-26 23:50:07 +00004613 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Mike Stump1eb44332009-09-09 15:08:12 +00004614 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00004615 ID, FType, 0, FunctionDecl::Extern, false,
Douglas Gregor2224f842009-02-25 16:33:18 +00004616 false);
Steve Narofffa15fd92008-10-28 20:29:00 +00004617}
4618
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004619Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004620 Blocks.push_back(Exp);
4621
4622 CollectBlockDeclRefInfo(Exp);
4623 std::string FuncName;
Mike Stump1eb44332009-09-09 15:08:12 +00004624
Steve Narofffa15fd92008-10-28 20:29:00 +00004625 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00004626 FuncName = CurFunctionDef->getNameAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00004627 else if (CurMethodDef) {
Chris Lattner077bf5e2008-11-24 03:33:13 +00004628 FuncName = CurMethodDef->getSelector().getAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00004629 // Convert colons to underscores.
4630 std::string::size_type loc = 0;
4631 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4632 FuncName.replace(loc, 1, "_");
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004633 } else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004634 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump1eb44332009-09-09 15:08:12 +00004635
Steve Narofffa15fd92008-10-28 20:29:00 +00004636 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump1eb44332009-09-09 15:08:12 +00004637
Steve Narofffa15fd92008-10-28 20:29:00 +00004638 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4639 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00004640
Steve Narofffa15fd92008-10-28 20:29:00 +00004641 // Get a pointer to the function type so we can cast appropriately.
4642 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
4643
4644 FunctionDecl *FD;
4645 Expr *NewRep;
Mike Stump1eb44332009-09-09 15:08:12 +00004646
Steve Narofffa15fd92008-10-28 20:29:00 +00004647 // Simulate a contructor call...
4648 FD = SynthBlockInitFunctionDecl(Tag.c_str());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004649 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00004650
Steve Narofffa15fd92008-10-28 20:29:00 +00004651 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00004652
Steve Narofffdc03722008-10-29 21:23:59 +00004653 // Initialize the block function.
Steve Narofffa15fd92008-10-28 20:29:00 +00004654 FD = SynthBlockInitFunctionDecl(Func.c_str());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004655 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
4656 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00004657 CastExpr *castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy,
4658 CastExpr::CK_Unknown, Arg,
Ted Kremenek8189cde2009-02-07 01:47:29 +00004659 Context->VoidPtrTy, SourceLocation(),
4660 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00004661 InitExprs.push_back(castExpr);
4662
Steve Naroff01aec112009-12-06 21:14:13 +00004663 // Initialize the block descriptor.
4664 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump1eb44332009-09-09 15:08:12 +00004665
Steve Naroff01aec112009-12-06 21:14:13 +00004666 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
4667 &Context->Idents.get(DescData.c_str()),
4668 Context->VoidPtrTy, 0,
4669 VarDecl::Static);
4670 UnaryOperator *DescRefExpr = new (Context) UnaryOperator(
4671 new (Context) DeclRefExpr(NewVD,
4672 Context->VoidPtrTy, SourceLocation()),
4673 UnaryOperator::AddrOf,
4674 Context->getPointerType(Context->VoidPtrTy),
4675 SourceLocation());
4676 InitExprs.push_back(DescRefExpr);
4677
Steve Narofffa15fd92008-10-28 20:29:00 +00004678 // Add initializers for any closure decl refs.
4679 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00004680 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00004681 // Output all "by copy" declarations.
Mike Stump1eb44332009-09-09 15:08:12 +00004682 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00004683 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004684 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00004685 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner8ec03f52008-11-24 03:54:41 +00004686 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004687 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004688 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004689 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004690 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00004691 Exp = new (Context) CStyleCastExpr(Context->VoidPtrTy,
4692 CastExpr::CK_Unknown, Arg,
4693 Context->VoidPtrTy,
Anders Carlssoncdef2b72009-07-31 00:48:10 +00004694 SourceLocation(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00004695 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004696 } else {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004697 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004698 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004699 }
Mike Stump1eb44332009-09-09 15:08:12 +00004700 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004701 }
4702 // Output all "by ref" declarations.
Mike Stump1eb44332009-09-09 15:08:12 +00004703 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00004704 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004705 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004706 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4707 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00004708 Context->getPointerType(Exp->getType()),
Steve Narofffdc03722008-10-29 21:23:59 +00004709 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00004710 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004711 }
4712 }
Fariborz Jahanianff127882009-12-23 21:52:32 +00004713 if (ImportedBlockDecls.size()) {
4714 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4715 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff01aec112009-12-06 21:14:13 +00004716 unsigned IntSize =
4717 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanianff127882009-12-23 21:52:32 +00004718 Expr *FlagExp = new (Context) IntegerLiteral(llvm::APInt(IntSize, flag),
4719 Context->IntTy, SourceLocation());
4720 InitExprs.push_back(FlagExp);
Steve Naroff01aec112009-12-06 21:14:13 +00004721 }
Ted Kremenek668bf912009-02-09 20:51:47 +00004722 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4723 FType, SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004724 NewRep = new (Context) UnaryOperator(NewRep, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00004725 Context->getPointerType(NewRep->getType()),
Steve Narofffa15fd92008-10-28 20:29:00 +00004726 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00004727 NewRep = new (Context) CStyleCastExpr(FType, CastExpr::CK_Unknown, NewRep,
Anders Carlssoncdef2b72009-07-31 00:48:10 +00004728 FType, SourceLocation(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00004729 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004730 BlockDeclRefs.clear();
4731 BlockByRefDecls.clear();
4732 BlockByCopyDecls.clear();
4733 ImportedBlockDecls.clear();
4734 return NewRep;
4735}
4736
4737//===----------------------------------------------------------------------===//
4738// Function Body / Expression rewriting
4739//===----------------------------------------------------------------------===//
4740
Steve Naroffc77a6362008-12-04 16:24:46 +00004741// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
4742// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
4743// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
4744// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
4745// Since the rewriter isn't capable of rewriting rewritten code, it's important
4746// we get this right.
4747void RewriteObjC::CollectPropertySetters(Stmt *S) {
4748 // Perform a bottom up traversal of all children.
4749 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4750 CI != E; ++CI)
4751 if (*CI)
4752 CollectPropertySetters(*CI);
4753
4754 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
4755 if (BinOp->isAssignmentOp()) {
4756 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
4757 PropSetters[PRE] = BinOp;
4758 }
4759 }
4760}
4761
Steve Narofffa15fd92008-10-28 20:29:00 +00004762Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump1eb44332009-09-09 15:08:12 +00004763 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00004764 isa<DoStmt>(S) || isa<ForStmt>(S))
4765 Stmts.push_back(S);
4766 else if (isa<ObjCForCollectionStmt>(S)) {
4767 Stmts.push_back(S);
Chris Lattner4824fcd2010-01-09 21:45:57 +00004768 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofffa15fd92008-10-28 20:29:00 +00004769 }
Mike Stump1eb44332009-09-09 15:08:12 +00004770
Steve Narofffa15fd92008-10-28 20:29:00 +00004771 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00004772
Steve Narofffa15fd92008-10-28 20:29:00 +00004773 // Perform a bottom up rewrite of all children.
4774 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4775 CI != E; ++CI)
4776 if (*CI) {
4777 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Mike Stump1eb44332009-09-09 15:08:12 +00004778 if (newStmt)
Steve Narofffa15fd92008-10-28 20:29:00 +00004779 *CI = newStmt;
4780 }
Mike Stump1eb44332009-09-09 15:08:12 +00004781
Steve Narofffa15fd92008-10-28 20:29:00 +00004782 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4783 // Rewrite the block body in place.
4784 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Mike Stump1eb44332009-09-09 15:08:12 +00004785
Steve Narofffa15fd92008-10-28 20:29:00 +00004786 // Now we snarf the rewritten text and stash it away for later use.
Ted Kremenek6a12a142010-01-07 18:00:35 +00004787 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004788 RewrittenBlockExprs[BE] = Str;
Mike Stump1eb44332009-09-09 15:08:12 +00004789
Steve Narofffa15fd92008-10-28 20:29:00 +00004790 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
4791 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004792 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00004793 return blockTranscribed;
4794 }
4795 // Handle specific things.
4796 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4797 return RewriteAtEncode(AtEncode);
Mike Stump1eb44332009-09-09 15:08:12 +00004798
Steve Narofffa15fd92008-10-28 20:29:00 +00004799 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
4800 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
4801
Steve Naroffc77a6362008-12-04 16:24:46 +00004802 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
4803 BinaryOperator *BinOp = PropSetters[PropRefExpr];
4804 if (BinOp) {
4805 // Because the rewriter doesn't allow us to rewrite rewritten code,
4806 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroffb619d952008-12-09 12:56:34 +00004807 DisableReplaceStmt = true;
4808 // Save the source range. Even if we disable the replacement, the
4809 // rewritten node will have been inserted into the tree. If the synthesized
4810 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump1eb44332009-09-09 15:08:12 +00004811 // self.errorHandler = handler ? handler :
Steve Naroffb619d952008-12-09 12:56:34 +00004812 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
4813 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroffc77a6362008-12-04 16:24:46 +00004814 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroffb619d952008-12-09 12:56:34 +00004815 DisableReplaceStmt = false;
Steve Naroff4c3580e2008-12-04 23:50:32 +00004816 //
4817 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
4818 // we changed the RHS of BinOp, the rewriter would fail (since it needs
4819 // to see the original expression). Consider this example:
4820 //
4821 // Foo *obj1, *obj2;
4822 //
4823 // obj1.i = [obj2 rrrr];
4824 //
4825 // 'BinOp' for the previous expression looks like:
4826 //
4827 // (BinaryOperator 0x231ccf0 'int' '='
4828 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
4829 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
4830 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
4831 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
4832 //
4833 // 'newStmt' represents the rewritten message expression. For example:
4834 //
4835 // (CallExpr 0x231d300 'id':'struct objc_object *'
4836 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
4837 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
4838 // (CStyleCastExpr 0x231d220 'void *'
4839 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
4840 //
4841 // Note that 'newStmt' is passed to RewritePropertySetter so that it
4842 // can be used as the setter argument. ReplaceStmt() will still 'see'
4843 // the original RHS (since we haven't altered BinOp).
4844 //
Mike Stump1eb44332009-09-09 15:08:12 +00004845 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff4c3580e2008-12-04 23:50:32 +00004846 // node. As a result, we now leak the original AST nodes.
4847 //
Steve Naroffb619d952008-12-09 12:56:34 +00004848 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroffc77a6362008-12-04 16:24:46 +00004849 } else {
4850 return RewritePropertyGetter(PropRefExpr);
Steve Naroff15f081d2008-12-03 00:56:33 +00004851 }
4852 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004853 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4854 return RewriteAtSelector(AtSelector);
Mike Stump1eb44332009-09-09 15:08:12 +00004855
Steve Narofffa15fd92008-10-28 20:29:00 +00004856 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4857 return RewriteObjCStringLiteral(AtString);
Mike Stump1eb44332009-09-09 15:08:12 +00004858
Steve Narofffa15fd92008-10-28 20:29:00 +00004859 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00004860#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00004861 // Before we rewrite it, put the original message expression in a comment.
4862 SourceLocation startLoc = MessExpr->getLocStart();
4863 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00004864
Steve Narofffa15fd92008-10-28 20:29:00 +00004865 const char *startBuf = SM->getCharacterData(startLoc);
4866 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00004867
Steve Narofffa15fd92008-10-28 20:29:00 +00004868 std::string messString;
4869 messString += "// ";
4870 messString.append(startBuf, endBuf-startBuf+1);
4871 messString += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004872
4873 // FIXME: Missing definition of
Steve Narofffa15fd92008-10-28 20:29:00 +00004874 // InsertText(clang::SourceLocation, char const*, unsigned int).
4875 // InsertText(startLoc, messString.c_str(), messString.size());
4876 // Tried this, but it didn't work either...
4877 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00004878#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00004879 return RewriteMessageExpr(MessExpr);
4880 }
Mike Stump1eb44332009-09-09 15:08:12 +00004881
Steve Narofffa15fd92008-10-28 20:29:00 +00004882 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4883 return RewriteObjCTryStmt(StmtTry);
4884
4885 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4886 return RewriteObjCSynchronizedStmt(StmtTry);
4887
4888 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4889 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump1eb44332009-09-09 15:08:12 +00004890
Steve Narofffa15fd92008-10-28 20:29:00 +00004891 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4892 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump1eb44332009-09-09 15:08:12 +00004893
4894 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofffa15fd92008-10-28 20:29:00 +00004895 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump1eb44332009-09-09 15:08:12 +00004896 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofffa15fd92008-10-28 20:29:00 +00004897 OrigStmtRange.getEnd());
4898 if (BreakStmt *StmtBreakStmt =
4899 dyn_cast<BreakStmt>(S))
4900 return RewriteBreakStmt(StmtBreakStmt);
4901 if (ContinueStmt *StmtContinueStmt =
4902 dyn_cast<ContinueStmt>(S))
4903 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00004904
4905 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofffa15fd92008-10-28 20:29:00 +00004906 // and cast exprs.
4907 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4908 // FIXME: What we're doing here is modifying the type-specifier that
4909 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump1eb44332009-09-09 15:08:12 +00004910 // a separate type-specifier that we can rewrite.
Steve Naroff3d7e7862009-12-05 15:55:59 +00004911 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4912 // the context of an ObjCForCollectionStmt. For example:
4913 // NSArray *someArray;
4914 // for (id <FooProtocol> index in someArray) ;
4915 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4916 // and it depends on the original text locations/positions.
Benjamin Kramerb2041de2009-12-05 22:16:51 +00004917 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
Steve Naroff3d7e7862009-12-05 15:55:59 +00004918 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump1eb44332009-09-09 15:08:12 +00004919
Steve Narofffa15fd92008-10-28 20:29:00 +00004920 // Blocks rewrite rules.
4921 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4922 DI != DE; ++DI) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004923 Decl *SD = *DI;
Steve Narofffa15fd92008-10-28 20:29:00 +00004924 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004925 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004926 RewriteBlockPointerDecl(ND);
Mike Stump1eb44332009-09-09 15:08:12 +00004927 else if (ND->getType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00004928 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004929 if (VarDecl *VD = dyn_cast<VarDecl>(SD))
4930 if (VD->hasAttr<BlocksAttr>())
4931 RewriteByRefVar(VD);
Steve Narofffa15fd92008-10-28 20:29:00 +00004932 }
4933 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004934 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004935 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00004936 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00004937 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4938 }
4939 }
4940 }
Mike Stump1eb44332009-09-09 15:08:12 +00004941
Steve Narofffa15fd92008-10-28 20:29:00 +00004942 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4943 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump1eb44332009-09-09 15:08:12 +00004944
4945 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00004946 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4947 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump1eb44332009-09-09 15:08:12 +00004948 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4949 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004950 && "Statement stack mismatch");
4951 Stmts.pop_back();
4952 }
4953 // Handle blocks rewriting.
4954 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4955 if (BDRE->isByRef())
Steve Naroff621edce2009-04-29 16:37:50 +00004956 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofffa15fd92008-10-28 20:29:00 +00004957 }
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004958 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4959 ValueDecl *VD = DRE->getDecl();
4960 if (VD->hasAttr<BlocksAttr>())
4961 return RewriteBlockDeclRefExpr(DRE);
4962 }
4963
Steve Narofffa15fd92008-10-28 20:29:00 +00004964 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004965 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004966 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004967 ReplaceStmt(S, BlockCall);
4968 return BlockCall;
4969 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004970 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00004971 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004972 RewriteCastExpr(CE);
4973 }
4974#if 0
4975 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00004976 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004977 // Get the new text.
4978 std::string SStr;
4979 llvm::raw_string_ostream Buf(SStr);
Eli Friedman3a9eb442009-05-30 05:19:26 +00004980 Replacement->printPretty(Buf, *Context);
Steve Narofffa15fd92008-10-28 20:29:00 +00004981 const std::string &Str = Buf.str();
4982
4983 printf("CAST = %s\n", &Str[0]);
4984 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4985 delete S;
4986 return Replacement;
4987 }
4988#endif
4989 // Return this stmt unmodified.
4990 return S;
4991}
4992
Steve Naroff3d7e7862009-12-05 15:55:59 +00004993void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
4994 for (RecordDecl::field_iterator i = RD->field_begin(),
4995 e = RD->field_end(); i != e; ++i) {
4996 FieldDecl *FD = *i;
4997 if (isTopLevelBlockPointerType(FD->getType()))
4998 RewriteBlockPointerDecl(FD);
4999 if (FD->getType()->isObjCQualifiedIdType() ||
5000 FD->getType()->isObjCQualifiedInterfaceType())
5001 RewriteObjCQualifiedInterfaceTypes(FD);
5002 }
5003}
5004
Steve Narofffa15fd92008-10-28 20:29:00 +00005005/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5006/// main file of the input.
5007void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5008 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffcb735302008-12-17 00:20:22 +00005009 if (FD->isOverloadedOperator())
5010 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005011
Steve Narofffa15fd92008-10-28 20:29:00 +00005012 // Since function prototypes don't have ParmDecl's, we check the function
5013 // prototype. This enables us to rewrite function declarations and
5014 // definitions using the same code.
Douglas Gregor72564e72009-02-26 23:50:07 +00005015 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005016
Sebastian Redld3a413d2009-04-26 20:35:05 +00005017 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00005018 if (CompoundStmt *Body = FD->getCompoundBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005019 CurFunctionDef = FD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005020 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005021 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005022 Body =
5023 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5024 FD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005025 CurrentBody = 0;
5026 if (PropParentMap) {
5027 delete PropParentMap;
5028 PropParentMap = 0;
5029 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005030 // This synthesizes and inserts the block "impl" struct, invoke function,
5031 // and any copy/dispose helper functions.
5032 InsertBlockLiteralsWithinFunction(FD);
5033 CurFunctionDef = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00005034 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005035 return;
5036 }
5037 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00005038 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005039 CurMethodDef = MD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005040 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005041 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005042 Body =
5043 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5044 MD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005045 CurrentBody = 0;
5046 if (PropParentMap) {
5047 delete PropParentMap;
5048 PropParentMap = 0;
5049 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005050 InsertBlockLiteralsWithinMethod(MD);
5051 CurMethodDef = 0;
5052 }
5053 }
5054 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5055 ClassImplementation.push_back(CI);
5056 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5057 CategoryImplementation.push_back(CI);
5058 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
5059 RewriteForwardClassDecl(CD);
5060 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5061 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005062 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005063 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005064 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005065 CheckFunctionPointerDecl(VD->getType(), VD);
5066 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00005067 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005068 RewriteCastExpr(CE);
5069 }
5070 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00005071 } else if (VD->getType()->isRecordType()) {
5072 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5073 if (RD->isDefinition())
5074 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005075 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005076 if (VD->getInit()) {
5077 GlobalVarDecl = VD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005078 CollectPropertySetters(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005079 CurrentBody = VD->getInit();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005080 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005081 CurrentBody = 0;
5082 if (PropParentMap) {
5083 delete PropParentMap;
5084 PropParentMap = 0;
5085 }
Mike Stump1eb44332009-09-09 15:08:12 +00005086 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00005087 VD->getNameAsCString());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005088 GlobalVarDecl = 0;
5089
5090 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00005091 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005092 RewriteCastExpr(CE);
5093 }
5094 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005095 return;
5096 }
5097 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005098 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005099 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005100 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005101 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
Steve Naroff3d7e7862009-12-05 15:55:59 +00005102 else if (TD->getUnderlyingType()->isRecordType()) {
5103 RecordDecl *RD = TD->getUnderlyingType()->getAs<RecordType>()->getDecl();
5104 if (RD->isDefinition())
5105 RewriteRecordBody(RD);
5106 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005107 return;
5108 }
5109 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroff3d7e7862009-12-05 15:55:59 +00005110 if (RD->isDefinition())
5111 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005112 return;
5113 }
5114 // Nothing yet.
5115}
5116
Chris Lattnerdacbc5d2009-03-28 04:11:33 +00005117void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005118 // Get the top-level buffer that this corresponds to.
Mike Stump1eb44332009-09-09 15:08:12 +00005119
Steve Narofffa15fd92008-10-28 20:29:00 +00005120 // Rewrite tabs if we care.
5121 //RewriteTabs();
Mike Stump1eb44332009-09-09 15:08:12 +00005122
Steve Narofffa15fd92008-10-28 20:29:00 +00005123 if (Diags.hasErrorOccurred())
5124 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005125
Steve Narofffa15fd92008-10-28 20:29:00 +00005126 RewriteInclude();
Mike Stump1eb44332009-09-09 15:08:12 +00005127
Steve Naroff621edce2009-04-29 16:37:50 +00005128 // Here's a great place to add any extra declarations that may be needed.
5129 // Write out meta data for each @protocol(<expr>).
Mike Stump1eb44332009-09-09 15:08:12 +00005130 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00005131 E = ProtocolExprDecls.end(); I != E; ++I)
5132 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5133
Mike Stump1eb44332009-09-09 15:08:12 +00005134 InsertText(SM->getLocForStartOfFile(MainFileID),
Steve Narofffa15fd92008-10-28 20:29:00 +00005135 Preamble.c_str(), Preamble.size(), false);
Steve Naroff0aab7962008-11-14 14:10:01 +00005136 if (ClassImplementation.size() || CategoryImplementation.size())
5137 RewriteImplementations();
Steve Naroff621edce2009-04-29 16:37:50 +00005138
Steve Narofffa15fd92008-10-28 20:29:00 +00005139 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5140 // we are done.
Mike Stump1eb44332009-09-09 15:08:12 +00005141 if (const RewriteBuffer *RewriteBuf =
Steve Narofffa15fd92008-10-28 20:29:00 +00005142 Rewrite.getRewriteBufferFor(MainFileID)) {
5143 //printf("Changed:\n");
5144 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5145 } else {
5146 fprintf(stderr, "No changes\n");
5147 }
Steve Narofface66252008-11-13 20:07:04 +00005148
Steve Naroff621edce2009-04-29 16:37:50 +00005149 if (ClassImplementation.size() || CategoryImplementation.size() ||
5150 ProtocolExprDecls.size()) {
Steve Naroff0aab7962008-11-14 14:10:01 +00005151 // Rewrite Objective-c meta data*
5152 std::string ResultStr;
5153 SynthesizeMetaDataIntoBuffer(ResultStr);
5154 // Emit metadata.
5155 *OutFile << ResultStr;
5156 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005157 OutFile->flush();
5158}
5159