blob: 3ef3a0611931bdabece1bdd1bdd4bf39b63bb4db [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"
Chris Lattner77cd2a02007-10-11 00:43:27 +000028using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000029using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000030
Chris Lattner77cd2a02007-10-11 00:43:27 +000031namespace {
Steve Naroffb29b4272008-04-14 22:03:09 +000032 class RewriteObjC : public ASTConsumer {
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000033 enum {
34 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
35 block, ... */
36 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
37 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
38 __block variable */
39 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
40 helpers */
41 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
42 support routines */
43 BLOCK_BYREF_CURRENT_MAX = 256
44 };
45
46 enum {
47 BLOCK_NEEDS_FREE = (1 << 24),
48 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
49 BLOCK_HAS_CXX_OBJ = (1 << 26),
50 BLOCK_IS_GC = (1 << 27),
51 BLOCK_IS_GLOBAL = (1 << 28),
52 BLOCK_HAS_DESCRIPTOR = (1 << 29)
53 };
54
Chris Lattner2c64b7b2007-10-16 21:07:07 +000055 Rewriter Rewrite;
Chris Lattnere365c502007-11-30 22:25:36 +000056 Diagnostic &Diags;
Steve Naroff4f943c22008-03-10 20:43:59 +000057 const LangOptions &LangOpts;
Steve Narofff69cc5d2008-01-30 19:17:43 +000058 unsigned RewriteFailedDiag;
Steve Naroff8c565152008-12-05 17:03:39 +000059 unsigned TryFinallyContainsReturnDiag;
Mike Stump1eb44332009-09-09 15:08:12 +000060
Chris Lattner01c57482007-10-17 22:35:30 +000061 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000062 SourceManager *SM;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000063 TranslationUnitDecl *TUDecl;
Chris Lattner2b2453a2009-01-17 06:22:33 +000064 FileID MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000065 const char *MainFileStart, *MainFileEnd;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000066 SourceLocation LastIncLoc;
Mike Stump1eb44332009-09-09 15:08:12 +000067
Ted Kremeneka526c5c2008-01-07 19:49:32 +000068 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
69 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
70 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Narofffbfe8252008-05-06 18:26:51 +000071 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000072 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
73 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000074 llvm::SmallVector<Stmt *, 32> Stmts;
75 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroff621edce2009-04-29 16:37:50 +000076 // Remember all the @protocol(<expr>) expressions.
77 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Mike Stump1eb44332009-09-09 15:08:12 +000078
Steve Naroffd82a9ab2008-03-15 00:55:56 +000079 unsigned NumObjCStringLiterals;
Mike Stump1eb44332009-09-09 15:08:12 +000080
Steve Naroffebf2b562007-10-23 23:50:29 +000081 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000082 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000083 FunctionDecl *MsgSendStretFunctionDecl;
84 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000085 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000086 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000087 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000088 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000089 FunctionDecl *CFStringFunctionDecl;
Steve Naroffc0a123c2008-03-11 17:37:02 +000090 FunctionDecl *SuperContructorFunctionDecl;
Mike Stump1eb44332009-09-09 15:08:12 +000091
Steve Naroffbeaf2992007-11-03 11:27:19 +000092 // ObjC string constant support.
Steve Naroff248a7532008-04-15 22:42:06 +000093 VarDecl *ConstantStringClassReference;
Steve Naroffbeaf2992007-11-03 11:27:19 +000094 RecordDecl *NSStringRecord;
Mike Stump1eb44332009-09-09 15:08:12 +000095
Fariborz Jahanianb586cce2008-01-16 00:09:11 +000096 // ObjC foreach break/continue generation support.
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000097 int BcLabelCount;
Mike Stump1eb44332009-09-09 15:08:12 +000098
Steve Naroff874e2322007-11-15 10:28:18 +000099 // Needed for super.
Steve Naroff54055232008-10-27 17:20:55 +0000100 ObjCMethodDecl *CurMethodDef;
Steve Naroff874e2322007-11-15 10:28:18 +0000101 RecordDecl *SuperStructDecl;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000102 RecordDecl *ConstantStringDecl;
Mike Stump1eb44332009-09-09 15:08:12 +0000103
Steve Naroff621edce2009-04-29 16:37:50 +0000104 TypeDecl *ProtocolTypeDecl;
105 QualType getProtocolType();
Mike Stump1eb44332009-09-09 15:08:12 +0000106
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000107 // Needed for header files being rewritten
108 bool IsHeader;
Mike Stump1eb44332009-09-09 15:08:12 +0000109
Steve Naroffa7b402d2008-03-28 22:26:09 +0000110 std::string InFileName;
Eli Friedman66d6f042009-05-18 22:20:00 +0000111 llvm::raw_ostream* OutFile;
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000112
113 bool SilenceRewriteMacroWarning;
114
Steve Naroffba92b2e2008-03-27 22:29:16 +0000115 std::string Preamble;
Steve Naroff54055232008-10-27 17:20:55 +0000116
117 // Block expressions.
118 llvm::SmallVector<BlockExpr *, 32> Blocks;
119 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
120 llvm::DenseMap<BlockDeclRefExpr *, CallExpr *> BlockCallExprs;
Mike Stump1eb44332009-09-09 15:08:12 +0000121
Steve Naroff54055232008-10-27 17:20:55 +0000122 // Block related declarations.
123 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDecls;
124 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDecls;
125 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
126
127 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
128
Steve Naroffc77a6362008-12-04 16:24:46 +0000129 // This maps a property to it's assignment statement.
130 llvm::DenseMap<ObjCPropertyRefExpr *, BinaryOperator *> PropSetters;
Steve Naroff8599e7a2008-12-08 16:43:47 +0000131 // This maps a property to it's synthesied message expression.
132 // This allows us to rewrite chained getters (e.g. o.a.b.c).
133 llvm::DenseMap<ObjCPropertyRefExpr *, Stmt *> PropGetters;
Mike Stump1eb44332009-09-09 15:08:12 +0000134
Steve Naroff4c3580e2008-12-04 23:50:32 +0000135 // This maps an original source AST to it's rewritten form. This allows
136 // us to avoid rewriting the same node twice (which is very uncommon).
137 // This is needed to support some of the exotic property rewriting.
138 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Naroff15f081d2008-12-03 00:56:33 +0000139
Steve Naroff54055232008-10-27 17:20:55 +0000140 FunctionDecl *CurFunctionDef;
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000141 VarDecl *GlobalVarDecl;
Mike Stump1eb44332009-09-09 15:08:12 +0000142
Steve Naroffb619d952008-12-09 12:56:34 +0000143 bool DisableReplaceStmt;
Mike Stump1eb44332009-09-09 15:08:12 +0000144
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000145 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +0000146 public:
Ted Kremeneke3a61982008-05-31 20:11:04 +0000147 virtual void Initialize(ASTContext &context);
148
Chris Lattnerf04da132007-10-24 17:06:59 +0000149 // Top Level Driver code.
Chris Lattner682bf922009-03-29 16:50:03 +0000150 virtual void HandleTopLevelDecl(DeclGroupRef D) {
151 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I)
152 HandleTopLevelSingleDecl(*I);
153 }
154 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000155 void HandleDeclInMainFile(Decl *D);
Eli Friedman66d6f042009-05-18 22:20:00 +0000156 RewriteObjC(std::string inFile, llvm::raw_ostream *OS,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000157 Diagnostic &D, const LangOptions &LOpts,
158 bool silenceMacroWarn);
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000159
160 ~RewriteObjC() {}
Mike Stump1eb44332009-09-09 15:08:12 +0000161
Chris Lattnerdacbc5d2009-03-28 04:11:33 +0000162 virtual void HandleTranslationUnit(ASTContext &C);
Mike Stump1eb44332009-09-09 15:08:12 +0000163
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000164 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000165 Stmt *ReplacingStmt = ReplacedNodes[Old];
Mike Stump1eb44332009-09-09 15:08:12 +0000166
Steve Naroff4c3580e2008-12-04 23:50:32 +0000167 if (ReplacingStmt)
168 return; // We can't rewrite the same node twice.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000169
Steve Naroffb619d952008-12-09 12:56:34 +0000170 if (DisableReplaceStmt)
171 return; // Used when rewriting the assignment of a property setter.
172
Steve Naroff4c3580e2008-12-04 23:50:32 +0000173 // If replacement succeeded or warning disabled return with no warning.
174 if (!Rewrite.ReplaceStmt(Old, New)) {
175 ReplacedNodes[Old] = New;
176 return;
177 }
178 if (SilenceRewriteMacroWarning)
179 return;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000180 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
181 << Old->getSourceRange();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000182 }
Steve Naroffb619d952008-12-09 12:56:34 +0000183
184 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
185 // Measaure the old text.
186 int Size = Rewrite.getRangeSize(SrcRange);
187 if (Size == -1) {
188 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
189 << Old->getSourceRange();
190 return;
191 }
192 // Get the new text.
193 std::string SStr;
194 llvm::raw_string_ostream S(SStr);
Chris Lattnere4f21422009-06-30 01:26:17 +0000195 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
Steve Naroffb619d952008-12-09 12:56:34 +0000196 const std::string &Str = S.str();
197
198 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbard7407dc2009-08-19 19:10:30 +0000199 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroffb619d952008-12-09 12:56:34 +0000200 ReplacedNodes[Old] = New;
201 return;
202 }
203 if (SilenceRewriteMacroWarning)
204 return;
205 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
206 << Old->getSourceRange();
207 }
208
Steve Naroffba92b2e2008-03-27 22:29:16 +0000209 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
210 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000211 // If insertion succeeded or warning disabled return with no warning.
Daniel Dunbard7407dc2009-08-19 19:10:30 +0000212 if (!Rewrite.InsertText(Loc, llvm::StringRef(StrData, StrLen),
213 InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000214 SilenceRewriteMacroWarning)
215 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000216
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000217 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
218 }
Mike Stump1eb44332009-09-09 15:08:12 +0000219
Chris Lattneraadaf782008-01-31 19:51:04 +0000220 void RemoveText(SourceLocation Loc, unsigned StrLen) {
221 // If removal succeeded or warning disabled return with no warning.
222 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
223 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000224
Chris Lattneraadaf782008-01-31 19:51:04 +0000225 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
226 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000227
Chris Lattneraadaf782008-01-31 19:51:04 +0000228 void ReplaceText(SourceLocation Start, unsigned OrigLength,
229 const char *NewStr, unsigned NewLength) {
230 // If removal succeeded or warning disabled return with no warning.
Daniel Dunbard7407dc2009-08-19 19:10:30 +0000231 if (!Rewrite.ReplaceText(Start, OrigLength,
232 llvm::StringRef(NewStr, NewLength)) ||
Chris Lattneraadaf782008-01-31 19:51:04 +0000233 SilenceRewriteMacroWarning)
234 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000235
Chris Lattneraadaf782008-01-31 19:51:04 +0000236 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
237 }
Mike Stump1eb44332009-09-09 15:08:12 +0000238
Chris Lattnerf04da132007-10-24 17:06:59 +0000239 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000240 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000241 void RewriteInclude();
Chris Lattnerf04da132007-10-24 17:06:59 +0000242 void RewriteTabs();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000243 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffa0876e82008-12-02 17:36:43 +0000244 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
245 ObjCImplementationDecl *IMD,
246 ObjCCategoryImplDecl *CID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000247 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000248 void RewriteImplementationDecl(Decl *Dcl);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000249 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
250 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
251 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
252 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
253 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff6327e0d2009-01-11 01:06:09 +0000254 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff09b266e2007-10-30 23:14:51 +0000255 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000256 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroff4f95b752008-07-29 18:15:38 +0000257 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffd5255f52007-11-01 13:24:47 +0000258 bool needToScanForQualifiers(QualType T);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000259 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000260 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000261 QualType getConstantStringStructType();
Steve Naroffbaf58c32008-05-31 14:15:04 +0000262 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Mike Stump1eb44332009-09-09 15:08:12 +0000263
Chris Lattnerf04da132007-10-24 17:06:59 +0000264 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000265 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroffc77a6362008-12-04 16:24:46 +0000266 void CollectPropertySetters(Stmt *S);
Mike Stump1eb44332009-09-09 15:08:12 +0000267
Steve Naroff8599e7a2008-12-08 16:43:47 +0000268 Stmt *CurrentBody;
269 ParentMap *PropParentMap; // created lazily.
Mike Stump1eb44332009-09-09 15:08:12 +0000270
Chris Lattnere64b7772007-10-24 16:57:36 +0000271 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000272 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart);
Steve Naroffc77a6362008-12-04 16:24:46 +0000273 Stmt *RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr);
Mike Stump1eb44332009-09-09 15:08:12 +0000274 Stmt *RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroffb619d952008-12-09 12:56:34 +0000275 SourceRange SrcRange);
Steve Naroffb42f8412007-11-05 14:50:49 +0000276 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000277 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000278 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000279 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffb85e77a2009-12-05 21:43:12 +0000280 void WarnAboutReturnGotoStmts(Stmt *S);
281 void HasReturnStmts(Stmt *S, bool &hasReturns);
282 void RewriteTryReturnStmts(Stmt *S);
283 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000284 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000285 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000286 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
287 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
288 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000289 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
290 SourceLocation OrigEnd);
Mike Stump1eb44332009-09-09 15:08:12 +0000291 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
Steve Naroff934f2762007-10-24 22:48:43 +0000292 Expr **args, unsigned nargs);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000293 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000294 Stmt *RewriteBreakStmt(BreakStmt *S);
295 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000296 void SynthCountByEnumWithState(std::string &buf);
Mike Stump1eb44332009-09-09 15:08:12 +0000297
Steve Naroff09b266e2007-10-30 23:14:51 +0000298 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000299 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000300 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000301 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000302 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000303 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000304 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000305 void SynthSelGetUidFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000306 void SynthSuperContructorFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000307
Chris Lattnerf04da132007-10-24 17:06:59 +0000308 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000309 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000310 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000311
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000312 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000313 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000314
Douglas Gregor653f1b12009-04-23 01:02:12 +0000315 template<typename MethodIterator>
316 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
317 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000318 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000319 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000320 const char *ClassName,
321 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000322
Steve Naroff621edce2009-04-29 16:37:50 +0000323 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
324 const char *prefix,
325 const char *ClassName,
326 std::string &Result);
327 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
Mike Stump1eb44332009-09-09 15:08:12 +0000328 const char *prefix,
Steve Naroff621edce2009-04-29 16:37:50 +0000329 const char *ClassName,
330 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000331 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000332 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000333 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
334 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000335 std::string &Result);
Steve Narofface66252008-11-13 20:07:04 +0000336 void RewriteImplementations();
337 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000338
Steve Naroff54055232008-10-27 17:20:55 +0000339 // Block rewriting.
Mike Stump1eb44332009-09-09 15:08:12 +0000340 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff54055232008-10-27 17:20:55 +0000341 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
Mike Stump1eb44332009-09-09 15:08:12 +0000342
Steve Naroff54055232008-10-27 17:20:55 +0000343 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
344 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
Mike Stump1eb44332009-09-09 15:08:12 +0000345
346 // Block specific rewrite rules.
Steve Naroff54055232008-10-27 17:20:55 +0000347 void RewriteBlockCall(CallExpr *Exp);
348 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000349 void RewriteByRefVar(VarDecl *VD);
Steve Naroff621edce2009-04-29 16:37:50 +0000350 Stmt *RewriteBlockDeclRefExpr(BlockDeclRefExpr *VD);
Steve Naroff54055232008-10-27 17:20:55 +0000351 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Mike Stump1eb44332009-09-09 15:08:12 +0000352
353 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Steve Naroff54055232008-10-27 17:20:55 +0000354 const char *funcName, std::string Tag);
Mike Stump1eb44332009-09-09 15:08:12 +0000355 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Steve Naroff54055232008-10-27 17:20:55 +0000356 const char *funcName, std::string Tag);
Steve Naroff01aec112009-12-06 21:14:13 +0000357 std::string SynthesizeBlockImpl(BlockExpr *CE,
358 std::string Tag, std::string Desc);
359 std::string SynthesizeBlockDescriptor(std::string DescTag,
360 std::string ImplTag,
361 int i, const char *funcName,
362 unsigned hasCopy);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +0000363 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff54055232008-10-27 17:20:55 +0000364 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
365 const char *FunName);
Steve Naroff3d7e7862009-12-05 15:55:59 +0000366 void RewriteRecordBody(RecordDecl *RD);
Mike Stump1eb44332009-09-09 15:08:12 +0000367
Steve Naroff54055232008-10-27 17:20:55 +0000368 void CollectBlockDeclRefInfo(BlockExpr *Exp);
369 void GetBlockCallExprs(Stmt *S);
370 void GetBlockDeclRefExprs(Stmt *S);
Mike Stump1eb44332009-09-09 15:08:12 +0000371
Steve Naroff54055232008-10-27 17:20:55 +0000372 // We avoid calling Type::isBlockPointerType(), since it operates on the
373 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000374 bool isTopLevelBlockPointerType(QualType T) {
375 return isa<BlockPointerType>(T);
376 }
Mike Stump1eb44332009-09-09 15:08:12 +0000377
Steve Naroff54055232008-10-27 17:20:55 +0000378 // FIXME: This predicate seems like it would be useful to add to ASTContext.
379 bool isObjCType(QualType T) {
380 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
381 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000382
Steve Naroff54055232008-10-27 17:20:55 +0000383 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000384
Steve Naroff54055232008-10-27 17:20:55 +0000385 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
386 OCT == Context->getCanonicalType(Context->getObjCClassType()))
387 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000388
Ted Kremenek6217b802009-07-29 21:53:49 +0000389 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000390 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000391 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff54055232008-10-27 17:20:55 +0000392 return true;
393 }
394 return false;
395 }
396 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Ted Kremenek8189cde2009-02-07 01:47:29 +0000397 void GetExtentOfArgList(const char *Name, const char *&LParen,
398 const char *&RParen);
Steve Naroffb2f9e512008-11-03 23:29:32 +0000399 void RewriteCastExpr(CStyleCastExpr *CE);
Mike Stump1eb44332009-09-09 15:08:12 +0000400
Steve Narofffa15fd92008-10-28 20:29:00 +0000401 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000402 Stmt *SynthBlockInitExpr(BlockExpr *Exp);
Mike Stump1eb44332009-09-09 15:08:12 +0000403
Steve Naroff621edce2009-04-29 16:37:50 +0000404 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump1eb44332009-09-09 15:08:12 +0000405 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroff621edce2009-04-29 16:37:50 +0000406 if (From[i] == '"')
407 To += "\\\"";
408 else
409 To += From[i];
410 }
411 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000412 };
413}
414
Mike Stump1eb44332009-09-09 15:08:12 +0000415void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
416 NamedDecl *D) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000417 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000418 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +0000419 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000420 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff54055232008-10-27 17:20:55 +0000421 // All the args are checked/rewritten. Don't call twice!
422 RewriteBlockPointerDecl(D);
423 break;
424 }
425 }
426}
427
428void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000429 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +0000430 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor72564e72009-02-26 23:50:07 +0000431 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff54055232008-10-27 17:20:55 +0000432}
433
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000434static bool IsHeaderFile(const std::string &Filename) {
435 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump1eb44332009-09-09 15:08:12 +0000436
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000437 if (DotPos == std::string::npos) {
438 // no file extension
Mike Stump1eb44332009-09-09 15:08:12 +0000439 return false;
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000440 }
Mike Stump1eb44332009-09-09 15:08:12 +0000441
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000442 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
443 // C header: .h
444 // C++ header: .hh or .H;
445 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump1eb44332009-09-09 15:08:12 +0000446}
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000447
Eli Friedman66d6f042009-05-18 22:20:00 +0000448RewriteObjC::RewriteObjC(std::string inFile, llvm::raw_ostream* OS,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000449 Diagnostic &D, const LangOptions &LOpts,
450 bool silenceMacroWarn)
451 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
452 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Naroffa7b402d2008-03-28 22:26:09 +0000453 IsHeader = IsHeaderFile(inFile);
Mike Stump1eb44332009-09-09 15:08:12 +0000454 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000455 "rewriting sub-expression within a macro (may not be correct)");
Mike Stump1eb44332009-09-09 15:08:12 +0000456 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000457 "rewriter doesn't support user-specified control flow semantics "
458 "for @try/@finally (code may not execute properly)");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000459}
460
Eli Friedmanbce831b2009-05-18 22:29:17 +0000461ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
462 llvm::raw_ostream* OS,
Mike Stump1eb44332009-09-09 15:08:12 +0000463 Diagnostic &Diags,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000464 const LangOptions &LOpts,
465 bool SilenceRewriteMacroWarning) {
466 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere365c502007-11-30 22:25:36 +0000467}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000468
Steve Naroffb29b4272008-04-14 22:03:09 +0000469void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000470 Context = &context;
471 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000472 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000473 MsgSendFunctionDecl = 0;
474 MsgSendSuperFunctionDecl = 0;
475 MsgSendStretFunctionDecl = 0;
476 MsgSendSuperStretFunctionDecl = 0;
477 MsgSendFpretFunctionDecl = 0;
478 GetClassFunctionDecl = 0;
479 GetMetaClassFunctionDecl = 0;
480 SelGetUidFunctionDecl = 0;
481 CFStringFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000482 ConstantStringClassReference = 0;
483 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000484 CurMethodDef = 0;
485 CurFunctionDef = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000486 GlobalVarDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000487 SuperStructDecl = 0;
Steve Naroff621edce2009-04-29 16:37:50 +0000488 ProtocolTypeDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000489 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000490 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000491 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000492 NumObjCStringLiterals = 0;
Steve Naroff68272b82008-12-08 20:01:41 +0000493 PropParentMap = 0;
494 CurrentBody = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000495 DisableReplaceStmt = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000496
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000497 // Get the ID and start/end of the main file.
498 MainFileID = SM->getMainFileID();
499 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
500 MainFileStart = MainBuf->getBufferStart();
501 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000502
Chris Lattner2c78b872009-04-14 23:22:57 +0000503 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump1eb44332009-09-09 15:08:12 +0000504
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000505 // declaring objc_selector outside the parameter list removes a silly
506 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000507 if (IsHeader)
Steve Naroff62c26322009-02-03 20:39:18 +0000508 Preamble = "#pragma once\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000509 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff46a98a72008-12-23 20:11:22 +0000510 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000511 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000512 if (LangOpts.Microsoft) {
513 // Add a constructor for creating temporary objects.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000514 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
515 ": ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000516 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000517 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000518 Preamble += "};\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000519 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
520 Preamble += "typedef struct objc_object Protocol;\n";
521 Preamble += "#define _REWRITER_typedef_Protocol\n";
522 Preamble += "#endif\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000523 if (LangOpts.Microsoft) {
524 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
525 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
526 } else
527 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
528 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000529 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000530 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000531 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000532 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000533 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000534 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000535 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000536 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000537 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000538 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000539 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000540 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000541 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000542 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
543 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
544 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
545 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
546 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000547 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000548 // @synchronized hooks.
Steve Naroff4ebd7162008-12-08 17:30:33 +0000549 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
550 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
551 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000552 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
553 Preamble += "struct __objcFastEnumerationState {\n\t";
554 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000555 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000556 Preamble += "unsigned long *mutationsPtr;\n\t";
557 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000558 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000559 Preamble += "#define __FASTENUMERATIONSTATE\n";
560 Preamble += "#endif\n";
561 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
562 Preamble += "struct __NSConstantStringImpl {\n";
563 Preamble += " int *isa;\n";
564 Preamble += " int flags;\n";
565 Preamble += " char *str;\n";
566 Preamble += " long length;\n";
567 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000568 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
569 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
570 Preamble += "#else\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000571 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000572 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000573 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
574 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000575 // Blocks preamble.
576 Preamble += "#ifndef BLOCK_IMPL\n";
577 Preamble += "#define BLOCK_IMPL\n";
578 Preamble += "struct __block_impl {\n";
579 Preamble += " void *isa;\n";
580 Preamble += " int Flags;\n";
Steve Naroff01aec112009-12-06 21:14:13 +0000581 Preamble += " int Reserved;\n";
Steve Naroff54055232008-10-27 17:20:55 +0000582 Preamble += " void *FuncPtr;\n";
583 Preamble += "};\n";
Steve Naroff5bc60d02008-12-16 15:50:30 +0000584 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
Steve Naroffc9c1e9c2009-12-06 01:52:22 +0000585 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000586 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_assign(void *, const void *, const int);\n";
587 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
588 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
589 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
590 Preamble += "#else\n";
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +0000591 Preamble += "__OBJC_RW_DLLIMPORT \"C\" void _Block_object_assign(void *, const void *, const int);\n";
592 Preamble += "__OBJC_RW_DLLIMPORT \"C\" void _Block_object_dispose(const void *, const int);\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000593 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
594 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
595 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000596 Preamble += "#endif\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000597 if (LangOpts.Microsoft) {
Steve Naroff4ebd7162008-12-08 17:30:33 +0000598 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
599 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000600 Preamble += "#define __attribute__(X)\n";
601 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000602 else
603 Preamble += "#define __block\n";
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000604}
605
606
Chris Lattnerf04da132007-10-24 17:06:59 +0000607//===----------------------------------------------------------------------===//
608// Top Level Driver Code
609//===----------------------------------------------------------------------===//
610
Chris Lattner682bf922009-03-29 16:50:03 +0000611void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000612 // Two cases: either the decl could be in the main file, or it could be in a
613 // #included file. If the former, rewrite it now. If the later, check to see
614 // if we rewrote the #include/#import.
615 SourceLocation Loc = D->getLocation();
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000616 Loc = SM->getInstantiationLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000617
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000618 // If this is for a builtin, ignore it.
619 if (Loc.isInvalid()) return;
620
Steve Naroffebf2b562007-10-23 23:50:29 +0000621 // Look for built-in declarations that we need to refer during the rewrite.
622 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000623 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000624 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000625 // declared in <Foundation/NSString.h>
Chris Lattner8ec03f52008-11-24 03:54:41 +0000626 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000627 ConstantStringClassReference = FVD;
628 return;
629 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000630 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000631 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000632 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000633 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000634 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000635 RewriteProtocolDecl(PD);
Mike Stump1eb44332009-09-09 15:08:12 +0000636 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000637 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000638 RewriteForwardProtocolDecl(FP);
Douglas Gregord0434102009-01-09 00:49:46 +0000639 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
640 // Recurse into linkage specifications
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000641 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
642 DIEnd = LSD->decls_end();
Douglas Gregord0434102009-01-09 00:49:46 +0000643 DI != DIEnd; ++DI)
Chris Lattner682bf922009-03-29 16:50:03 +0000644 HandleTopLevelSingleDecl(*DI);
Steve Naroffebf2b562007-10-23 23:50:29 +0000645 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000646 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000647 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000648 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000649}
650
Chris Lattnerf04da132007-10-24 17:06:59 +0000651//===----------------------------------------------------------------------===//
652// Syntactic (non-AST) Rewriting Code
653//===----------------------------------------------------------------------===//
654
Steve Naroffb29b4272008-04-14 22:03:09 +0000655void RewriteObjC::RewriteInclude() {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000656 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000657 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
658 const char *MainBufStart = MainBuf.first;
659 const char *MainBufEnd = MainBuf.second;
660 size_t ImportLen = strlen("import");
661 size_t IncludeLen = strlen("include");
Mike Stump1eb44332009-09-09 15:08:12 +0000662
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000663 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000664 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
665 if (*BufPtr == '#') {
666 if (++BufPtr == MainBufEnd)
667 return;
668 while (*BufPtr == ' ' || *BufPtr == '\t')
669 if (++BufPtr == MainBufEnd)
670 return;
671 if (!strncmp(BufPtr, "import", ImportLen)) {
672 // replace import with include
Mike Stump1eb44332009-09-09 15:08:12 +0000673 SourceLocation ImportLoc =
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000674 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattneraadaf782008-01-31 19:51:04 +0000675 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000676 BufPtr += ImportLen;
677 }
678 }
679 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000680}
681
Steve Naroffb29b4272008-04-14 22:03:09 +0000682void RewriteObjC::RewriteTabs() {
Chris Lattnerf04da132007-10-24 17:06:59 +0000683 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
684 const char *MainBufStart = MainBuf.first;
685 const char *MainBufEnd = MainBuf.second;
Mike Stump1eb44332009-09-09 15:08:12 +0000686
Chris Lattnerf04da132007-10-24 17:06:59 +0000687 // Loop over the whole file, looking for tabs.
688 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
689 if (*BufPtr != '\t')
690 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000691
Chris Lattnerf04da132007-10-24 17:06:59 +0000692 // Okay, we found a tab. This tab will turn into at least one character,
693 // but it depends on which 'virtual column' it is in. Compute that now.
694 unsigned VCol = 0;
695 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
696 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
697 ++VCol;
Mike Stump1eb44332009-09-09 15:08:12 +0000698
Chris Lattnerf04da132007-10-24 17:06:59 +0000699 // Okay, now that we know the virtual column, we know how many spaces to
700 // insert. We assume 8-character tab-stops.
701 unsigned Spaces = 8-(VCol & 7);
Mike Stump1eb44332009-09-09 15:08:12 +0000702
Chris Lattnerf04da132007-10-24 17:06:59 +0000703 // Get the location of the tab.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000704 SourceLocation TabLoc = SM->getLocForStartOfFile(MainFileID);
705 TabLoc = TabLoc.getFileLocWithOffset(BufPtr-MainBufStart);
Mike Stump1eb44332009-09-09 15:08:12 +0000706
Chris Lattnerf04da132007-10-24 17:06:59 +0000707 // Rewrite the single tab character into a sequence of spaces.
Chris Lattneraadaf782008-01-31 19:51:04 +0000708 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerf04da132007-10-24 17:06:59 +0000709 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000710}
711
Steve Naroffeb0646c2008-12-02 15:48:25 +0000712static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
713 ObjCIvarDecl *OID) {
714 std::string S;
715 S = "((struct ";
716 S += ClassDecl->getIdentifier()->getName();
717 S += "_IMPL *)self)->";
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +0000718 S += OID->getName();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000719 return S;
720}
721
Steve Naroffa0876e82008-12-02 17:36:43 +0000722void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
723 ObjCImplementationDecl *IMD,
724 ObjCCategoryImplDecl *CID) {
Steve Naroffd40910b2008-12-01 20:33:01 +0000725 SourceLocation startLoc = PID->getLocStart();
726 InsertText(startLoc, "// ", 3);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000727 const char *startBuf = SM->getCharacterData(startLoc);
728 assert((*startBuf == '@') && "bogus @synthesize location");
729 const char *semiBuf = strchr(startBuf, ';');
730 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek8189cde2009-02-07 01:47:29 +0000731 SourceLocation onePastSemiLoc =
732 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000733
734 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
735 return; // FIXME: is this correct?
Mike Stump1eb44332009-09-09 15:08:12 +0000736
Steve Naroffeb0646c2008-12-02 15:48:25 +0000737 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000738 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000739 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000740 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000741
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000742 if (!OID)
743 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000744
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000745 std::string Getr;
746 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
747 Getr += "{ ";
748 // Synthesize an explicit cast to gain access to the ivar.
Mike Stump1eb44332009-09-09 15:08:12 +0000749 // FIXME: deal with code generation implications for various property
750 // attributes (copy, retain, nonatomic).
Steve Naroff3539cdb2008-12-02 17:54:50 +0000751 // See objc-act.c:objc_synthesize_new_getter() for details.
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000752 Getr += "return " + getIvarAccessString(ClassDecl, OID);
753 Getr += "; }";
Steve Naroffeb0646c2008-12-02 15:48:25 +0000754 InsertText(onePastSemiLoc, Getr.c_str(), Getr.size());
Steve Naroffeb0646c2008-12-02 15:48:25 +0000755 if (PD->isReadOnly())
756 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000757
Steve Naroffeb0646c2008-12-02 15:48:25 +0000758 // Generate the 'setter' function.
759 std::string Setr;
760 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000761 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000762 // Synthesize an explicit cast to initialize the ivar.
Mike Stump1eb44332009-09-09 15:08:12 +0000763 // FIXME: deal with code generation implications for various property
764 // attributes (copy, retain, nonatomic).
Steve Naroff15f081d2008-12-03 00:56:33 +0000765 // See objc-act.c:objc_synthesize_new_setter() for details.
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000766 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
Steve Narofff4312dc2008-12-11 19:29:16 +0000767 Setr += PD->getNameAsCString();
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000768 Setr += "; }";
Steve Naroffeb0646c2008-12-02 15:48:25 +0000769 InsertText(onePastSemiLoc, Setr.c_str(), Setr.size());
Steve Naroffd40910b2008-12-01 20:33:01 +0000770}
Chris Lattner8a12c272007-10-11 18:38:32 +0000771
Steve Naroffb29b4272008-04-14 22:03:09 +0000772void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000773 // Get the start location and compute the semi location.
774 SourceLocation startLoc = ClassDecl->getLocation();
775 const char *startBuf = SM->getCharacterData(startLoc);
776 const char *semiPtr = strchr(startBuf, ';');
Mike Stump1eb44332009-09-09 15:08:12 +0000777
Chris Lattnerf04da132007-10-24 17:06:59 +0000778 // Translate to typedef's that forward reference structs with the same name
779 // as the class. As a convenience, we include the original declaration
780 // as a comment.
781 std::string typedefString;
782 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000783 typedefString.append(startBuf, semiPtr-startBuf+1);
784 typedefString += "\n";
Chris Lattner67956052009-02-20 18:04:31 +0000785 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
786 I != E; ++I) {
Ted Kremenek321c22f2009-11-18 00:28:11 +0000787 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
Steve Naroff32174822007-11-09 12:50:28 +0000788 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000789 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000790 typedefString += "\n";
791 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000792 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000793 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000794 typedefString += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000795 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000796 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000797 }
Mike Stump1eb44332009-09-09 15:08:12 +0000798
Steve Naroff934f2762007-10-24 22:48:43 +0000799 // Replace the @class with typedefs corresponding to the classes.
Mike Stump1eb44332009-09-09 15:08:12 +0000800 ReplaceText(startLoc, semiPtr-startBuf+1,
Chris Lattneraadaf782008-01-31 19:51:04 +0000801 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000802}
803
Steve Naroffb29b4272008-04-14 22:03:09 +0000804void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000805 SourceLocation LocStart = Method->getLocStart();
806 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000807
Chris Lattner30fc9332009-02-04 01:06:56 +0000808 if (SM->getInstantiationLineNumber(LocEnd) >
809 SM->getInstantiationLineNumber(LocStart)) {
Steve Naroff94ac21e2008-10-21 13:37:27 +0000810 InsertText(LocStart, "#if 0\n", 6);
811 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000812 } else {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000813 InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000814 }
815}
816
Mike Stump1eb44332009-09-09 15:08:12 +0000817void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Steve Naroff6327e0d2009-01-11 01:06:09 +0000818 SourceLocation Loc = prop->getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000819
Steve Naroff6327e0d2009-01-11 01:06:09 +0000820 ReplaceText(Loc, 0, "// ", 3);
Mike Stump1eb44332009-09-09 15:08:12 +0000821
Steve Naroff6327e0d2009-01-11 01:06:09 +0000822 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000823}
824
Steve Naroffb29b4272008-04-14 22:03:09 +0000825void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000826 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000827
Steve Naroff423cb562007-10-30 13:30:57 +0000828 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000829 ReplaceText(LocStart, 0, "// ", 3);
Mike Stump1eb44332009-09-09 15:08:12 +0000830
831 for (ObjCCategoryDecl::instmeth_iterator
832 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000833 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000834 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +0000835 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000836 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000837 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000838 RewriteMethodDeclaration(*I);
839
Steve Naroff423cb562007-10-30 13:30:57 +0000840 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000841 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000842}
843
Steve Naroffb29b4272008-04-14 22:03:09 +0000844void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000845 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Mike Stump1eb44332009-09-09 15:08:12 +0000846
Steve Naroff752d6ef2007-10-30 16:42:30 +0000847 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000848
Steve Naroff752d6ef2007-10-30 16:42:30 +0000849 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000850 ReplaceText(LocStart, 0, "// ", 3);
Mike Stump1eb44332009-09-09 15:08:12 +0000851
852 for (ObjCProtocolDecl::instmeth_iterator
853 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000854 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000855 RewriteMethodDeclaration(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000856 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000857 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000858 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000859 RewriteMethodDeclaration(*I);
860
Steve Naroff752d6ef2007-10-30 16:42:30 +0000861 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000862 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattneraadaf782008-01-31 19:51:04 +0000863 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000864
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000865 // Must comment out @optional/@required
866 const char *startBuf = SM->getCharacterData(LocStart);
867 const char *endBuf = SM->getCharacterData(LocEnd);
868 for (const char *p = startBuf; p < endBuf; p++) {
869 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
870 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000871 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000872 ReplaceText(OptionalLoc, strlen("@optional"),
873 CommentedOptional.c_str(), CommentedOptional.size());
Mike Stump1eb44332009-09-09 15:08:12 +0000874
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000875 }
876 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
877 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000878 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000879 ReplaceText(OptionalLoc, strlen("@required"),
880 CommentedRequired.c_str(), CommentedRequired.size());
Mike Stump1eb44332009-09-09 15:08:12 +0000881
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000882 }
883 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000884}
885
Steve Naroffb29b4272008-04-14 22:03:09 +0000886void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000887 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000888 if (LocStart.isInvalid())
889 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000890 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000891 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000892}
893
Mike Stump1eb44332009-09-09 15:08:12 +0000894void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000895 std::string &ResultStr) {
Steve Naroffced80a82008-10-30 12:09:33 +0000896 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroff76e429d2008-07-16 14:40:40 +0000897 const FunctionType *FPRetType = 0;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000898 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000899 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000900 ResultStr += "id";
Steve Narofff4312dc2008-12-11 19:29:16 +0000901 else if (OMD->getResultType()->isFunctionPointerType() ||
902 OMD->getResultType()->isBlockPointerType()) {
Steve Naroff76e429d2008-07-16 14:40:40 +0000903 // needs special handling, since pointer-to-functions have special
904 // syntax (where a decaration models use).
905 QualType retType = OMD->getResultType();
Steve Narofff4312dc2008-12-11 19:29:16 +0000906 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +0000907 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +0000908 PointeeTy = PT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000909 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +0000910 PointeeTy = BPT->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +0000911 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Steve Narofff4312dc2008-12-11 19:29:16 +0000912 ResultStr += FPRetType->getResultType().getAsString();
913 ResultStr += "(*";
Steve Naroff76e429d2008-07-16 14:40:40 +0000914 }
915 } else
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000916 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000917 ResultStr += " ";
Mike Stump1eb44332009-09-09 15:08:12 +0000918
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000919 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000920 std::string NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +0000921
Douglas Gregorf8d49f62009-01-09 17:18:27 +0000922 if (OMD->isInstanceMethod())
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000923 NameStr += "_I_";
924 else
925 NameStr += "_C_";
Mike Stump1eb44332009-09-09 15:08:12 +0000926
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000927 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000928 NameStr += "_";
Mike Stump1eb44332009-09-09 15:08:12 +0000929
930 if (ObjCCategoryImplDecl *CID =
Steve Naroff3e0a5402009-01-08 19:41:02 +0000931 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000932 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000933 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000934 }
Mike Stump1eb44332009-09-09 15:08:12 +0000935 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +0000936 {
937 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000938 int len = selString.size();
939 for (int i = 0; i < len; i++)
940 if (selString[i] == ':')
941 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000942 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000943 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000944 // Remember this name for metadata emission
945 MethodInternalNames[OMD] = NameStr;
946 ResultStr += NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +0000947
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000948 // Rewrite arguments
949 ResultStr += "(";
Mike Stump1eb44332009-09-09 15:08:12 +0000950
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000951 // invisible arguments
Douglas Gregorf8d49f62009-01-09 17:18:27 +0000952 if (OMD->isInstanceMethod()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000953 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000954 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +0000955 if (!LangOpts.Microsoft) {
956 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
957 ResultStr += "struct ";
958 }
959 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000960 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000961 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000962 }
963 else
Steve Naroff621edce2009-04-29 16:37:50 +0000964 ResultStr += Context->getObjCClassType().getAsString();
Mike Stump1eb44332009-09-09 15:08:12 +0000965
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000966 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000967 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000968 ResultStr += " _cmd";
Mike Stump1eb44332009-09-09 15:08:12 +0000969
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000970 // Method arguments.
Chris Lattner89951a82009-02-20 18:43:26 +0000971 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
972 E = OMD->param_end(); PI != E; ++PI) {
973 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000974 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +0000975 if (PDecl->getType()->isObjCQualifiedIdType()) {
976 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000977 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +0000978 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000979 std::string Name = PDecl->getNameAsString();
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000980 if (isTopLevelBlockPointerType(PDecl->getType())) {
Steve Naroffc8ad87b2008-10-30 14:45:29 +0000981 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Ted Kremenek6217b802009-07-29 21:53:49 +0000982 const BlockPointerType *BPT = PDecl->getType()->getAs<BlockPointerType>();
Douglas Gregord249e1d1f2009-05-29 20:38:28 +0000983 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name,
984 Context->PrintingPolicy);
Steve Naroffc8ad87b2008-10-30 14:45:29 +0000985 } else
Douglas Gregord249e1d1f2009-05-29 20:38:28 +0000986 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroff543409e2008-04-18 21:13:19 +0000987 ResultStr += Name;
988 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000989 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +0000990 if (OMD->isVariadic())
991 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000992 ResultStr += ") ";
Mike Stump1eb44332009-09-09 15:08:12 +0000993
Steve Naroff76e429d2008-07-16 14:40:40 +0000994 if (FPRetType) {
995 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump1eb44332009-09-09 15:08:12 +0000996
Steve Naroff76e429d2008-07-16 14:40:40 +0000997 // Now, emit the argument types (if any).
Douglas Gregor72564e72009-02-26 23:50:07 +0000998 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff76e429d2008-07-16 14:40:40 +0000999 ResultStr += "(";
1000 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1001 if (i) ResultStr += ", ";
1002 std::string ParamStr = FT->getArgType(i).getAsString();
1003 ResultStr += ParamStr;
1004 }
1005 if (FT->isVariadic()) {
1006 if (FT->getNumArgs()) ResultStr += ", ";
1007 ResultStr += "...";
1008 }
1009 ResultStr += ")";
1010 } else {
1011 ResultStr += "()";
1012 }
1013 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001014}
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001015void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001016 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1017 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump1eb44332009-09-09 15:08:12 +00001018
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001019 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001020 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001021 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001022 InsertText(CID->getLocStart(), "// ", 3);
Mike Stump1eb44332009-09-09 15:08:12 +00001023
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001024 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001025 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1026 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001027 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001028 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001029 ObjCMethodDecl *OMD = *I;
1030 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001031 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001032 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redld3a413d2009-04-26 20:35:05 +00001033
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001034 const char *startBuf = SM->getCharacterData(LocStart);
1035 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +00001036 ReplaceText(LocStart, endBuf-startBuf,
1037 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001038 }
Mike Stump1eb44332009-09-09 15:08:12 +00001039
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001040 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001041 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1042 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001043 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001044 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001045 ObjCMethodDecl *OMD = *I;
1046 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001047 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001048 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001049
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001050 const char *startBuf = SM->getCharacterData(LocStart);
1051 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +00001052 ReplaceText(LocStart, endBuf-startBuf,
Mike Stump1eb44332009-09-09 15:08:12 +00001053 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001054 }
Steve Naroffd40910b2008-12-01 20:33:01 +00001055 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001056 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001057 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001058 I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +00001059 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001060 }
1061
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001062 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001063 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001064 else
Mike Stump1eb44332009-09-09 15:08:12 +00001065 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001066}
1067
Steve Naroffb29b4272008-04-14 22:03:09 +00001068void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001069 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001070 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001071 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001072 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001073 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001074 ResultStr += "\n";
1075 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001076 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001077 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001078 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001079 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001080 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001081 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001082 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001083 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001084 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump1eb44332009-09-09 15:08:12 +00001085
1086 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001087 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff6327e0d2009-01-11 01:06:09 +00001088 RewriteProperty(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001089 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001090 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001091 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001092 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001093 for (ObjCInterfaceDecl::classmeth_iterator
1094 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001095 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001096 RewriteMethodDeclaration(*I);
1097
Steve Naroff2feac5e2007-10-30 03:43:13 +00001098 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +00001099 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +00001100}
1101
Steve Naroffb619d952008-12-09 12:56:34 +00001102Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1103 SourceRange SrcRange) {
Steve Naroffc77a6362008-12-04 16:24:46 +00001104 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1105 // This allows us to reuse all the fun and games in SynthMessageExpr().
1106 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1107 ObjCMessageExpr *MsgExpr;
1108 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1109 llvm::SmallVector<Expr *, 1> ExprVec;
1110 ExprVec.push_back(newStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001111
Steve Naroff8599e7a2008-12-08 16:43:47 +00001112 Stmt *Receiver = PropRefExpr->getBase();
1113 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1114 if (PRE && PropGetters[PRE]) {
1115 // This allows us to handle chain/nested property getters.
1116 Receiver = PropGetters[PRE];
1117 }
Mike Stump1eb44332009-09-09 15:08:12 +00001118 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
1119 PDecl->getSetterName(), PDecl->getType(),
1120 PDecl->getSetterMethodDecl(),
1121 SourceLocation(), SourceLocation(),
Steve Naroffc77a6362008-12-04 16:24:46 +00001122 &ExprVec[0], 1);
1123 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001124
Steve Naroffc77a6362008-12-04 16:24:46 +00001125 // Now do the actual rewrite.
Steve Naroffb619d952008-12-09 12:56:34 +00001126 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffe58ee0c2008-12-10 14:53:27 +00001127 //delete BinOp;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001128 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1129 // to things that stay around.
1130 Context->Deallocate(MsgExpr);
Steve Naroffc77a6362008-12-04 16:24:46 +00001131 return ReplacingStmt;
Steve Naroff15f081d2008-12-03 00:56:33 +00001132}
1133
Steve Naroffc77a6362008-12-04 16:24:46 +00001134Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Naroff15f081d2008-12-03 00:56:33 +00001135 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1136 // This allows us to reuse all the fun and games in SynthMessageExpr().
1137 ObjCMessageExpr *MsgExpr;
1138 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
Mike Stump1eb44332009-09-09 15:08:12 +00001139
Steve Naroff8599e7a2008-12-08 16:43:47 +00001140 Stmt *Receiver = PropRefExpr->getBase();
Mike Stump1eb44332009-09-09 15:08:12 +00001141
Steve Naroff8599e7a2008-12-08 16:43:47 +00001142 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1143 if (PRE && PropGetters[PRE]) {
1144 // This allows us to handle chain/nested property getters.
1145 Receiver = PropGetters[PRE];
1146 }
Mike Stump1eb44332009-09-09 15:08:12 +00001147 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
1148 PDecl->getGetterName(), PDecl->getType(),
1149 PDecl->getGetterMethodDecl(),
1150 SourceLocation(), SourceLocation(),
Steve Naroff15f081d2008-12-03 00:56:33 +00001151 0, 0);
1152
Steve Naroff4c3580e2008-12-04 23:50:32 +00001153 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001154
1155 if (!PropParentMap)
1156 PropParentMap = new ParentMap(CurrentBody);
1157
1158 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1159 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1160 // We stash away the ReplacingStmt since actually doing the
1161 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1162 PropGetters[PropRefExpr] = ReplacingStmt;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001163 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1164 // to things that stay around.
1165 Context->Deallocate(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001166 return PropRefExpr; // return the original...
1167 } else {
1168 ReplaceStmt(PropRefExpr, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001169 // delete PropRefExpr; elsewhere...
Ted Kremenek8189cde2009-02-07 01:47:29 +00001170 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1171 // to things that stay around.
1172 Context->Deallocate(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001173 return ReplacingStmt;
1174 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001175}
1176
Mike Stump1eb44332009-09-09 15:08:12 +00001177Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001178 SourceLocation OrigStart) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001179 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff54055232008-10-27 17:20:55 +00001180 if (CurMethodDef) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001181 if (const PointerType *pType = IV->getBase()->getType()->getAs<PointerType>()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001182 ObjCInterfaceType *iFaceDecl =
1183 dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Narofff0757612008-05-08 17:52:16 +00001184 // lookup which class implements the instance variable.
1185 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001186 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001187 clsDeclared);
Steve Narofff0757612008-05-08 17:52:16 +00001188 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001189
Steve Narofff0757612008-05-08 17:52:16 +00001190 // Synthesize an explicit cast to gain access to the ivar.
1191 std::string RecName = clsDeclared->getIdentifier()->getName();
1192 RecName += "_IMPL";
1193 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001194 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001195 SourceLocation(), II);
Steve Narofff0757612008-05-08 17:52:16 +00001196 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1197 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Mike Stump1eb44332009-09-09 15:08:12 +00001198 CastExpr *castExpr = new (Context) CStyleCastExpr(castT,
Anders Carlssoncdef2b72009-07-31 00:48:10 +00001199 CastExpr::CK_Unknown,
1200 IV->getBase(),
1201 castT,SourceLocation(),
1202 SourceLocation());
Steve Narofff0757612008-05-08 17:52:16 +00001203 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001204 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1205 IV->getBase()->getLocEnd(),
1206 castExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001207 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +00001208 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001209 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1210 IV->getLocation(),
1211 D->getType());
Steve Narofff0757612008-05-08 17:52:16 +00001212 ReplaceStmt(IV, ME);
Steve Naroff4c3580e2008-12-04 23:50:32 +00001213 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Narofff0757612008-05-08 17:52:16 +00001214 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001215 }
Mike Stump1eb44332009-09-09 15:08:12 +00001216
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001217 ReplaceStmt(IV->getBase(), PE);
1218 // Cannot delete IV->getBase(), since PE points to it.
1219 // Replace the old base with the cast. This is important when doing
1220 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001221 IV->setBase(PE);
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001222 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001223 }
Steve Naroff84472a82008-04-18 21:55:08 +00001224 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001225 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump1eb44332009-09-09 15:08:12 +00001226
Steve Naroff9f525972008-05-06 23:20:07 +00001227 // Explicit ivar refs need to have a cast inserted.
1228 // FIXME: consider sharing some of this code with the code above.
Ted Kremenek6217b802009-07-29 21:53:49 +00001229 if (const PointerType *pType = IV->getBase()->getType()->getAs<PointerType>()) {
Steve Narofff0757612008-05-08 17:52:16 +00001230 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001231 // lookup which class implements the instance variable.
1232 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001233 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001234 clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001235 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001236
Steve Naroff9f525972008-05-06 23:20:07 +00001237 // Synthesize an explicit cast to gain access to the ivar.
1238 std::string RecName = clsDeclared->getIdentifier()->getName();
1239 RecName += "_IMPL";
1240 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001241 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001242 SourceLocation(), II);
Steve Naroff9f525972008-05-06 23:20:07 +00001243 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1244 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Mike Stump1eb44332009-09-09 15:08:12 +00001245 CastExpr *castExpr = new (Context) CStyleCastExpr(castT,
Anders Carlssoncdef2b72009-07-31 00:48:10 +00001246 CastExpr::CK_Unknown,
1247 IV->getBase(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00001248 castT, SourceLocation(),
1249 SourceLocation());
Steve Naroff9f525972008-05-06 23:20:07 +00001250 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001251 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner8d366162008-05-28 16:38:23 +00001252 IV->getBase()->getLocEnd(), castExpr);
Steve Naroff9f525972008-05-06 23:20:07 +00001253 ReplaceStmt(IV->getBase(), PE);
1254 // Cannot delete IV->getBase(), since PE points to it.
1255 // Replace the old base with the cast. This is important when doing
1256 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001257 IV->setBase(PE);
Steve Naroff9f525972008-05-06 23:20:07 +00001258 return IV;
1259 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001260 }
Steve Naroff84472a82008-04-18 21:55:08 +00001261 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +00001262}
1263
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001264/// SynthCountByEnumWithState - To print:
1265/// ((unsigned int (*)
1266/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001267/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001268/// sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001269/// "countByEnumeratingWithState:objects:count:"),
1270/// &enumState,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001271/// (id *)items, (unsigned int)16)
1272///
Steve Naroffb29b4272008-04-14 22:03:09 +00001273void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001274 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1275 "id *, unsigned int))(void *)objc_msgSend)";
1276 buf += "\n\t\t";
1277 buf += "((id)l_collection,\n\t\t";
1278 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1279 buf += "\n\t\t";
1280 buf += "&enumState, "
1281 "(id *)items, (unsigned int)16)";
1282}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001283
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001284/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1285/// statement to exit to its outer synthesized loop.
1286///
Steve Naroffb29b4272008-04-14 22:03:09 +00001287Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001288 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1289 return S;
1290 // replace break with goto __break_label
1291 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001292
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001293 SourceLocation startLoc = S->getLocStart();
1294 buf = "goto __break_label_";
1295 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001296 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001297
1298 return 0;
1299}
1300
1301/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1302/// statement to continue with its inner synthesized loop.
1303///
Steve Naroffb29b4272008-04-14 22:03:09 +00001304Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001305 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1306 return S;
1307 // replace continue with goto __continue_label
1308 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001309
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001310 SourceLocation startLoc = S->getLocStart();
1311 buf = "goto __continue_label_";
1312 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001313 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001314
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001315 return 0;
1316}
1317
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001318/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001319/// It rewrites:
1320/// for ( type elem in collection) { stmts; }
Mike Stump1eb44332009-09-09 15:08:12 +00001321
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001322/// Into:
1323/// {
Mike Stump1eb44332009-09-09 15:08:12 +00001324/// type elem;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001325/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001326/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001327/// id l_collection = (id)collection;
Mike Stump1eb44332009-09-09 15:08:12 +00001328/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001329/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001330/// if (limit) {
1331/// unsigned long startMutations = *enumState.mutationsPtr;
1332/// do {
1333/// unsigned long counter = 0;
1334/// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001335/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001336/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001337/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001338/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001339/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001340/// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001341/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001342/// objects:items count:16]);
1343/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001344/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001345/// }
1346/// else
1347/// elem = nil;
1348/// }
1349///
Steve Naroffb29b4272008-04-14 22:03:09 +00001350Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001351 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001352 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001353 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001354 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump1eb44332009-09-09 15:08:12 +00001355 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001356 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001357
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001358 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001359 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001360 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001361 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001362 std::string buf;
1363 buf = "\n{\n\t";
1364 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1365 // type elem;
Chris Lattner7e24e822009-03-28 06:33:19 +00001366 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001367 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001368 if (ElementType->isObjCQualifiedIdType() ||
1369 ElementType->isObjCQualifiedInterfaceType())
1370 // Simply use 'id' for all qualified types.
1371 elementTypeAsString = "id";
1372 else
1373 elementTypeAsString = ElementType.getAsString();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001374 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001375 buf += " ";
Chris Lattner8ec03f52008-11-24 03:54:41 +00001376 elementName = D->getNameAsCString();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001377 buf += elementName;
1378 buf += ";\n\t";
1379 }
Chris Lattner06767512008-04-08 05:52:18 +00001380 else {
1381 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner8ec03f52008-11-24 03:54:41 +00001382 elementName = DR->getDecl()->getNameAsCString();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001383 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1384 if (VD->getType()->isObjCQualifiedIdType() ||
1385 VD->getType()->isObjCQualifiedInterfaceType())
1386 // Simply use 'id' for all qualified types.
1387 elementTypeAsString = "id";
1388 else
1389 elementTypeAsString = VD->getType().getAsString();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001390 }
Mike Stump1eb44332009-09-09 15:08:12 +00001391
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001392 // struct __objcFastEnumerationState enumState = { 0 };
1393 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1394 // id items[16];
1395 buf += "id items[16];\n\t";
1396 // id l_collection = (id)
1397 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001398 // Find start location of 'collection' the hard way!
1399 const char *startCollectionBuf = startBuf;
1400 startCollectionBuf += 3; // skip 'for'
1401 startCollectionBuf = strchr(startCollectionBuf, '(');
1402 startCollectionBuf++; // skip '('
1403 // find 'in' and skip it.
1404 while (*startCollectionBuf != ' ' ||
1405 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1406 (*(startCollectionBuf+3) != ' ' &&
1407 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1408 startCollectionBuf++;
1409 startCollectionBuf += 3;
Mike Stump1eb44332009-09-09 15:08:12 +00001410
1411 // Replace: "for (type element in" with string constructed thus far.
Chris Lattneraadaf782008-01-31 19:51:04 +00001412 ReplaceText(startLoc, startCollectionBuf - startBuf,
1413 buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001414 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001415 SourceLocation rightParenLoc = S->getRParenLoc();
1416 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1417 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001418 buf = ";\n\t";
Mike Stump1eb44332009-09-09 15:08:12 +00001419
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001420 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1421 // objects:items count:16];
1422 // which is synthesized into:
Mike Stump1eb44332009-09-09 15:08:12 +00001423 // unsigned int limit =
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001424 // ((unsigned int (*)
1425 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001426 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001427 // sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001428 // "countByEnumeratingWithState:objects:count:"),
1429 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001430 // (id *)items, (unsigned int)16);
1431 buf += "unsigned long limit =\n\t\t";
1432 SynthCountByEnumWithState(buf);
1433 buf += ";\n\t";
1434 /// if (limit) {
1435 /// unsigned long startMutations = *enumState.mutationsPtr;
1436 /// do {
1437 /// unsigned long counter = 0;
1438 /// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001439 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001440 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001441 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001442 buf += "if (limit) {\n\t";
1443 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1444 buf += "do {\n\t\t";
1445 buf += "unsigned long counter = 0;\n\t\t";
1446 buf += "do {\n\t\t\t";
1447 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1448 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1449 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001450 buf += " = (";
1451 buf += elementTypeAsString;
1452 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001453 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattneraadaf782008-01-31 19:51:04 +00001454 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001455
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001456 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001457 /// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001458 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001459 /// objects:items count:16]);
1460 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001461 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001462 /// }
1463 /// else
1464 /// elem = nil;
1465 /// }
Mike Stump1eb44332009-09-09 15:08:12 +00001466 ///
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001467 buf = ";\n\t";
1468 buf += "__continue_label_";
1469 buf += utostr(ObjCBcLabelNo.back());
1470 buf += ": ;";
1471 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001472 buf += "} while (counter < limit);\n\t";
1473 buf += "} while (limit = ";
1474 SynthCountByEnumWithState(buf);
1475 buf += ");\n\t";
1476 buf += elementName;
Steve Naroff5605fdf2008-12-17 14:24:39 +00001477 buf += " = ((id)0);\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001478 buf += "__break_label_";
1479 buf += utostr(ObjCBcLabelNo.back());
1480 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001481 buf += "}\n\t";
1482 buf += "else\n\t\t";
1483 buf += elementName;
Steve Naroff5605fdf2008-12-17 14:24:39 +00001484 buf += " = ((id)0);\n";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001485 buf += "}\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001486
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001487 // Insert all these *after* the statement body.
Sebastian Redld3a413d2009-04-26 20:35:05 +00001488 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Naroff600e4e82008-07-21 18:26:02 +00001489 if (isa<CompoundStmt>(S->getBody())) {
1490 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1491 InsertText(endBodyLoc, buf.c_str(), buf.size());
1492 } else {
1493 /* Need to treat single statements specially. For example:
1494 *
1495 * for (A *a in b) if (stuff()) break;
1496 * for (A *a in b) xxxyy;
1497 *
1498 * The following code simply scans ahead to the semi to find the actual end.
1499 */
1500 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1501 const char *semiBuf = strchr(stmtBuf, ';');
1502 assert(semiBuf && "Can't find ';'");
1503 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1504 InsertText(endBodyLoc, buf.c_str(), buf.size());
1505 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001506 Stmts.pop_back();
1507 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001508 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001509}
1510
Mike Stump1eb44332009-09-09 15:08:12 +00001511/// RewriteObjCSynchronizedStmt -
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001512/// This routine rewrites @synchronized(expr) stmt;
1513/// into:
1514/// objc_sync_enter(expr);
1515/// @try stmt @finally { objc_sync_exit(expr); }
1516///
Steve Naroffb29b4272008-04-14 22:03:09 +00001517Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001518 // Get the start location and compute the semi location.
1519 SourceLocation startLoc = S->getLocStart();
1520 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001521
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001522 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump1eb44332009-09-09 15:08:12 +00001523
1524 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001525 buf = "objc_sync_enter((id)";
1526 const char *lparenBuf = startBuf;
1527 while (*lparenBuf != '(') lparenBuf++;
1528 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001529 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1530 // the sync expression is typically a message expression that's already
Steve Naroffc7089f12008-08-19 13:04:19 +00001531 // been rewritten! (which implies the SourceLocation's are invalid).
1532 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001533 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001534 while (*endBuf != ')') endBuf--;
1535 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001536 buf = ");\n";
1537 // declare a new scope with two variables, _stack and _rethrow.
1538 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1539 buf += "int buf[18/*32-bit i386*/];\n";
1540 buf += "char *pointers[4];} _stack;\n";
1541 buf += "id volatile _rethrow = 0;\n";
1542 buf += "objc_exception_try_enter(&_stack);\n";
1543 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00001544 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001545 startLoc = S->getSynchBody()->getLocEnd();
1546 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001547
Steve Naroffc7089f12008-08-19 13:04:19 +00001548 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001549 SourceLocation lastCurlyLoc = startLoc;
1550 buf = "}\nelse {\n";
1551 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroff621edce2009-04-29 16:37:50 +00001552 buf += "}\n";
1553 buf += "{ /* implicit finally clause */\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001554 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb85e77a2009-12-05 21:43:12 +00001555
1556 std::string syncBuf;
1557 syncBuf += " objc_sync_exit(";
Mike Stump1eb44332009-09-09 15:08:12 +00001558 Expr *syncExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssoncdef2b72009-07-31 00:48:10 +00001559 CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00001560 S->getSynchExpr(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00001561 Context->getObjCIdType(),
1562 SourceLocation(),
1563 SourceLocation());
Ted Kremeneka95d3752008-09-13 05:16:45 +00001564 std::string syncExprBufS;
1565 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00001566 syncExpr->printPretty(syncExprBuf, *Context, 0,
1567 PrintingPolicy(LangOpts));
Steve Naroffb85e77a2009-12-05 21:43:12 +00001568 syncBuf += syncExprBuf.str();
1569 syncBuf += ");";
1570
1571 buf += syncBuf;
1572 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001573 buf += "}\n";
1574 buf += "}";
Mike Stump1eb44332009-09-09 15:08:12 +00001575
Chris Lattneraadaf782008-01-31 19:51:04 +00001576 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffb85e77a2009-12-05 21:43:12 +00001577
1578 bool hasReturns = false;
1579 HasReturnStmts(S->getSynchBody(), hasReturns);
1580 if (hasReturns)
1581 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1582
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001583 return 0;
1584}
1585
Steve Naroffb85e77a2009-12-05 21:43:12 +00001586void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1587{
Steve Naroff8c565152008-12-05 17:03:39 +00001588 // Perform a bottom up traversal of all children.
1589 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1590 CI != E; ++CI)
1591 if (*CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001592 WarnAboutReturnGotoStmts(*CI);
Steve Naroff8c565152008-12-05 17:03:39 +00001593
Steve Naroffb85e77a2009-12-05 21:43:12 +00001594 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001595 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff8c565152008-12-05 17:03:39 +00001596 TryFinallyContainsReturnDiag);
1597 }
1598 return;
1599}
1600
Steve Naroffb85e77a2009-12-05 21:43:12 +00001601void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1602{
1603 // Perform a bottom up traversal of all children.
1604 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1605 CI != E; ++CI)
1606 if (*CI)
1607 HasReturnStmts(*CI, hasReturns);
1608
1609 if (isa<ReturnStmt>(S))
1610 hasReturns = true;
1611 return;
1612}
1613
1614void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1615 // Perform a bottom up traversal of all children.
1616 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1617 CI != E; ++CI)
1618 if (*CI) {
1619 RewriteTryReturnStmts(*CI);
1620 }
1621 if (isa<ReturnStmt>(S)) {
1622 SourceLocation startLoc = S->getLocStart();
1623 const char *startBuf = SM->getCharacterData(startLoc);
1624
1625 const char *semiBuf = strchr(startBuf, ';');
1626 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1627 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1628
1629 std::string buf;
1630 buf = "{ objc_exception_try_exit(&_stack); return";
1631
1632 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
1633 InsertText(onePastSemiLoc, "}", 1);
1634 }
1635 return;
1636}
1637
1638void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1639 // Perform a bottom up traversal of all children.
1640 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1641 CI != E; ++CI)
1642 if (*CI) {
1643 RewriteSyncReturnStmts(*CI, syncExitBuf);
1644 }
1645 if (isa<ReturnStmt>(S)) {
1646 SourceLocation startLoc = S->getLocStart();
1647 const char *startBuf = SM->getCharacterData(startLoc);
1648
1649 const char *semiBuf = strchr(startBuf, ';');
1650 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1651 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1652
1653 std::string buf;
1654 buf = "{ objc_exception_try_exit(&_stack);";
1655 buf += syncExitBuf;
1656 buf += " return";
1657
1658 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
1659 InsertText(onePastSemiLoc, "}", 1);
1660 }
1661 return;
1662}
1663
Steve Naroffb29b4272008-04-14 22:03:09 +00001664Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001665 // Get the start location and compute the semi location.
1666 SourceLocation startLoc = S->getLocStart();
1667 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001668
Steve Naroff75730982007-11-07 04:08:17 +00001669 assert((*startBuf == '@') && "bogus @try location");
1670
1671 std::string buf;
1672 // declare a new scope with two variables, _stack and _rethrow.
1673 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1674 buf += "int buf[18/*32-bit i386*/];\n";
1675 buf += "char *pointers[4];} _stack;\n";
1676 buf += "id volatile _rethrow = 0;\n";
1677 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001678 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001679
Chris Lattneraadaf782008-01-31 19:51:04 +00001680 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001681
Steve Naroff75730982007-11-07 04:08:17 +00001682 startLoc = S->getTryBody()->getLocEnd();
1683 startBuf = SM->getCharacterData(startLoc);
1684
1685 assert((*startBuf == '}') && "bogus @try block");
Mike Stump1eb44332009-09-09 15:08:12 +00001686
Steve Naroff75730982007-11-07 04:08:17 +00001687 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffc9ba1722008-07-16 15:31:30 +00001688 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1689 if (catchList) {
1690 startLoc = startLoc.getFileLocWithOffset(1);
1691 buf = " /* @catch begin */ else {\n";
1692 buf += " id _caught = objc_exception_extract(&_stack);\n";
1693 buf += " objc_exception_try_enter (&_stack);\n";
1694 buf += " if (_setjmp(_stack.buf))\n";
1695 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1696 buf += " else { /* @catch continue */";
Mike Stump1eb44332009-09-09 15:08:12 +00001697
Steve Naroffc9ba1722008-07-16 15:31:30 +00001698 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001699 } else { /* no catch list */
1700 buf = "}\nelse {\n";
1701 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1702 buf += "}";
1703 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffc9ba1722008-07-16 15:31:30 +00001704 }
Steve Naroff75730982007-11-07 04:08:17 +00001705 bool sawIdTypedCatch = false;
1706 Stmt *lastCatchBody = 0;
Steve Naroff75730982007-11-07 04:08:17 +00001707 while (catchList) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00001708 ParmVarDecl *catchDecl = catchList->getCatchParamDecl();
Steve Naroff75730982007-11-07 04:08:17 +00001709
Mike Stump1eb44332009-09-09 15:08:12 +00001710 if (catchList == S->getCatchStmts())
Steve Naroff75730982007-11-07 04:08:17 +00001711 buf = "if ("; // we are generating code for the first catch clause
1712 else
1713 buf = "else if (";
1714 startLoc = catchList->getLocStart();
1715 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001716
Steve Naroff75730982007-11-07 04:08:17 +00001717 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump1eb44332009-09-09 15:08:12 +00001718
Steve Naroff75730982007-11-07 04:08:17 +00001719 const char *lParenLoc = strchr(startBuf, '(');
1720
Steve Naroffbe4b3332008-02-01 22:08:12 +00001721 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001722 // Now rewrite the body...
1723 lastCatchBody = catchList->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001724 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1725 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner06767512008-04-08 05:52:18 +00001726 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1727 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001728 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001729
Steve Naroffe12e6922008-02-01 20:02:07 +00001730 buf += "1) { id _tmp = _caught;";
Daniel Dunbard7407dc2009-08-19 19:10:30 +00001731 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff7ba138a2009-03-03 19:52:17 +00001732 } else if (catchDecl) {
1733 QualType t = catchDecl->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001734 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001735 buf += "1) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001736 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001737 sawIdTypedCatch = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001738 } else if (const PointerType *pType = t->getAs<PointerType>()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001739 ObjCInterfaceType *cls; // Should be a pointer to a class.
Mike Stump1eb44332009-09-09 15:08:12 +00001740
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001741 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001742 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001743 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001744 buf += cls->getDecl()->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001745 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001746 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001747 }
1748 }
1749 // Now rewrite the body...
1750 lastCatchBody = catchList->getCatchBody();
1751 SourceLocation rParenLoc = catchList->getRParenLoc();
1752 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1753 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1754 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1755 assert((*rParenBuf == ')') && "bogus @catch paren location");
1756 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001757
Steve Naroff75730982007-11-07 04:08:17 +00001758 buf = " = _caught;";
Mike Stump1eb44332009-09-09 15:08:12 +00001759 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroff75730982007-11-07 04:08:17 +00001760 // declares the @catch parameter).
Chris Lattneraadaf782008-01-31 19:51:04 +00001761 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff7ba138a2009-03-03 19:52:17 +00001762 } else {
Steve Naroff75730982007-11-07 04:08:17 +00001763 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001764 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001765 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001766 catchList = catchList->getNextCatchStmt();
1767 }
1768 // Complete the catch list...
1769 if (lastCatchBody) {
1770 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001771 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1772 "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001773
Steve Naroff378f47a2008-09-11 15:29:03 +00001774 // Insert the last (implicit) else clause *before* the right curly brace.
1775 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1776 buf = "} /* last catch end */\n";
1777 buf += "else {\n";
1778 buf += " _rethrow = _caught;\n";
1779 buf += " objc_exception_try_exit(&_stack);\n";
1780 buf += "} } /* @catch end */\n";
1781 if (!S->getFinallyStmt())
1782 buf += "}\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001783 InsertText(bodyLoc, buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001784
Steve Naroff75730982007-11-07 04:08:17 +00001785 // Set lastCurlyLoc
1786 lastCurlyLoc = lastCatchBody->getLocEnd();
1787 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001788 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001789 startLoc = finalStmt->getLocStart();
1790 startBuf = SM->getCharacterData(startLoc);
1791 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump1eb44332009-09-09 15:08:12 +00001792
Steve Naroff75730982007-11-07 04:08:17 +00001793 buf = "/* @finally */";
Chris Lattneraadaf782008-01-31 19:51:04 +00001794 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001795
Steve Naroff75730982007-11-07 04:08:17 +00001796 Stmt *body = finalStmt->getFinallyBody();
1797 SourceLocation startLoc = body->getLocStart();
1798 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001799 assert(*SM->getCharacterData(startLoc) == '{' &&
1800 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001801 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner06767512008-04-08 05:52:18 +00001802 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001803
Steve Naroff75730982007-11-07 04:08:17 +00001804 startLoc = startLoc.getFileLocWithOffset(1);
1805 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001806 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001807 endLoc = endLoc.getFileLocWithOffset(-1);
1808 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001809 InsertText(endLoc, buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001810
Steve Naroff75730982007-11-07 04:08:17 +00001811 // Set lastCurlyLoc
1812 lastCurlyLoc = body->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00001813
Steve Naroff8c565152008-12-05 17:03:39 +00001814 // Now check for any return/continue/go statements within the @try.
Steve Naroffb85e77a2009-12-05 21:43:12 +00001815 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00001816 } else { /* no finally clause - make sure we synthesize an implicit one */
1817 buf = "{ /* implicit finally clause */\n";
1818 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1819 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1820 buf += "}";
1821 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffb85e77a2009-12-05 21:43:12 +00001822
1823 // Now check for any return/continue/go statements within the @try.
1824 // The implicit finally clause won't called if the @try contains any
1825 // jump statements.
1826 bool hasReturns = false;
1827 HasReturnStmts(S->getTryBody(), hasReturns);
1828 if (hasReturns)
1829 RewriteTryReturnStmts(S->getTryBody());
Steve Naroff75730982007-11-07 04:08:17 +00001830 }
1831 // Now emit the final closing curly brace...
1832 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1833 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001834 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001835 return 0;
1836}
1837
Steve Naroffb29b4272008-04-14 22:03:09 +00001838Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001839 return 0;
1840}
1841
Steve Naroffb29b4272008-04-14 22:03:09 +00001842Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001843 return 0;
1844}
1845
Mike Stump1eb44332009-09-09 15:08:12 +00001846// This can't be done with ReplaceStmt(S, ThrowExpr), since
1847// the throw expression is typically a message expression that's already
Steve Naroff2bd03922007-11-07 15:32:26 +00001848// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001849Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001850 // Get the start location and compute the semi location.
1851 SourceLocation startLoc = S->getLocStart();
1852 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001853
Steve Naroff2bd03922007-11-07 15:32:26 +00001854 assert((*startBuf == '@') && "bogus @throw location");
1855
1856 std::string buf;
1857 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001858 if (S->getThrowExpr())
1859 buf = "objc_exception_throw(";
1860 else // add an implicit argument
1861 buf = "objc_exception_throw(_caught";
Mike Stump1eb44332009-09-09 15:08:12 +00001862
Steve Naroff4ba0acb2008-07-25 15:41:30 +00001863 // handle "@ throw" correctly.
1864 const char *wBuf = strchr(startBuf, 'w');
1865 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1866 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001867
Steve Naroff2bd03922007-11-07 15:32:26 +00001868 const char *semiBuf = strchr(startBuf, ';');
1869 assert((*semiBuf == ';') && "@throw: can't find ';'");
1870 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1871 buf = ");";
Chris Lattneraadaf782008-01-31 19:51:04 +00001872 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001873 return 0;
1874}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001875
Steve Naroffb29b4272008-04-14 22:03:09 +00001876Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001877 // Create a new string expression.
1878 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001879 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001880 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattner2085fd62009-02-18 06:40:38 +00001881 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
1882 StrEncoding.length(), false,StrType,
1883 SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001884 ReplaceStmt(Exp, Replacement);
Mike Stump1eb44332009-09-09 15:08:12 +00001885
Chris Lattner07506182007-11-30 22:53:43 +00001886 // Replace this subexpr in the parent.
Steve Naroff4c3580e2008-12-04 23:50:32 +00001887 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00001888 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001889}
1890
Steve Naroffb29b4272008-04-14 22:03:09 +00001891Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff1a937642008-12-22 22:16:07 +00001892 if (!SelGetUidFunctionDecl)
1893 SynthSelGetUidFunctionDecl();
Steve Naroffb42f8412007-11-05 14:50:49 +00001894 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1895 // Create a call to sel_registerName("selName").
1896 llvm::SmallVector<Expr*, 8> SelExprs;
1897 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001898 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00001899 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00001900 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00001901 false, argType, SourceLocation()));
Steve Naroffb42f8412007-11-05 14:50:49 +00001902 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1903 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001904 ReplaceStmt(Exp, SelExp);
Steve Naroff4c3580e2008-12-04 23:50:32 +00001905 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00001906 return SelExp;
1907}
1908
Steve Naroffb29b4272008-04-14 22:03:09 +00001909CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff934f2762007-10-24 22:48:43 +00001910 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001911 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001912 QualType msgSendType = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001913
Steve Naroffebf2b562007-10-23 23:50:29 +00001914 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001915 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001916
Steve Naroffebf2b562007-10-23 23:50:29 +00001917 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001918 QualType pToFunc = Context->getPointerType(msgSendType);
Mike Stump1eb44332009-09-09 15:08:12 +00001919 ImplicitCastExpr *ICE = new (Context) ImplicitCastExpr(pToFunc,
Anders Carlssoncdef2b72009-07-31 00:48:10 +00001920 CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00001921 DRE,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001922 /*isLvalue=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00001923
John McCall183700f2009-09-21 23:43:11 +00001924 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001925
Ted Kremenek668bf912009-02-09 20:51:47 +00001926 return new (Context) CallExpr(*Context, ICE, args, nargs, FT->getResultType(),
1927 SourceLocation());
Steve Naroff934f2762007-10-24 22:48:43 +00001928}
1929
Steve Naroffd5255f52007-11-01 13:24:47 +00001930static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1931 const char *&startRef, const char *&endRef) {
1932 while (startBuf < endBuf) {
1933 if (*startBuf == '<')
1934 startRef = startBuf; // mark the start.
1935 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001936 if (startRef && *startRef == '<') {
1937 endRef = startBuf; // mark the end.
1938 return true;
1939 }
1940 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001941 }
1942 startBuf++;
1943 }
1944 return false;
1945}
1946
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001947static void scanToNextArgument(const char *&argRef) {
1948 int angle = 0;
1949 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1950 if (*argRef == '<')
1951 angle++;
1952 else if (*argRef == '>')
1953 angle--;
1954 argRef++;
1955 }
1956 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1957}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001958
Steve Naroffb29b4272008-04-14 22:03:09 +00001959bool RewriteObjC::needToScanForQualifiers(QualType T) {
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001960 return T->isObjCQualifiedIdType() || T->isObjCQualifiedInterfaceType();
Steve Naroffd5255f52007-11-01 13:24:47 +00001961}
1962
Steve Naroff4f95b752008-07-29 18:15:38 +00001963void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1964 QualType Type = E->getType();
1965 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00001966 SourceLocation Loc, EndLoc;
Mike Stump1eb44332009-09-09 15:08:12 +00001967
Steve Naroffcda658e2008-11-19 21:15:47 +00001968 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
1969 Loc = ECE->getLParenLoc();
1970 EndLoc = ECE->getRParenLoc();
1971 } else {
1972 Loc = E->getLocStart();
1973 EndLoc = E->getLocEnd();
1974 }
1975 // This will defend against trying to rewrite synthesized expressions.
1976 if (Loc.isInvalid() || EndLoc.isInvalid())
1977 return;
1978
Steve Naroff4f95b752008-07-29 18:15:38 +00001979 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00001980 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00001981 const char *startRef = 0, *endRef = 0;
1982 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1983 // Get the locations of the startRef, endRef.
1984 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1985 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1986 // Comment out the protocol references.
1987 InsertText(LessLoc, "/*", 2);
1988 InsertText(GreaterLoc, "*/", 2);
1989 }
1990 }
1991}
1992
Steve Naroffb29b4272008-04-14 22:03:09 +00001993void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001994 SourceLocation Loc;
1995 QualType Type;
Douglas Gregor72564e72009-02-26 23:50:07 +00001996 const FunctionProtoType *proto = 0;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001997 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1998 Loc = VD->getLocation();
1999 Type = VD->getType();
2000 }
2001 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2002 Loc = FD->getLocation();
2003 // Check for ObjC 'id' and class types that have been adorned with protocol
2004 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall183700f2009-09-21 23:43:11 +00002005 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002006 assert(funcType && "missing function type");
Douglas Gregor72564e72009-02-26 23:50:07 +00002007 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002008 if (!proto)
2009 return;
2010 Type = proto->getResultType();
2011 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00002012 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2013 Loc = FD->getLocation();
2014 Type = FD->getType();
2015 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002016 else
2017 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002018
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002019 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00002020 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002021
Steve Naroffd5255f52007-11-01 13:24:47 +00002022 const char *endBuf = SM->getCharacterData(Loc);
2023 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00002024 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00002025 startBuf--; // scan backward (from the decl location) for return type.
2026 const char *startRef = 0, *endRef = 0;
2027 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2028 // Get the locations of the startRef, endRef.
2029 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2030 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2031 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002032 InsertText(LessLoc, "/*", 2);
2033 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00002034 }
2035 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002036 if (!proto)
2037 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00002038 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002039 const char *startBuf = SM->getCharacterData(Loc);
2040 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00002041 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2042 if (needToScanForQualifiers(proto->getArgType(i))) {
2043 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002044
Steve Naroffd5255f52007-11-01 13:24:47 +00002045 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002046 // scan forward (from the decl location) for argument types.
2047 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00002048 const char *startRef = 0, *endRef = 0;
2049 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2050 // Get the locations of the startRef, endRef.
Mike Stump1eb44332009-09-09 15:08:12 +00002051 SourceLocation LessLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002052 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002053 SourceLocation GreaterLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002054 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002055 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002056 InsertText(LessLoc, "/*", 2);
2057 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00002058 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002059 startBuf = ++endBuf;
2060 }
2061 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00002062 // If the function name is derived from a macro expansion, then the
2063 // argument buffer will not follow the name. Need to speak with Chris.
2064 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002065 startBuf++; // scan forward (from the decl location) for argument types.
2066 startBuf++;
2067 }
Steve Naroffd5255f52007-11-01 13:24:47 +00002068 }
Steve Naroff9165ad32007-10-31 04:38:33 +00002069}
2070
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002071// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00002072void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002073 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2074 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002075 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002076 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002077 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002078 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002079 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002080 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002081 SelGetUidIdent, getFuncType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002082 FunctionDecl::Extern, false);
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002083}
2084
Steve Naroffb29b4272008-04-14 22:03:09 +00002085void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002086 // declared in <objc/objc.h>
Douglas Gregor51efe562009-01-09 01:47:02 +00002087 if (FD->getIdentifier() &&
2088 strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002089 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00002090 return;
2091 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002092 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00002093}
2094
Steve Naroffc0a123c2008-03-11 17:37:02 +00002095// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00002096void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002097 if (SuperContructorFunctionDecl)
2098 return;
Steve Naroff46a98a72008-12-23 20:11:22 +00002099 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroffc0a123c2008-03-11 17:37:02 +00002100 llvm::SmallVector<QualType, 16> ArgTys;
2101 QualType argT = Context->getObjCIdType();
2102 assert(!argT.isNull() && "Can't find 'id' type");
2103 ArgTys.push_back(argT);
2104 ArgTys.push_back(argT);
2105 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2106 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002107 false, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002108 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002109 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002110 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002111 FunctionDecl::Extern, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002112}
2113
Steve Naroff09b266e2007-10-30 23:14:51 +00002114// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002115void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002116 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2117 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002118 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002119 assert(!argT.isNull() && "Can't find 'id' type");
2120 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002121 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002122 assert(!argT.isNull() && "Can't find 'SEL' type");
2123 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002124 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002125 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002126 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002127 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002128 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002129 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002130 FunctionDecl::Extern, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002131}
2132
Steve Naroff874e2322007-11-15 10:28:18 +00002133// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002134void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00002135 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2136 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002137 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002138 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002139 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002140 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2141 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2142 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002143 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002144 assert(!argT.isNull() && "Can't find 'SEL' type");
2145 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002146 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00002147 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002148 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002149 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002150 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002151 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002152 FunctionDecl::Extern, false);
Steve Naroff874e2322007-11-15 10:28:18 +00002153}
2154
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002155// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002156void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002157 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2158 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002159 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002160 assert(!argT.isNull() && "Can't find 'id' type");
2161 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002162 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002163 assert(!argT.isNull() && "Can't find 'SEL' type");
2164 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002165 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002166 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002167 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002168 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002169 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002170 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002171 FunctionDecl::Extern, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002172}
2173
Mike Stump1eb44332009-09-09 15:08:12 +00002174// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002175// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002176void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump1eb44332009-09-09 15:08:12 +00002177 IdentifierInfo *msgSendIdent =
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002178 &Context->Idents.get("objc_msgSendSuper_stret");
2179 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002180 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002181 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002182 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002183 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2184 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2185 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002186 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002187 assert(!argT.isNull() && "Can't find 'SEL' type");
2188 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002189 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002190 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002191 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002192 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002193 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002194 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002195 FunctionDecl::Extern, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002196}
2197
Steve Naroff1284db82008-05-08 22:02:18 +00002198// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002199void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002200 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2201 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002202 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002203 assert(!argT.isNull() && "Can't find 'id' type");
2204 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002205 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002206 assert(!argT.isNull() && "Can't find 'SEL' type");
2207 ArgTys.push_back(argT);
Steve Naroff1284db82008-05-08 22:02:18 +00002208 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002209 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002210 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002211 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002212 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002213 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002214 FunctionDecl::Extern, false);
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002215}
2216
Steve Naroff09b266e2007-10-30 23:14:51 +00002217// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002218void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002219 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2220 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002221 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002222 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002223 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002224 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002225 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002226 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002227 getClassIdent, getClassType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002228 FunctionDecl::Extern, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002229}
2230
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002231// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002232void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002233 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2234 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002235 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002236 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002237 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002238 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002239 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002240 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002241 getClassIdent, getClassType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002242 FunctionDecl::Extern, false);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002243}
2244
Steve Naroffb29b4272008-04-14 22:03:09 +00002245Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002246 QualType strType = getConstantStringStructType();
2247
2248 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002249
2250 std::string tmpName = InFileName;
2251 unsigned i;
2252 for (i=0; i < tmpName.length(); i++) {
2253 char c = tmpName.at(i);
2254 // replace any non alphanumeric characters with '_'.
2255 if (!isalpha(c) && (c < '0' || c > '9'))
2256 tmpName[i] = '_';
2257 }
2258 S += tmpName;
2259 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002260 S += utostr(NumObjCStringLiterals++);
2261
Steve Naroffba92b2e2008-03-27 22:29:16 +00002262 Preamble += "static __NSConstantStringImpl " + S;
2263 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2264 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002265 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002266 std::string prettyBufS;
2267 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00002268 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2269 PrintingPolicy(LangOpts));
Steve Naroffba92b2e2008-03-27 22:29:16 +00002270 Preamble += prettyBuf.str();
2271 Preamble += ",";
Steve Narofffd5b76f2009-12-06 01:48:44 +00002272 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002273
2274 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2275 &Context->Idents.get(S.c_str()), strType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002276 VarDecl::Static);
Ted Kremenek8189cde2009-02-07 01:47:29 +00002277 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
2278 Expr *Unop = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002279 Context->getPointerType(DRE->getType()),
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002280 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002281 // cast to NSConstantString *
Mike Stump1eb44332009-09-09 15:08:12 +00002282 CastExpr *cast = new (Context) CStyleCastExpr(Exp->getType(),
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002283 CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00002284 Unop, Exp->getType(),
2285 SourceLocation(),
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002286 SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002287 ReplaceStmt(Exp, cast);
Steve Naroff4c3580e2008-12-04 23:50:32 +00002288 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002289 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002290}
2291
Steve Naroffb29b4272008-04-14 22:03:09 +00002292ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002293 // check if we are sending a message to 'super'
Douglas Gregorf8d49f62009-01-09 17:18:27 +00002294 if (!CurMethodDef || !CurMethodDef->isInstanceMethod()) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002295
Douglas Gregorcd9b46e2008-11-04 14:56:14 +00002296 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002297 const ObjCObjectPointerType *OPT =
John McCall183700f2009-09-21 23:43:11 +00002298 Super->getType()->getAs<ObjCObjectPointerType>();
Steve Naroff14108da2009-07-10 23:34:53 +00002299 assert(OPT);
2300 const ObjCInterfaceType *IT = OPT->getInterfaceType();
Chris Lattner0d17f6f2008-06-21 18:04:54 +00002301 return IT->getDecl();
2302 }
2303 return 0;
Steve Naroff874e2322007-11-15 10:28:18 +00002304}
2305
2306// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002307QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002308 if (!SuperStructDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002309 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002310 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002311 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002312 QualType FieldTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00002313
Steve Naroff874e2322007-11-15 10:28:18 +00002314 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002315 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002316 // struct objc_class *super;
Mike Stump1eb44332009-09-09 15:08:12 +00002317 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor44b43212008-12-11 16:49:14 +00002318
Steve Naroff874e2322007-11-15 10:28:18 +00002319 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002320 for (unsigned i = 0; i < 2; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002321 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2322 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002323 FieldTypes[i], 0,
2324 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002325 /*Mutable=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002326 }
Mike Stump1eb44332009-09-09 15:08:12 +00002327
Douglas Gregor44b43212008-12-11 16:49:14 +00002328 SuperStructDecl->completeDefinition(*Context);
Steve Naroff874e2322007-11-15 10:28:18 +00002329 }
2330 return Context->getTagDeclType(SuperStructDecl);
2331}
2332
Steve Naroffb29b4272008-04-14 22:03:09 +00002333QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002334 if (!ConstantStringDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002335 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002336 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002337 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002338 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002339
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002340 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002341 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002342 // int flags;
Mike Stump1eb44332009-09-09 15:08:12 +00002343 FieldTypes[1] = Context->IntTy;
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002344 // char *str;
Mike Stump1eb44332009-09-09 15:08:12 +00002345 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002346 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002347 FieldTypes[3] = Context->LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002348
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002349 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002350 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002351 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2352 ConstantStringDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00002353 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002354 FieldTypes[i], 0,
Douglas Gregor44b43212008-12-11 16:49:14 +00002355 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002356 /*Mutable=*/true));
Douglas Gregor44b43212008-12-11 16:49:14 +00002357 }
2358
2359 ConstantStringDecl->completeDefinition(*Context);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002360 }
2361 return Context->getTagDeclType(ConstantStringDecl);
2362}
2363
Steve Naroffb29b4272008-04-14 22:03:09 +00002364Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002365 if (!SelGetUidFunctionDecl)
2366 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002367 if (!MsgSendFunctionDecl)
2368 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002369 if (!MsgSendSuperFunctionDecl)
2370 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002371 if (!MsgSendStretFunctionDecl)
2372 SynthMsgSendStretFunctionDecl();
2373 if (!MsgSendSuperStretFunctionDecl)
2374 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002375 if (!MsgSendFpretFunctionDecl)
2376 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002377 if (!GetClassFunctionDecl)
2378 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002379 if (!GetMetaClassFunctionDecl)
2380 SynthGetMetaClassFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002381
Steve Naroff874e2322007-11-15 10:28:18 +00002382 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002383 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2384 // May need to use objc_msgSend_stret() as well.
2385 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroff621edce2009-04-29 16:37:50 +00002386 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2387 QualType resultType = mDecl->getResultType();
Chris Lattner8b51fd72008-07-26 22:36:27 +00002388 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002389 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002390 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002391 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002392 }
Mike Stump1eb44332009-09-09 15:08:12 +00002393
Steve Naroff934f2762007-10-24 22:48:43 +00002394 // Synthesize a call to objc_msgSend().
2395 llvm::SmallVector<Expr*, 8> MsgExprs;
2396 IdentifierInfo *clsName = Exp->getClassName();
Mike Stump1eb44332009-09-09 15:08:12 +00002397
Steve Naroff934f2762007-10-24 22:48:43 +00002398 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2399 if (clsName) { // class message.
Steve Narofffc93d522008-07-24 19:44:33 +00002400 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2401 // the 'super' idiom within a class method.
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00002402 if (clsName->getName() == "super") {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002403 MsgSendFlavor = MsgSendSuperFunctionDecl;
2404 if (MsgSendStretFlavor)
2405 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2406 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump1eb44332009-09-09 15:08:12 +00002407
2408 ObjCInterfaceDecl *SuperDecl =
Steve Naroff54055232008-10-27 17:20:55 +00002409 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002410
2411 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00002412
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002413 // set the receiver to self, the first argument to all methods.
Steve Naroff621edce2009-04-29 16:37:50 +00002414 InitExprs.push_back(
Mike Stump1eb44332009-09-09 15:08:12 +00002415 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002416 CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00002417 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroff621edce2009-04-29 16:37:50 +00002418 Context->getObjCIdType(),
2419 SourceLocation()),
2420 Context->getObjCIdType(),
2421 SourceLocation(), SourceLocation())); // set the 'receiver'.
2422
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002423 llvm::SmallVector<Expr*, 8> ClsExprs;
2424 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner2085fd62009-02-18 06:40:38 +00002425 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbare013d682009-10-18 20:26:12 +00002426 SuperDecl->getIdentifier()->getNameStart(),
2427 SuperDecl->getIdentifier()->getLength(),
2428 false, argType, SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002429 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002430 &ClsExprs[0],
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002431 ClsExprs.size());
2432 // To turn off a warning, type-cast to 'id'
Douglas Gregor49badde2008-10-27 19:41:14 +00002433 InitExprs.push_back( // set 'super class', using objc_getClass().
Mike Stump1eb44332009-09-09 15:08:12 +00002434 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002435 CastExpr::CK_Unknown,
Douglas Gregor49badde2008-10-27 19:41:14 +00002436 Cls, Context->getObjCIdType(),
Mike Stump1eb44332009-09-09 15:08:12 +00002437 SourceLocation(), SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002438 // struct objc_super
2439 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00002440 Expr *SuperRep;
Mike Stump1eb44332009-09-09 15:08:12 +00002441
Steve Naroff23f41272008-03-11 18:14:26 +00002442 if (LangOpts.Microsoft) {
2443 SynthSuperContructorFunctionDecl();
2444 // Simulate a contructor call...
Mike Stump1eb44332009-09-09 15:08:12 +00002445 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff23f41272008-03-11 18:14:26 +00002446 superType, SourceLocation());
Ted Kremenek668bf912009-02-09 20:51:47 +00002447 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00002448 InitExprs.size(),
Ted Kremenek668bf912009-02-09 20:51:47 +00002449 superType, SourceLocation());
Steve Naroff46a98a72008-12-23 20:11:22 +00002450 // The code for super is a little tricky to prevent collision with
2451 // the structure definition in the header. The rewriter has it's own
2452 // internal definition (__rw_objc_super) that is uses. This is why
2453 // we need the cast below. For example:
2454 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2455 //
Ted Kremenek8189cde2009-02-07 01:47:29 +00002456 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002457 Context->getPointerType(SuperRep->getType()),
Steve Naroff46a98a72008-12-23 20:11:22 +00002458 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002459 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
2460 CastExpr::CK_Unknown, SuperRep,
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002461 Context->getPointerType(superType),
Mike Stump1eb44332009-09-09 15:08:12 +00002462 SourceLocation(), SourceLocation());
2463 } else {
Steve Naroff23f41272008-03-11 18:14:26 +00002464 // (struct objc_super) { <exprs from above> }
Mike Stump1eb44332009-09-09 15:08:12 +00002465 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2466 &InitExprs[0], InitExprs.size(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002467 SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00002468 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE,
Chris Lattner418f6c72008-10-26 23:43:26 +00002469 false);
Steve Naroff46a98a72008-12-23 20:11:22 +00002470 // struct objc_super *
Ted Kremenek8189cde2009-02-07 01:47:29 +00002471 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002472 Context->getPointerType(SuperRep->getType()),
Steve Naroff46a98a72008-12-23 20:11:22 +00002473 SourceLocation());
Steve Naroff23f41272008-03-11 18:14:26 +00002474 }
Steve Naroff46a98a72008-12-23 20:11:22 +00002475 MsgExprs.push_back(SuperRep);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002476 } else {
2477 llvm::SmallVector<Expr*, 8> ClsExprs;
2478 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner2085fd62009-02-18 06:40:38 +00002479 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbare013d682009-10-18 20:26:12 +00002480 clsName->getNameStart(),
Chris Lattner2085fd62009-02-18 06:40:38 +00002481 clsName->getLength(),
2482 false, argType,
2483 SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002484 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002485 &ClsExprs[0],
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002486 ClsExprs.size());
2487 MsgExprs.push_back(Cls);
2488 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002489 } else { // instance message.
2490 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00002491
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002492 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00002493 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002494 if (MsgSendStretFlavor)
2495 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00002496 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump1eb44332009-09-09 15:08:12 +00002497
Steve Naroff874e2322007-11-15 10:28:18 +00002498 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00002499
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002500 InitExprs.push_back(
Mike Stump1eb44332009-09-09 15:08:12 +00002501 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002502 CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00002503 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Narofff616ebb2008-07-16 22:35:27 +00002504 Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002505 SourceLocation()),
2506 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002507 SourceLocation(), SourceLocation())); // set the 'receiver'.
Mike Stump1eb44332009-09-09 15:08:12 +00002508
Steve Naroff874e2322007-11-15 10:28:18 +00002509 llvm::SmallVector<Expr*, 8> ClsExprs;
2510 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002511 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbare013d682009-10-18 20:26:12 +00002512 SuperDecl->getIdentifier()->getNameStart(),
2513 SuperDecl->getIdentifier()->getLength(),
2514 false, argType, SourceLocation()));
Steve Naroff874e2322007-11-15 10:28:18 +00002515 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002516 &ClsExprs[0],
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002517 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00002518 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002519 InitExprs.push_back(
Douglas Gregor49badde2008-10-27 19:41:14 +00002520 // set 'super class', using objc_getClass().
Mike Stump1eb44332009-09-09 15:08:12 +00002521 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002522 CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00002523 Cls, Context->getObjCIdType(), SourceLocation(), SourceLocation()));
Steve Naroff874e2322007-11-15 10:28:18 +00002524 // struct objc_super
2525 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00002526 Expr *SuperRep;
Mike Stump1eb44332009-09-09 15:08:12 +00002527
Steve Naroffc0a123c2008-03-11 17:37:02 +00002528 if (LangOpts.Microsoft) {
2529 SynthSuperContructorFunctionDecl();
2530 // Simulate a contructor call...
Mike Stump1eb44332009-09-09 15:08:12 +00002531 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroffc0a123c2008-03-11 17:37:02 +00002532 superType, SourceLocation());
Ted Kremenek668bf912009-02-09 20:51:47 +00002533 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00002534 InitExprs.size(),
Ted Kremenek668bf912009-02-09 20:51:47 +00002535 superType, SourceLocation());
Steve Naroff46a98a72008-12-23 20:11:22 +00002536 // The code for super is a little tricky to prevent collision with
2537 // the structure definition in the header. The rewriter has it's own
2538 // internal definition (__rw_objc_super) that is uses. This is why
2539 // we need the cast below. For example:
2540 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2541 //
Ted Kremenek8189cde2009-02-07 01:47:29 +00002542 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002543 Context->getPointerType(SuperRep->getType()),
Steve Naroff46a98a72008-12-23 20:11:22 +00002544 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002545 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002546 CastExpr::CK_Unknown,
Steve Naroff46a98a72008-12-23 20:11:22 +00002547 SuperRep, Context->getPointerType(superType),
Mike Stump1eb44332009-09-09 15:08:12 +00002548 SourceLocation(), SourceLocation());
Steve Naroffc0a123c2008-03-11 17:37:02 +00002549 } else {
2550 // (struct objc_super) { <exprs from above> }
Mike Stump1eb44332009-09-09 15:08:12 +00002551 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2552 &InitExprs[0], InitExprs.size(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002553 SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00002554 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002555 }
Steve Naroff46a98a72008-12-23 20:11:22 +00002556 MsgExprs.push_back(SuperRep);
Steve Naroff874e2322007-11-15 10:28:18 +00002557 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002558 // Remove all type-casts because it may contain objc-style types; e.g.
2559 // Foo<Proto> *.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002560 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002561 recExpr = CE->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00002562 recExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002563 CastExpr::CK_Unknown, recExpr,
Mike Stump1eb44332009-09-09 15:08:12 +00002564 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002565 SourceLocation(), SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00002566 MsgExprs.push_back(recExpr);
2567 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002568 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00002569 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002570 llvm::SmallVector<Expr*, 8> SelExprs;
2571 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002572 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002573 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00002574 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00002575 false, argType, SourceLocation()));
Steve Naroff934f2762007-10-24 22:48:43 +00002576 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2577 &SelExprs[0], SelExprs.size());
2578 MsgExprs.push_back(SelExp);
Mike Stump1eb44332009-09-09 15:08:12 +00002579
Steve Naroff934f2762007-10-24 22:48:43 +00002580 // Now push any user supplied arguments.
2581 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002582 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002583 // Make all implicit casts explicit...ICE comes in handy:-)
2584 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2585 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregor49badde2008-10-27 19:41:14 +00002586 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002587 ? Context->getObjCIdType()
Douglas Gregor49badde2008-10-27 19:41:14 +00002588 : ICE->getType();
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002589 userExpr = new (Context) CStyleCastExpr(type, CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00002590 userExpr, type, SourceLocation(),
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002591 SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002592 }
2593 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002594 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002595 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002596 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002597 userExpr = CE->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00002598 userExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002599 CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00002600 userExpr, Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002601 SourceLocation(), SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002602 }
Mike Stump1eb44332009-09-09 15:08:12 +00002603 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002604 MsgExprs.push_back(userExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00002605 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2606 // out the argument in the original expression (since we aren't deleting
2607 // the ObjCMessageExpr). See RewritePropertySetter() usage for more info.
2608 //Exp->setArg(i, 0);
Steve Naroff934f2762007-10-24 22:48:43 +00002609 }
Steve Naroffab972d32007-11-04 22:37:50 +00002610 // Generate the funky cast.
2611 CastExpr *cast;
2612 llvm::SmallVector<QualType, 8> ArgTypes;
2613 QualType returnType;
Mike Stump1eb44332009-09-09 15:08:12 +00002614
Steve Naroffab972d32007-11-04 22:37:50 +00002615 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002616 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2617 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2618 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002619 ArgTypes.push_back(Context->getObjCIdType());
2620 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner89951a82009-02-20 18:43:26 +00002621 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002622 // Push any user argument types.
Chris Lattner89951a82009-02-20 18:43:26 +00002623 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2624 E = OMD->param_end(); PI != E; ++PI) {
2625 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump1eb44332009-09-09 15:08:12 +00002626 ? Context->getObjCIdType()
Chris Lattner89951a82009-02-20 18:43:26 +00002627 : (*PI)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00002628 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroff01f2ffa2008-12-11 21:05:33 +00002629 if (isTopLevelBlockPointerType(t)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002630 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroffa206b062008-10-29 14:49:46 +00002631 t = Context->getPointerType(BPT->getPointeeType());
2632 }
Steve Naroff352336b2007-11-05 14:36:37 +00002633 ArgTypes.push_back(t);
2634 }
Chris Lattner89951a82009-02-20 18:43:26 +00002635 returnType = OMD->getResultType()->isObjCQualifiedIdType()
2636 ? Context->getObjCIdType() : OMD->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00002637 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002638 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002639 }
2640 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002641 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002642
Steve Naroffab972d32007-11-04 22:37:50 +00002643 // Create a reference to the objc_msgSend() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00002644 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002645 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002646
Mike Stump1eb44332009-09-09 15:08:12 +00002647 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Naroffab972d32007-11-04 22:37:50 +00002648 // If we don't do this cast, we get the following bizarre warning/note:
2649 // xx.m:13: warning: function called through a non-compatible type
2650 // xx.m:13: note: if this code is reached, the program will abort
Mike Stump1eb44332009-09-09 15:08:12 +00002651 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy),
2652 CastExpr::CK_Unknown, DRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002653 Context->getPointerType(Context->VoidTy),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002654 SourceLocation(), SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002655
Steve Naroffab972d32007-11-04 22:37:50 +00002656 // Now do the "normal" pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00002657 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002658 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00002659 // If we don't have a method decl, force a variadic cast.
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002660 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Naroffab972d32007-11-04 22:37:50 +00002661 castType = Context->getPointerType(castType);
Mike Stump1eb44332009-09-09 15:08:12 +00002662 cast = new (Context) CStyleCastExpr(castType, CastExpr::CK_Unknown, cast,
2663 castType, SourceLocation(),
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002664 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002665
2666 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002667 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump1eb44332009-09-09 15:08:12 +00002668
John McCall183700f2009-09-21 23:43:11 +00002669 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00002670 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00002671 MsgExprs.size(),
Ted Kremenek668bf912009-02-09 20:51:47 +00002672 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002673 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002674 if (MsgSendStretFlavor) {
2675 // We have the method which returns a struct/union. Must also generate
2676 // call to objc_msgSend_stret and hang both varieties on a conditional
2677 // expression which dictate which one to envoke depending on size of
2678 // method's return type.
Mike Stump1eb44332009-09-09 15:08:12 +00002679
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002680 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00002681 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002682 SourceLocation());
2683 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Mike Stump1eb44332009-09-09 15:08:12 +00002684 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy),
2685 CastExpr::CK_Unknown, STDRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002686 Context->getPointerType(Context->VoidTy),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002687 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002688 // Now do the "normal" pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00002689 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002690 &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002691 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002692 castType = Context->getPointerType(castType);
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002693 cast = new (Context) CStyleCastExpr(castType, CastExpr::CK_Unknown,
2694 cast, castType, SourceLocation(), SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002695
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002696 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002697 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump1eb44332009-09-09 15:08:12 +00002698
John McCall183700f2009-09-21 23:43:11 +00002699 FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00002700 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00002701 MsgExprs.size(),
Ted Kremenek668bf912009-02-09 20:51:47 +00002702 FT->getResultType(), SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002703
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002704 // Build sizeof(returnType)
Mike Stump1eb44332009-09-09 15:08:12 +00002705 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
John McCalla93c9342009-12-07 02:54:59 +00002706 Context->getTrivialTypeSourceInfo(returnType),
Sebastian Redl05189992008-11-11 17:56:53 +00002707 Context->getSizeType(),
2708 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002709 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2710 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2711 // For X86 it is more complicated and some kind of target specific routine
2712 // is needed to decide what to do.
Mike Stump1eb44332009-09-09 15:08:12 +00002713 unsigned IntSize =
Chris Lattner98be4942008-03-05 18:54:05 +00002714 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Mike Stump1eb44332009-09-09 15:08:12 +00002715 IntegerLiteral *limit = new (Context) IntegerLiteral(llvm::APInt(IntSize, 8),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002716 Context->IntTy,
2717 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002718 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
2719 BinaryOperator::LE,
2720 Context->IntTy,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002721 SourceLocation());
2722 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump1eb44332009-09-09 15:08:12 +00002723 ConditionalOperator *CondExpr =
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00002724 new (Context) ConditionalOperator(lessThanExpr,
2725 SourceLocation(), CE,
2726 SourceLocation(), STCE, returnType);
Ted Kremenek8189cde2009-02-07 01:47:29 +00002727 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002728 }
Mike Stump1eb44332009-09-09 15:08:12 +00002729 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002730 return ReplacingStmt;
2731}
2732
Steve Naroffb29b4272008-04-14 22:03:09 +00002733Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002734 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Mike Stump1eb44332009-09-09 15:08:12 +00002735
Steve Naroff934f2762007-10-24 22:48:43 +00002736 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002737 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00002738
2739 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002740 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002741}
2742
Steve Naroff621edce2009-04-29 16:37:50 +00002743// typedef struct objc_object Protocol;
2744QualType RewriteObjC::getProtocolType() {
2745 if (!ProtocolTypeDecl) {
John McCalla93c9342009-12-07 02:54:59 +00002746 TypeSourceInfo *TInfo
2747 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroff621edce2009-04-29 16:37:50 +00002748 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002749 SourceLocation(),
Steve Naroff621edce2009-04-29 16:37:50 +00002750 &Context->Idents.get("Protocol"),
John McCalla93c9342009-12-07 02:54:59 +00002751 TInfo);
Steve Naroff621edce2009-04-29 16:37:50 +00002752 }
2753 return Context->getTypeDeclType(ProtocolTypeDecl);
2754}
2755
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002756/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroff621edce2009-04-29 16:37:50 +00002757/// a synthesized/forward data reference (to the protocol's metadata).
2758/// The forward references (and metadata) are generated in
2759/// RewriteObjC::HandleTranslationUnit().
Steve Naroffb29b4272008-04-14 22:03:09 +00002760Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroff621edce2009-04-29 16:37:50 +00002761 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
2762 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00002763 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Douglas Gregor0da76df2009-11-23 11:41:28 +00002764 ID, getProtocolType(), 0, VarDecl::Extern);
Steve Naroff621edce2009-04-29 16:37:50 +00002765 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), SourceLocation());
2766 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
2767 Context->getPointerType(DRE->getType()),
2768 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002769 CastExpr *castExpr = new (Context) CStyleCastExpr(DerefExpr->getType(),
2770 CastExpr::CK_Unknown,
2771 DerefExpr, DerefExpr->getType(),
Steve Naroff621edce2009-04-29 16:37:50 +00002772 SourceLocation(), SourceLocation());
2773 ReplaceStmt(Exp, castExpr);
2774 ProtocolExprDecls.insert(Exp->getProtocol());
Mike Stump1eb44332009-09-09 15:08:12 +00002775 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00002776 return castExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00002777
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002778}
2779
Mike Stump1eb44332009-09-09 15:08:12 +00002780bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffbaf58c32008-05-31 14:15:04 +00002781 const char *endBuf) {
2782 while (startBuf < endBuf) {
2783 if (*startBuf == '#') {
2784 // Skip whitespace.
2785 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2786 ;
2787 if (!strncmp(startBuf, "if", strlen("if")) ||
2788 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2789 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2790 !strncmp(startBuf, "define", strlen("define")) ||
2791 !strncmp(startBuf, "undef", strlen("undef")) ||
2792 !strncmp(startBuf, "else", strlen("else")) ||
2793 !strncmp(startBuf, "elif", strlen("elif")) ||
2794 !strncmp(startBuf, "endif", strlen("endif")) ||
2795 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2796 !strncmp(startBuf, "include", strlen("include")) ||
2797 !strncmp(startBuf, "import", strlen("import")) ||
2798 !strncmp(startBuf, "include_next", strlen("include_next")))
2799 return true;
2800 }
2801 startBuf++;
2802 }
2803 return false;
2804}
2805
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002806/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002807/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00002808void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002809 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002810 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Mike Stump1eb44332009-09-09 15:08:12 +00002811 assert(CDecl->getNameAsCString() &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002812 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002813 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002814 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002815 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002816 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002817 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00002818 SourceLocation LocStart = CDecl->getLocStart();
2819 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00002820
Steve Narofffea763e82007-11-14 19:25:57 +00002821 const char *startBuf = SM->getCharacterData(LocStart);
2822 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump1eb44332009-09-09 15:08:12 +00002823
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002824 // If no ivars and no root or if its root, directly or indirectly,
2825 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002826 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2827 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner2c78b872009-04-14 23:22:57 +00002828 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Chris Lattneraadaf782008-01-31 19:51:04 +00002829 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002830 return;
2831 }
Mike Stump1eb44332009-09-09 15:08:12 +00002832
2833 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002834 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002835 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002836 Result += CDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002837 if (LangOpts.Microsoft)
2838 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00002839
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002840 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002841 const char *cursor = strchr(startBuf, '{');
Mike Stump1eb44332009-09-09 15:08:12 +00002842 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002843 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00002844 // If the buffer contains preprocessor directives, we do more fine-grained
2845 // rewrites. This is intended to fix code that looks like (which occurs in
2846 // NSURL.h, for example):
2847 //
2848 // #ifdef XYZ
2849 // @interface Foo : NSObject
2850 // #else
2851 // @interface FooBar : NSObject
2852 // #endif
2853 // {
2854 // int i;
2855 // }
2856 // @end
2857 //
2858 // This clause is segregated to avoid breaking the common case.
2859 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002860 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffbaf58c32008-05-31 14:15:04 +00002861 CDecl->getClassLoc();
2862 const char *endHeader = SM->getCharacterData(L);
Chris Lattner2c78b872009-04-14 23:22:57 +00002863 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffbaf58c32008-05-31 14:15:04 +00002864
Chris Lattnercafeb352009-02-20 18:18:36 +00002865 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00002866 // advance to the end of the referenced protocols.
2867 while (endHeader < cursor && *endHeader != '>') endHeader++;
2868 endHeader++;
2869 }
2870 // rewrite the original header
2871 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2872 } else {
2873 // rewrite the original header *without* disturbing the '{'
Steve Naroff17c87782009-12-04 21:36:32 +00002874 ReplaceText(LocStart, cursor-startBuf, Result.c_str(), Result.size());
Steve Naroffbaf58c32008-05-31 14:15:04 +00002875 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002876 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002877 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002878 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002879 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002880 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00002881 Result += "_IVARS;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002882
Steve Narofffea763e82007-11-14 19:25:57 +00002883 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002884 SourceLocation OnePastCurly =
2885 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2886 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002887 }
2888 cursor++; // past '{'
Mike Stump1eb44332009-09-09 15:08:12 +00002889
Steve Narofffea763e82007-11-14 19:25:57 +00002890 // Now comment out any visibility specifiers.
2891 while (cursor < endBuf) {
2892 if (*cursor == '@') {
2893 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002894 // Skip whitespace.
2895 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2896 /*scan*/;
2897
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002898 // FIXME: presence of @public, etc. inside comment results in
2899 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002900 if (!strncmp(cursor, "public", strlen("public")) ||
2901 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00002902 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002903 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002904 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002905 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002906 // FIXME: If there are cases where '<' is used in ivar declaration part
2907 // of user code, then scan the ivar list and use needToScanForQualifiers
2908 // for type checking.
2909 else if (*cursor == '<') {
2910 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002911 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002912 cursor = strchr(cursor, '>');
2913 cursor++;
2914 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002915 InsertText(atLoc, " */", 3);
Steve Naroffced80a82008-10-30 12:09:33 +00002916 } else if (*cursor == '^') { // rewrite block specifier.
2917 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2918 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002919 }
Steve Narofffea763e82007-11-14 19:25:57 +00002920 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002921 }
Steve Narofffea763e82007-11-14 19:25:57 +00002922 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002923 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00002924 } else { // we don't have any instance variables - insert super struct.
Chris Lattner2c78b872009-04-14 23:22:57 +00002925 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Narofffea763e82007-11-14 19:25:57 +00002926 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002927 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002928 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002929 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00002930 Result += "_IVARS;\n};\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00002931 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002932 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002933 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002934 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00002935 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002936}
2937
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002938// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002939/// class methods.
Douglas Gregor653f1b12009-04-23 01:02:12 +00002940template<typename MethodIterator>
2941void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
2942 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002943 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002944 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002945 const char *ClassName,
2946 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002947 if (MethodBegin == MethodEnd) return;
Mike Stump1eb44332009-09-09 15:08:12 +00002948
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002949 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002950 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002951 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002952 SEL _cmd;
2953 char *method_types;
2954 void *_imp;
2955 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002956 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002957 Result += "\nstruct _objc_method {\n";
2958 Result += "\tSEL _cmd;\n";
2959 Result += "\tchar *method_types;\n";
2960 Result += "\tvoid *_imp;\n";
2961 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002962
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002963 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002964 }
Mike Stump1eb44332009-09-09 15:08:12 +00002965
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002966 // Build _objc_method_list for class's methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00002967
Steve Naroff946a6932008-03-11 00:12:29 +00002968 /* struct {
2969 struct _objc_method_list *next_method;
2970 int method_count;
2971 struct _objc_method method_list[];
2972 }
2973 */
Douglas Gregor653f1b12009-04-23 01:02:12 +00002974 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroff946a6932008-03-11 00:12:29 +00002975 Result += "\nstatic struct {\n";
2976 Result += "\tstruct _objc_method_list *next_method;\n";
2977 Result += "\tint method_count;\n";
2978 Result += "\tstruct _objc_method method_list[";
Douglas Gregor653f1b12009-04-23 01:02:12 +00002979 Result += utostr(NumMethods);
Steve Naroff946a6932008-03-11 00:12:29 +00002980 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002981 Result += prefix;
2982 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2983 Result += "_METHODS_";
2984 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002985 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002986 Result += IsInstanceMethod ? "inst" : "cls";
2987 Result += "_meth\")))= ";
Douglas Gregor653f1b12009-04-23 01:02:12 +00002988 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002989
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002990 Result += "\t,{{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002991 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002992 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002993 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002994 Result += "\", \"";
2995 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002996 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002997 Result += MethodInternalNames[*MethodBegin];
2998 Result += "}\n";
2999 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3000 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003001 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003002 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003003 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003004 Result += "\", \"";
3005 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003006 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003007 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00003008 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003009 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003010 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003011}
3012
Steve Naroff621edce2009-04-29 16:37:50 +00003013/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00003014void RewriteObjC::
Steve Naroff621edce2009-04-29 16:37:50 +00003015RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, const char *prefix,
3016 const char *ClassName, std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003017 static bool objc_protocol_methods = false;
Steve Naroff621edce2009-04-29 16:37:50 +00003018
3019 // Output struct protocol_methods holder of method selector and type.
3020 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3021 /* struct protocol_methods {
3022 SEL _cmd;
3023 char *method_types;
3024 }
3025 */
3026 Result += "\nstruct _protocol_methods {\n";
3027 Result += "\tstruct objc_selector *_cmd;\n";
3028 Result += "\tchar *method_types;\n";
3029 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003030
Steve Naroff621edce2009-04-29 16:37:50 +00003031 objc_protocol_methods = true;
3032 }
3033 // Do not synthesize the protocol more than once.
3034 if (ObjCSynthesizedProtocols.count(PDecl))
3035 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003036
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003037 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3038 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3039 PDecl->instmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003040 /* struct _objc_protocol_method_list {
3041 int protocol_method_count;
3042 struct protocol_methods protocols[];
3043 }
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003044 */
Steve Naroff621edce2009-04-29 16:37:50 +00003045 Result += "\nstatic struct {\n";
3046 Result += "\tint protocol_method_count;\n";
3047 Result += "\tstruct _protocol_methods protocol_methods[";
3048 Result += utostr(NumMethods);
3049 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3050 Result += PDecl->getNameAsString();
3051 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3052 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003053
Steve Naroff621edce2009-04-29 16:37:50 +00003054 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003055 for (ObjCProtocolDecl::instmeth_iterator
3056 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003057 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003058 if (I == PDecl->instmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003059 Result += "\t ,{{(struct objc_selector *)\"";
3060 else
3061 Result += "\t ,{(struct objc_selector *)\"";
3062 Result += (*I)->getSelector().getAsString().c_str();
3063 std::string MethodTypeString;
3064 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3065 Result += "\", \"";
3066 Result += MethodTypeString;
3067 Result += "\"}\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003068 }
Steve Naroff621edce2009-04-29 16:37:50 +00003069 Result += "\t }\n};\n";
3070 }
Mike Stump1eb44332009-09-09 15:08:12 +00003071
Steve Naroff621edce2009-04-29 16:37:50 +00003072 // Output class methods declared in this protocol.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003073 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3074 PDecl->classmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003075 if (NumMethods > 0) {
3076 /* struct _objc_protocol_method_list {
3077 int protocol_method_count;
3078 struct protocol_methods protocols[];
3079 }
3080 */
3081 Result += "\nstatic struct {\n";
3082 Result += "\tint protocol_method_count;\n";
3083 Result += "\tstruct _protocol_methods protocol_methods[";
3084 Result += utostr(NumMethods);
3085 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3086 Result += PDecl->getNameAsString();
3087 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3088 "{\n\t";
3089 Result += utostr(NumMethods);
3090 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003091
Steve Naroff621edce2009-04-29 16:37:50 +00003092 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003093 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003094 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003095 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003096 if (I == PDecl->classmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003097 Result += "\t ,{{(struct objc_selector *)\"";
3098 else
3099 Result += "\t ,{(struct objc_selector *)\"";
3100 Result += (*I)->getSelector().getAsString().c_str();
3101 std::string MethodTypeString;
3102 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3103 Result += "\", \"";
3104 Result += MethodTypeString;
3105 Result += "\"}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003106 }
Steve Naroff621edce2009-04-29 16:37:50 +00003107 Result += "\t }\n};\n";
3108 }
3109
3110 // Output:
3111 /* struct _objc_protocol {
3112 // Objective-C 1.0 extensions
3113 struct _objc_protocol_extension *isa;
3114 char *protocol_name;
3115 struct _objc_protocol **protocol_list;
3116 struct _objc_protocol_method_list *instance_methods;
3117 struct _objc_protocol_method_list *class_methods;
Mike Stump1eb44332009-09-09 15:08:12 +00003118 };
Steve Naroff621edce2009-04-29 16:37:50 +00003119 */
3120 static bool objc_protocol = false;
3121 if (!objc_protocol) {
3122 Result += "\nstruct _objc_protocol {\n";
3123 Result += "\tstruct _objc_protocol_extension *isa;\n";
3124 Result += "\tchar *protocol_name;\n";
3125 Result += "\tstruct _objc_protocol **protocol_list;\n";
3126 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3127 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003128 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003129
Steve Naroff621edce2009-04-29 16:37:50 +00003130 objc_protocol = true;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003131 }
Mike Stump1eb44332009-09-09 15:08:12 +00003132
Steve Naroff621edce2009-04-29 16:37:50 +00003133 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3134 Result += PDecl->getNameAsString();
3135 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3136 "{\n\t0, \"";
3137 Result += PDecl->getNameAsString();
3138 Result += "\", 0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003139 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003140 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3141 Result += PDecl->getNameAsString();
3142 Result += ", ";
3143 }
3144 else
3145 Result += "0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003146 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003147 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3148 Result += PDecl->getNameAsString();
3149 Result += "\n";
3150 }
3151 else
3152 Result += "0\n";
3153 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003154
Steve Naroff621edce2009-04-29 16:37:50 +00003155 // Mark this protocol as having been generated.
3156 if (!ObjCSynthesizedProtocols.insert(PDecl))
3157 assert(false && "protocol already synthesized");
3158
3159}
3160
3161void RewriteObjC::
3162RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
3163 const char *prefix, const char *ClassName,
3164 std::string &Result) {
3165 if (Protocols.empty()) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003166
Steve Naroff621edce2009-04-29 16:37:50 +00003167 for (unsigned i = 0; i != Protocols.size(); i++)
3168 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3169
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003170 // Output the top lovel protocol meta-data for the class.
3171 /* struct _objc_protocol_list {
3172 struct _objc_protocol_list *next;
3173 int protocol_count;
3174 struct _objc_protocol *class_protocols[];
3175 }
3176 */
3177 Result += "\nstatic struct {\n";
3178 Result += "\tstruct _objc_protocol_list *next;\n";
3179 Result += "\tint protocol_count;\n";
3180 Result += "\tstruct _objc_protocol *class_protocols[";
3181 Result += utostr(Protocols.size());
3182 Result += "];\n} _OBJC_";
3183 Result += prefix;
3184 Result += "_PROTOCOLS_";
3185 Result += ClassName;
3186 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3187 "{\n\t0, ";
3188 Result += utostr(Protocols.size());
3189 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003190
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003191 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003192 Result += Protocols[0]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003193 Result += " \n";
Mike Stump1eb44332009-09-09 15:08:12 +00003194
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003195 for (unsigned i = 1; i != Protocols.size(); i++) {
3196 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003197 Result += Protocols[i]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003198 Result += "\n";
3199 }
3200 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003201}
3202
Steve Naroff621edce2009-04-29 16:37:50 +00003203
Mike Stump1eb44332009-09-09 15:08:12 +00003204/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003205/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00003206void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003207 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003208 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003209 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003210 ObjCCategoryDecl *CDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00003211 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003212 CDecl = CDecl->getNextClassCategory())
3213 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3214 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003215
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003216 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00003217 FullCategoryName += '_';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003218 FullCategoryName += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003219
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003220 // Build _objc_method_list for class's instance methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003221 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003222 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003223
3224 // If any of our property implementations have associated getters or
3225 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003226 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3227 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003228 Prop != PropEnd; ++Prop) {
3229 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3230 continue;
3231 if (!(*Prop)->getPropertyIvarDecl())
3232 continue;
3233 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3234 if (!PD)
3235 continue;
3236 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3237 InstanceMethods.push_back(Getter);
3238 if (PD->isReadOnly())
3239 continue;
3240 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3241 InstanceMethods.push_back(Setter);
3242 }
3243 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003244 true, "CATEGORY_", FullCategoryName.c_str(),
3245 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003246
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003247 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003248 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003249 false, "CATEGORY_", FullCategoryName.c_str(),
3250 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003251
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003252 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00003253 // Null CDecl is case of a category implementation with no category interface
3254 if (CDecl)
Steve Naroff621edce2009-04-29 16:37:50 +00003255 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
3256 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003257 /* struct _objc_category {
3258 char *category_name;
3259 char *class_name;
3260 struct _objc_method_list *instance_methods;
3261 struct _objc_method_list *class_methods;
3262 struct _objc_protocol_list *protocols;
3263 // Objective-C 1.0 extensions
3264 uint32_t size; // sizeof (struct _objc_category)
Mike Stump1eb44332009-09-09 15:08:12 +00003265 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003266 // @property decl.
Mike Stump1eb44332009-09-09 15:08:12 +00003267 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003268 */
Mike Stump1eb44332009-09-09 15:08:12 +00003269
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003270 static bool objc_category = false;
3271 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003272 Result += "\nstruct _objc_category {\n";
3273 Result += "\tchar *category_name;\n";
3274 Result += "\tchar *class_name;\n";
3275 Result += "\tstruct _objc_method_list *instance_methods;\n";
3276 Result += "\tstruct _objc_method_list *class_methods;\n";
3277 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003278 Result += "\tunsigned int size;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003279 Result += "\tstruct _objc_property_list *instance_properties;\n";
3280 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003281 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003282 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003283 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3284 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003285 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003286 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003287 Result += "\"\n\t, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003288 Result += ClassDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003289 Result += "\"\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003290
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003291 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003292 Result += "\t, (struct _objc_method_list *)"
3293 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3294 Result += FullCategoryName;
3295 Result += "\n";
3296 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003297 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003298 Result += "\t, 0\n";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003299 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003300 Result += "\t, (struct _objc_method_list *)"
3301 "&_OBJC_CATEGORY_CLASS_METHODS_";
3302 Result += FullCategoryName;
3303 Result += "\n";
3304 }
3305 else
3306 Result += "\t, 0\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003307
Chris Lattnercafeb352009-02-20 18:18:36 +00003308 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003309 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003310 Result += FullCategoryName;
3311 Result += "\n";
3312 }
3313 else
3314 Result += "\t, 0\n";
3315 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003316}
3317
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003318/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3319/// ivar offset.
Mike Stump1eb44332009-09-09 15:08:12 +00003320void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
3321 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003322 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00003323 if (ivar->isBitField()) {
3324 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3325 // place all bitfields at offset 0.
3326 Result += "0";
3327 } else {
3328 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003329 Result += IDecl->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003330 if (LangOpts.Microsoft)
3331 Result += "_IMPL";
3332 Result += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003333 Result += ivar->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003334 Result += ")";
3335 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003336}
3337
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003338//===----------------------------------------------------------------------===//
3339// Meta Data Emission
3340//===----------------------------------------------------------------------===//
3341
Steve Naroffb29b4272008-04-14 22:03:09 +00003342void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003343 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003344 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00003345
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003346 // Explictly declared @interface's are already synthesized.
Steve Naroff33feeb02009-04-20 20:09:33 +00003347 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003348 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003349 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003350 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003351 }
Mike Stump1eb44332009-09-09 15:08:12 +00003352
Chris Lattnerbe6df082007-12-12 07:56:42 +00003353 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003354 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump1eb44332009-09-09 15:08:12 +00003355 ? IDecl->ivar_size()
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003356 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003357 if (NumIvars > 0) {
3358 static bool objc_ivar = false;
3359 if (!objc_ivar) {
3360 /* struct _objc_ivar {
3361 char *ivar_name;
3362 char *ivar_type;
3363 int ivar_offset;
Mike Stump1eb44332009-09-09 15:08:12 +00003364 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003365 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003366 Result += "\nstruct _objc_ivar {\n";
3367 Result += "\tchar *ivar_name;\n";
3368 Result += "\tchar *ivar_type;\n";
3369 Result += "\tint ivar_offset;\n";
3370 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003371
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003372 objc_ivar = true;
3373 }
3374
Steve Naroff946a6932008-03-11 00:12:29 +00003375 /* struct {
3376 int ivar_count;
3377 struct _objc_ivar ivar_list[nIvars];
Mike Stump1eb44332009-09-09 15:08:12 +00003378 };
Steve Naroff946a6932008-03-11 00:12:29 +00003379 */
Mike Stump1eb44332009-09-09 15:08:12 +00003380 Result += "\nstatic struct {\n";
Steve Naroff946a6932008-03-11 00:12:29 +00003381 Result += "\tint ivar_count;\n";
3382 Result += "\tstruct _objc_ivar ivar_list[";
3383 Result += utostr(NumIvars);
3384 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003385 Result += IDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003386 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003387 "{\n\t";
3388 Result += utostr(NumIvars);
3389 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003390
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003391 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003392 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003393 if (!IDecl->ivar_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003394 for (ObjCImplementationDecl::ivar_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003395 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003396 IV != IVEnd; ++IV)
3397 IVars.push_back(*IV);
3398 IVI = IVars.begin();
3399 IVE = IVars.end();
Chris Lattnerbe6df082007-12-12 07:56:42 +00003400 } else {
3401 IVI = CDecl->ivar_begin();
3402 IVE = CDecl->ivar_end();
3403 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003404 Result += "\t,{{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003405 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003406 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003407 std::string TmpString, StrEncoding;
3408 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3409 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003410 Result += StrEncoding;
3411 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003412 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003413 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003414 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003415 Result += "\t ,{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003416 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003417 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003418 std::string TmpString, StrEncoding;
3419 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3420 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003421 Result += StrEncoding;
3422 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003423 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003424 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003425 }
Mike Stump1eb44332009-09-09 15:08:12 +00003426
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003427 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003428 }
Mike Stump1eb44332009-09-09 15:08:12 +00003429
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003430 // Build _objc_method_list for class's instance methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003431 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003432 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003433
3434 // If any of our property implementations have associated getters or
3435 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003436 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3437 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003438 Prop != PropEnd; ++Prop) {
3439 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3440 continue;
3441 if (!(*Prop)->getPropertyIvarDecl())
3442 continue;
3443 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3444 if (!PD)
3445 continue;
3446 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3447 InstanceMethods.push_back(Getter);
3448 if (PD->isReadOnly())
3449 continue;
3450 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3451 InstanceMethods.push_back(Setter);
3452 }
3453 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003454 true, "", IDecl->getNameAsCString(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003455
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003456 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003457 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003458 false, "", IDecl->getNameAsCString(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003459
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003460 // Protocols referenced in class declaration?
Steve Naroff621edce2009-04-29 16:37:50 +00003461 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
3462 "CLASS", CDecl->getNameAsCString(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003463
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003464 // Declaration of class/meta-class metadata
3465 /* struct _objc_class {
3466 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003467 const char *super_class_name;
3468 char *name;
3469 long version;
3470 long info;
3471 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003472 struct _objc_ivar_list *ivars;
3473 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003474 struct objc_cache *cache;
3475 struct objc_protocol_list *protocols;
3476 const char *ivar_layout;
3477 struct _objc_class_ext *ext;
Mike Stump1eb44332009-09-09 15:08:12 +00003478 };
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003479 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003480 static bool objc_class = false;
3481 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003482 Result += "\nstruct _objc_class {\n";
3483 Result += "\tstruct _objc_class *isa;\n";
3484 Result += "\tconst char *super_class_name;\n";
3485 Result += "\tchar *name;\n";
3486 Result += "\tlong version;\n";
3487 Result += "\tlong info;\n";
3488 Result += "\tlong instance_size;\n";
3489 Result += "\tstruct _objc_ivar_list *ivars;\n";
3490 Result += "\tstruct _objc_method_list *methods;\n";
3491 Result += "\tstruct objc_cache *cache;\n";
3492 Result += "\tstruct _objc_protocol_list *protocols;\n";
3493 Result += "\tconst char *ivar_layout;\n";
3494 Result += "\tstruct _objc_class_ext *ext;\n";
3495 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003496 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003497 }
Mike Stump1eb44332009-09-09 15:08:12 +00003498
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003499 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003500 ObjCInterfaceDecl *RootClass = 0;
3501 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003502 while (SuperClass) {
3503 RootClass = SuperClass;
3504 SuperClass = SuperClass->getSuperClass();
3505 }
3506 SuperClass = CDecl->getSuperClass();
Mike Stump1eb44332009-09-09 15:08:12 +00003507
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003508 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003509 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003510 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003511 "{\n\t(struct _objc_class *)\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003512 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003513 Result += "\"";
3514
3515 if (SuperClass) {
3516 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003517 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003518 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003519 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003520 Result += "\"";
3521 }
3522 else {
3523 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003524 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003525 Result += "\"";
3526 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003527 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003528 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003529 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003530 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff23f41272008-03-11 18:14:26 +00003531 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003532 Result += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003533 Result += "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003534 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003535 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003536 Result += ", 0\n";
Chris Lattnercafeb352009-02-20 18:18:36 +00003537 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003538 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003539 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003540 Result += ",0,0\n";
3541 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003542 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003543 Result += "\t,0,0,0,0\n";
3544 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003545
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003546 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003547 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003548 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003549 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003550 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003551 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003552 if (SuperClass) {
3553 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003554 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003555 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003556 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003557 Result += "\"";
3558 }
3559 else {
3560 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003561 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003562 Result += "\"";
3563 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003564 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003565 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003566 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003567 Result += ",0";
3568 else {
3569 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003570 Result += ",sizeof(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003571 Result += CDecl->getNameAsString();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003572 if (LangOpts.Microsoft)
3573 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003574 Result += ")";
3575 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003576 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00003577 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003578 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003579 Result += "\n\t";
3580 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003581 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003582 Result += ",0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003583 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroff946a6932008-03-11 00:12:29 +00003584 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003585 Result += CDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003586 Result += ", 0\n\t";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003587 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003588 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003589 Result += ",0,0";
Chris Lattnercafeb352009-02-20 18:18:36 +00003590 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003591 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003592 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003593 Result += ", 0,0\n";
3594 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003595 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003596 Result += ",0,0,0\n";
3597 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003598}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003599
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003600/// RewriteImplementations - This routine rewrites all method implementations
3601/// and emits meta-data.
3602
Steve Narofface66252008-11-13 20:07:04 +00003603void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003604 int ClsDefCount = ClassImplementation.size();
3605 int CatDefCount = CategoryImplementation.size();
Mike Stump1eb44332009-09-09 15:08:12 +00003606
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003607 // Rewrite implemented methods
3608 for (int i = 0; i < ClsDefCount; i++)
3609 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00003610
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003611 for (int i = 0; i < CatDefCount; i++)
3612 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00003613}
Mike Stump1eb44332009-09-09 15:08:12 +00003614
Steve Narofface66252008-11-13 20:07:04 +00003615void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3616 int ClsDefCount = ClassImplementation.size();
3617 int CatDefCount = CategoryImplementation.size();
3618
Steve Naroff5df5b762008-05-07 21:23:49 +00003619 // This is needed for determining instance variable offsets.
Mike Stump1eb44332009-09-09 15:08:12 +00003620 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003621 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003622 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003623 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003624
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003625 // For each implemented category, write out all its meta data.
3626 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003627 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroff621edce2009-04-29 16:37:50 +00003628
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003629 // Write objc_symtab metadata
3630 /*
3631 struct _objc_symtab
3632 {
3633 long sel_ref_cnt;
3634 SEL *refs;
3635 short cls_def_cnt;
3636 short cat_def_cnt;
3637 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump1eb44332009-09-09 15:08:12 +00003638 };
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003639 */
Mike Stump1eb44332009-09-09 15:08:12 +00003640
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003641 Result += "\nstruct _objc_symtab {\n";
3642 Result += "\tlong sel_ref_cnt;\n";
3643 Result += "\tSEL *refs;\n";
3644 Result += "\tshort cls_def_cnt;\n";
3645 Result += "\tshort cat_def_cnt;\n";
3646 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3647 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003648
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003649 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00003650 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003651 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003652 + ", " + utostr(CatDefCount) + "\n";
3653 for (int i = 0; i < ClsDefCount; i++) {
3654 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003655 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003656 Result += "\n";
3657 }
Mike Stump1eb44332009-09-09 15:08:12 +00003658
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003659 for (int i = 0; i < CatDefCount; i++) {
3660 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003661 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003662 Result += "_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003663 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003664 Result += "\n";
3665 }
Mike Stump1eb44332009-09-09 15:08:12 +00003666
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003667 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003668
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003669 // Write objc_module metadata
Mike Stump1eb44332009-09-09 15:08:12 +00003670
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003671 /*
3672 struct _objc_module {
3673 long version;
3674 long size;
3675 const char *name;
3676 struct _objc_symtab *symtab;
3677 }
3678 */
Mike Stump1eb44332009-09-09 15:08:12 +00003679
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003680 Result += "\nstruct _objc_module {\n";
3681 Result += "\tlong version;\n";
3682 Result += "\tlong size;\n";
3683 Result += "\tconst char *name;\n";
3684 Result += "\tstruct _objc_symtab *symtab;\n";
3685 Result += "};\n\n";
3686 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00003687 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003688 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003689 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003690 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003691
3692 if (LangOpts.Microsoft) {
Steve Naroff621edce2009-04-29 16:37:50 +00003693 if (ProtocolExprDecls.size()) {
3694 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
3695 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003696 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00003697 E = ProtocolExprDecls.end(); I != E; ++I) {
3698 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
3699 Result += (*I)->getNameAsString();
3700 Result += " = &_OBJC_PROTOCOL_";
3701 Result += (*I)->getNameAsString();
3702 Result += ";\n";
3703 }
3704 Result += "#pragma data_seg(pop)\n\n";
3705 }
Steve Naroff4f943c22008-03-10 20:43:59 +00003706 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00003707 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003708 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3709 Result += "&_OBJC_MODULES;\n";
3710 Result += "#pragma data_seg(pop)\n\n";
3711 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003712}
Chris Lattner311ff022007-10-16 22:36:42 +00003713
Steve Naroff54055232008-10-27 17:20:55 +00003714std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3715 const char *funcName,
3716 std::string Tag) {
3717 const FunctionType *AFT = CE->getFunctionType();
3718 QualType RT = AFT->getResultType();
3719 std::string StructRef = "struct " + Tag;
3720 std::string S = "static " + RT.getAsString() + " __" +
3721 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003722
Steve Naroff54055232008-10-27 17:20:55 +00003723 BlockDecl *BD = CE->getBlockDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00003724
Douglas Gregor72564e72009-02-26 23:50:07 +00003725 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003726 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Naroffdf8570d2009-02-02 17:19:26 +00003727 // block (to reference imported block decl refs).
3728 S += "(" + StructRef + " *__cself)";
Steve Naroff54055232008-10-27 17:20:55 +00003729 } else if (BD->param_empty()) {
3730 S += "(" + StructRef + " *__cself)";
3731 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00003732 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff54055232008-10-27 17:20:55 +00003733 assert(FT && "SynthesizeBlockFunc: No function proto");
3734 S += '(';
3735 // first add the implicit argument.
3736 S += StructRef + " *__cself, ";
3737 std::string ParamStr;
3738 for (BlockDecl::param_iterator AI = BD->param_begin(),
3739 E = BD->param_end(); AI != E; ++AI) {
3740 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003741 ParamStr = (*AI)->getNameAsString();
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00003742 (*AI)->getType().getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00003743 S += ParamStr;
3744 }
3745 if (FT->isVariadic()) {
3746 if (!BD->param_empty()) S += ", ";
3747 S += "...";
3748 }
3749 S += ')';
3750 }
3751 S += " {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003752
Steve Naroff54055232008-10-27 17:20:55 +00003753 // Create local declarations to avoid rewriting all closure decl ref exprs.
3754 // First, emit a declaration for all "by ref" decls.
Mike Stump1eb44332009-09-09 15:08:12 +00003755 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003756 E = BlockByRefDecls.end(); I != E; ++I) {
3757 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003758 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00003759 std::string TypeString = "struct __Block_byref_" + Name + " *";
3760 Name = TypeString + Name;
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003761 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003762 }
Steve Naroff54055232008-10-27 17:20:55 +00003763 // Next, emit a declaration for all "by copy" declarations.
Mike Stump1eb44332009-09-09 15:08:12 +00003764 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003765 E = BlockByCopyDecls.end(); I != E; ++I) {
3766 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003767 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003768 // Handle nested closure invocation. For example:
3769 //
3770 // void (^myImportedClosure)(void);
3771 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00003772 //
Steve Naroff54055232008-10-27 17:20:55 +00003773 // void (^anotherClosure)(void);
3774 // anotherClosure = ^(void) {
3775 // myImportedClosure(); // import and invoke the closure
3776 // };
3777 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003778 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00003779 S += "struct __block_impl *";
3780 else
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00003781 (*I)->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003782 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff54055232008-10-27 17:20:55 +00003783 }
3784 std::string RewrittenStr = RewrittenBlockExprs[CE];
3785 const char *cstr = RewrittenStr.c_str();
3786 while (*cstr++ != '{') ;
3787 S += cstr;
3788 S += "\n";
3789 return S;
3790}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003791
Steve Naroff54055232008-10-27 17:20:55 +00003792std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3793 const char *funcName,
3794 std::string Tag) {
3795 std::string StructRef = "struct " + Tag;
3796 std::string S = "static void __";
Mike Stump1eb44332009-09-09 15:08:12 +00003797
Steve Naroff54055232008-10-27 17:20:55 +00003798 S += funcName;
3799 S += "_block_copy_" + utostr(i);
3800 S += "(" + StructRef;
3801 S += "*dst, " + StructRef;
3802 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00003803 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003804 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00003805 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003806 S += (*I)->getNameAsString();
Steve Naroff47a24222008-12-11 20:51:38 +00003807 S += ", (void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003808 S += (*I)->getNameAsString();
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00003809 if (BlockByRefDecls.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00003810 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00003811 else
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00003812 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00003813 }
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00003814 S += "}\n";
3815
Steve Naroff54055232008-10-27 17:20:55 +00003816 S += "\nstatic void __";
3817 S += funcName;
3818 S += "_block_dispose_" + utostr(i);
3819 S += "(" + StructRef;
3820 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00003821 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003822 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00003823 S += "_Block_object_dispose((void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003824 S += (*I)->getNameAsString();
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00003825 if (BlockByRefDecls.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00003826 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00003827 else
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00003828 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00003829 }
Mike Stump1eb44332009-09-09 15:08:12 +00003830 S += "}\n";
Steve Naroff54055232008-10-27 17:20:55 +00003831 return S;
3832}
3833
Steve Naroff01aec112009-12-06 21:14:13 +00003834std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3835 std::string Desc) {
Steve Naroffced80a82008-10-30 12:09:33 +00003836 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00003837 std::string Constructor = " " + Tag;
Mike Stump1eb44332009-09-09 15:08:12 +00003838
Steve Naroff54055232008-10-27 17:20:55 +00003839 S += " {\n struct __block_impl impl;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003840 S += " struct " + Desc;
3841 S += "* Desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003842
Steve Naroff01aec112009-12-06 21:14:13 +00003843 Constructor += "(void *fp, "; // Invoke function pointer.
3844 Constructor += "struct " + Desc; // Descriptor pointer.
3845 Constructor += " *desc";
Mike Stump1eb44332009-09-09 15:08:12 +00003846
Steve Naroff54055232008-10-27 17:20:55 +00003847 if (BlockDeclRefs.size()) {
3848 // Output all "by copy" declarations.
Mike Stump1eb44332009-09-09 15:08:12 +00003849 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003850 E = BlockByCopyDecls.end(); I != E; ++I) {
3851 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003852 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003853 std::string ArgName = "_" + FieldName;
3854 // Handle nested closure invocation. For example:
3855 //
3856 // void (^myImportedBlock)(void);
3857 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00003858 //
Steve Naroff54055232008-10-27 17:20:55 +00003859 // void (^anotherBlock)(void);
3860 // anotherBlock = ^(void) {
3861 // myImportedBlock(); // import and invoke the closure
3862 // };
3863 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003864 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00003865 S += "struct __block_impl *";
3866 Constructor += ", void *" + ArgName;
3867 } else {
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00003868 (*I)->getType().getAsStringInternal(FieldName, Context->PrintingPolicy);
3869 (*I)->getType().getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00003870 Constructor += ", " + ArgName;
3871 }
3872 S += FieldName + ";\n";
3873 }
3874 // Output all "by ref" declarations.
Mike Stump1eb44332009-09-09 15:08:12 +00003875 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003876 E = BlockByRefDecls.end(); I != E; ++I) {
3877 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003878 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003879 std::string ArgName = "_" + FieldName;
3880 // Handle nested closure invocation. For example:
3881 //
3882 // void (^myImportedBlock)(void);
3883 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00003884 //
Steve Naroff54055232008-10-27 17:20:55 +00003885 // void (^anotherBlock)(void);
3886 // anotherBlock = ^(void) {
3887 // myImportedBlock(); // import and invoke the closure
3888 // };
3889 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003890 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00003891 S += "struct __block_impl *";
3892 Constructor += ", void *" + ArgName;
3893 } else {
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00003894 std::string TypeString = "struct __Block_byref_" + FieldName;
3895 TypeString += " *";
3896 FieldName = TypeString + FieldName;
3897 ArgName = TypeString + ArgName;
Steve Naroff54055232008-10-27 17:20:55 +00003898 Constructor += ", " + ArgName;
3899 }
3900 S += FieldName + "; // by ref\n";
3901 }
3902 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00003903 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00003904 if (GlobalVarDecl)
3905 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3906 else
3907 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003908 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003909
Steve Naroff01aec112009-12-06 21:14:13 +00003910 Constructor += " Desc = desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003911
Steve Naroff54055232008-10-27 17:20:55 +00003912 // Initialize all "by copy" arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00003913 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003914 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003915 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003916 Constructor += " ";
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003917 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00003918 Constructor += Name + " = (struct __block_impl *)_";
3919 else
3920 Constructor += Name + " = _";
3921 Constructor += Name + ";\n";
3922 }
3923 // Initialize all "by ref" arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00003924 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003925 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003926 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003927 Constructor += " ";
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003928 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00003929 Constructor += Name + " = (struct __block_impl *)_";
3930 else
3931 Constructor += Name + " = _";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00003932 Constructor += Name + "->__forwarding;\n";
Steve Naroff54055232008-10-27 17:20:55 +00003933 }
3934 } else {
3935 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00003936 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00003937 if (GlobalVarDecl)
3938 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3939 else
3940 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003941 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3942 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00003943 }
3944 Constructor += " ";
3945 Constructor += "}\n";
3946 S += Constructor;
3947 S += "};\n";
3948 return S;
3949}
3950
Steve Naroff01aec112009-12-06 21:14:13 +00003951std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
3952 std::string ImplTag, int i,
3953 const char *FunName,
3954 unsigned hasCopy) {
3955 std::string S = "\nstatic struct " + DescTag;
3956
3957 S += " {\n unsigned long reserved;\n";
3958 S += " unsigned long Block_size;\n";
3959 if (hasCopy) {
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00003960 S += " void (*copy)(struct ";
3961 S += ImplTag; S += "*, struct ";
3962 S += ImplTag; S += "*);\n";
3963
3964 S += " void (*dispose)(struct ";
3965 S += ImplTag; S += "*);\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003966 }
3967 S += "} ";
3968
3969 S += DescTag + "_DATA = { 0, sizeof(struct ";
3970 S += ImplTag + ")";
3971 if (hasCopy) {
3972 S += ", __" + std::string(FunName) + "_block_copy_" + utostr(i);
3973 S += ", __" + std::string(FunName) + "_block_dispose_" + utostr(i);
3974 }
3975 S += "};\n";
3976 return S;
3977}
3978
Steve Naroff54055232008-10-27 17:20:55 +00003979void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3980 const char *FunName) {
3981 // Insert closures that were part of the function.
3982 for (unsigned i = 0; i < Blocks.size(); i++) {
3983
3984 CollectBlockDeclRefInfo(Blocks[i]);
3985
Steve Naroff01aec112009-12-06 21:14:13 +00003986 std::string ImplTag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
3987 std::string DescTag = "__" + std::string(FunName) + "_block_desc_" + utostr(i);
Mike Stump1eb44332009-09-09 15:08:12 +00003988
Steve Naroff01aec112009-12-06 21:14:13 +00003989 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff54055232008-10-27 17:20:55 +00003990
3991 InsertText(FunLocStart, CI.c_str(), CI.size());
3992
Steve Naroff01aec112009-12-06 21:14:13 +00003993 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump1eb44332009-09-09 15:08:12 +00003994
Steve Naroff54055232008-10-27 17:20:55 +00003995 InsertText(FunLocStart, CF.c_str(), CF.size());
3996
3997 if (ImportedBlockDecls.size()) {
Steve Naroff01aec112009-12-06 21:14:13 +00003998 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Steve Naroff54055232008-10-27 17:20:55 +00003999 InsertText(FunLocStart, HF.c_str(), HF.size());
4000 }
Steve Naroff01aec112009-12-06 21:14:13 +00004001 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4002 ImportedBlockDecls.size() > 0);
4003 InsertText(FunLocStart, BD.c_str(), BD.size());
Mike Stump1eb44332009-09-09 15:08:12 +00004004
Steve Naroff54055232008-10-27 17:20:55 +00004005 BlockDeclRefs.clear();
4006 BlockByRefDecls.clear();
4007 BlockByCopyDecls.clear();
4008 BlockCallExprs.clear();
4009 ImportedBlockDecls.clear();
4010 }
4011 Blocks.clear();
4012 RewrittenBlockExprs.clear();
4013}
4014
4015void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4016 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner8ec03f52008-11-24 03:54:41 +00004017 const char *FuncName = FD->getNameAsCString();
Mike Stump1eb44332009-09-09 15:08:12 +00004018
Steve Naroff54055232008-10-27 17:20:55 +00004019 SynthesizeBlockLiterals(FunLocStart, FuncName);
4020}
4021
4022void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00004023 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4024 //SourceLocation FunLocStart = MD->getLocStart();
4025 // FIXME: This hack works around a bug in Rewrite.InsertText().
4026 SourceLocation FunLocStart = MD->getLocStart().getFileLocWithOffset(-1);
Chris Lattner077bf5e2008-11-24 03:33:13 +00004027 std::string FuncName = MD->getSelector().getAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004028 // Convert colons to underscores.
4029 std::string::size_type loc = 0;
4030 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4031 FuncName.replace(loc, 1, "_");
Mike Stump1eb44332009-09-09 15:08:12 +00004032
Steve Naroff54055232008-10-27 17:20:55 +00004033 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
4034}
4035
4036void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
4037 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4038 CI != E; ++CI)
4039 if (*CI) {
4040 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4041 GetBlockDeclRefExprs(CBE->getBody());
4042 else
4043 GetBlockDeclRefExprs(*CI);
4044 }
4045 // Handle specific things.
4046 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
4047 // FIXME: Handle enums.
4048 if (!isa<FunctionDecl>(CDRE->getDecl()))
4049 BlockDeclRefs.push_back(CDRE);
4050 return;
4051}
4052
4053void RewriteObjC::GetBlockCallExprs(Stmt *S) {
4054 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4055 CI != E; ++CI)
4056 if (*CI) {
4057 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4058 GetBlockCallExprs(CBE->getBody());
4059 else
4060 GetBlockCallExprs(*CI);
4061 }
Mike Stump1eb44332009-09-09 15:08:12 +00004062
Steve Naroff54055232008-10-27 17:20:55 +00004063 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
4064 if (CE->getCallee()->getType()->isBlockPointerType()) {
4065 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
4066 }
4067 }
4068 return;
4069}
4070
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004071Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff54055232008-10-27 17:20:55 +00004072 // Navigate to relevant type information.
Steve Naroff54055232008-10-27 17:20:55 +00004073 const BlockPointerType *CPT = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004074
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004075 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004076 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004077 } else if (const BlockDeclRefExpr *CDRE =
4078 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004079 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004080 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004081 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004082 }
4083 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4084 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4085 }
4086 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4087 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4088 else if (const ConditionalOperator *CEXPR =
4089 dyn_cast<ConditionalOperator>(BlockExp)) {
4090 Expr *LHSExp = CEXPR->getLHS();
4091 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4092 Expr *RHSExp = CEXPR->getRHS();
4093 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4094 Expr *CONDExp = CEXPR->getCond();
4095 ConditionalOperator *CondExpr =
4096 new (Context) ConditionalOperator(CONDExp,
4097 SourceLocation(), cast<Expr>(LHSStmt),
4098 SourceLocation(), cast<Expr>(RHSStmt),
4099 Exp->getType());
4100 return CondExpr;
Fariborz Jahaniane24b22b2009-12-18 01:15:21 +00004101 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4102 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004103 } else {
4104 assert(1 && "RewriteBlockClass: Bad type");
4105 }
4106 assert(CPT && "RewriteBlockClass: Bad type");
John McCall183700f2009-09-21 23:43:11 +00004107 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff54055232008-10-27 17:20:55 +00004108 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor72564e72009-02-26 23:50:07 +00004109 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff54055232008-10-27 17:20:55 +00004110 // FTP will be null for closures that don't take arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004111
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004112 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
4113 SourceLocation(),
4114 &Context->Idents.get("__block_impl"));
4115 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00004116
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004117 // Generate a funky cast.
4118 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00004119
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004120 // Push the block argument type.
4121 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00004122 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004123 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004124 E = FTP->arg_type_end(); I && (I != E); ++I) {
4125 QualType t = *I;
4126 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004127 if (isTopLevelBlockPointerType(t)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004128 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004129 t = Context->getPointerType(BPT->getPointeeType());
4130 }
4131 ArgTypes.push_back(t);
4132 }
Steve Naroff54055232008-10-27 17:20:55 +00004133 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004134 // Now do the pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00004135 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004136 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00004137
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004138 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump1eb44332009-09-09 15:08:12 +00004139
4140 CastExpr *BlkCast = new (Context) CStyleCastExpr(PtrBlock,
Anders Carlssoncdef2b72009-07-31 00:48:10 +00004141 CastExpr::CK_Unknown,
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004142 const_cast<Expr*>(BlockExp),
Ted Kremenek8189cde2009-02-07 01:47:29 +00004143 PtrBlock, SourceLocation(),
4144 SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004145 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004146 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4147 BlkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004148 //PE->dump();
Mike Stump1eb44332009-09-09 15:08:12 +00004149
Douglas Gregor44b43212008-12-11 16:49:14 +00004150 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00004151 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004152 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004153 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4154 FD->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00004155
Anders Carlssoncdef2b72009-07-31 00:48:10 +00004156 CastExpr *FunkCast = new (Context) CStyleCastExpr(PtrToFuncCastType,
4157 CastExpr::CK_Unknown, ME,
Ted Kremenek8189cde2009-02-07 01:47:29 +00004158 PtrToFuncCastType,
4159 SourceLocation(),
4160 SourceLocation());
4161 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump1eb44332009-09-09 15:08:12 +00004162
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004163 llvm::SmallVector<Expr*, 8> BlkExprs;
4164 // Add the implicit argument.
4165 BlkExprs.push_back(BlkCast);
4166 // Add the user arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004167 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004168 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004169 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00004170 }
Ted Kremenek668bf912009-02-09 20:51:47 +00004171 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4172 BlkExprs.size(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00004173 Exp->getType(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004174 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00004175}
4176
4177void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004178 Stmt *BlockCall = SynthesizeBlockCall(Exp, Exp->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004179 ReplaceStmt(Exp, BlockCall);
Steve Naroff54055232008-10-27 17:20:55 +00004180}
4181
Steve Naroff621edce2009-04-29 16:37:50 +00004182// We need to return the rewritten expression to handle cases where the
4183// BlockDeclRefExpr is embedded in another expression being rewritten.
4184// For example:
4185//
4186// int main() {
4187// __block Foo *f;
4188// __block int i;
Mike Stump1eb44332009-09-09 15:08:12 +00004189//
Steve Naroff621edce2009-04-29 16:37:50 +00004190// void (^myblock)() = ^() {
4191// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4192// i = 77;
4193// };
4194//}
4195Stmt *RewriteObjC::RewriteBlockDeclRefExpr(BlockDeclRefExpr *BDRE) {
Fariborz Jahanianbbf37e22009-12-23 19:26:34 +00004196 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4197 // for each BDRE where BYREFVAR is name of the variable.
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004198 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4199 &Context->Idents.get("__forwarding"),
4200 Context->VoidPtrTy, 0,
4201 /*BitWidth=*/0, /*Mutable=*/true);
4202 MemberExpr *ME = new (Context) MemberExpr(BDRE, true, FD, SourceLocation(),
4203 FD->getType());
4204 const char *Name = BDRE->getDecl()->getNameAsCString();
4205 FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4206 &Context->Idents.get(Name),
4207 Context->VoidPtrTy, 0,
4208 /*BitWidth=*/0, /*Mutable=*/true);
4209 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
4210 BDRE->getType());
4211
4212
4213
Steve Naroffdf8570d2009-02-02 17:19:26 +00004214 // Need parens to enforce precedence.
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004215 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4216 ME);
Steve Naroffdf8570d2009-02-02 17:19:26 +00004217 ReplaceStmt(BDRE, PE);
Steve Naroff621edce2009-04-29 16:37:50 +00004218 return PE;
Steve Naroff54055232008-10-27 17:20:55 +00004219}
4220
Steve Naroffb2f9e512008-11-03 23:29:32 +00004221void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4222 SourceLocation LocStart = CE->getLParenLoc();
4223 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00004224
4225 // Need to avoid trying to rewrite synthesized casts.
4226 if (LocStart.isInvalid())
4227 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00004228 // Need to avoid trying to rewrite casts contained in macros.
4229 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4230 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004231
Steve Naroff54055232008-10-27 17:20:55 +00004232 const char *startBuf = SM->getCharacterData(LocStart);
4233 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump1eb44332009-09-09 15:08:12 +00004234
Steve Naroff54055232008-10-27 17:20:55 +00004235 // advance the location to startArgList.
4236 const char *argPtr = startBuf;
Mike Stump1eb44332009-09-09 15:08:12 +00004237
Steve Naroff54055232008-10-27 17:20:55 +00004238 while (*argPtr++ && (argPtr < endBuf)) {
4239 switch (*argPtr) {
Mike Stump1eb44332009-09-09 15:08:12 +00004240 case '^':
Steve Naroff54055232008-10-27 17:20:55 +00004241 // Replace the '^' with '*'.
4242 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
4243 ReplaceText(LocStart, 1, "*", 1);
4244 break;
4245 }
4246 }
4247 return;
4248}
4249
4250void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4251 SourceLocation DeclLoc = FD->getLocation();
4252 unsigned parenCount = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004253
Steve Naroff54055232008-10-27 17:20:55 +00004254 // We have 1 or more arguments that have closure pointers.
4255 const char *startBuf = SM->getCharacterData(DeclLoc);
4256 const char *startArgList = strchr(startBuf, '(');
Mike Stump1eb44332009-09-09 15:08:12 +00004257
Steve Naroff54055232008-10-27 17:20:55 +00004258 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004259
Steve Naroff54055232008-10-27 17:20:55 +00004260 parenCount++;
4261 // advance the location to startArgList.
4262 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4263 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump1eb44332009-09-09 15:08:12 +00004264
Steve Naroff54055232008-10-27 17:20:55 +00004265 const char *argPtr = startArgList;
Mike Stump1eb44332009-09-09 15:08:12 +00004266
Steve Naroff54055232008-10-27 17:20:55 +00004267 while (*argPtr++ && parenCount) {
4268 switch (*argPtr) {
Mike Stump1eb44332009-09-09 15:08:12 +00004269 case '^':
Steve Naroff54055232008-10-27 17:20:55 +00004270 // Replace the '^' with '*'.
4271 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
4272 ReplaceText(DeclLoc, 1, "*", 1);
4273 break;
Mike Stump1eb44332009-09-09 15:08:12 +00004274 case '(':
4275 parenCount++;
Steve Naroff54055232008-10-27 17:20:55 +00004276 break;
Mike Stump1eb44332009-09-09 15:08:12 +00004277 case ')':
Steve Naroff54055232008-10-27 17:20:55 +00004278 parenCount--;
4279 break;
4280 }
4281 }
4282 return;
4283}
4284
4285bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004286 const FunctionProtoType *FTP;
Ted Kremenek6217b802009-07-29 21:53:49 +00004287 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004288 if (PT) {
John McCall183700f2009-09-21 23:43:11 +00004289 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004290 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00004291 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004292 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall183700f2009-09-21 23:43:11 +00004293 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004294 }
4295 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004296 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004297 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004298 if (isTopLevelBlockPointerType(*I))
Steve Naroff54055232008-10-27 17:20:55 +00004299 return true;
4300 }
4301 return false;
4302}
4303
Ted Kremenek8189cde2009-02-07 01:47:29 +00004304void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4305 const char *&RParen) {
Steve Naroff54055232008-10-27 17:20:55 +00004306 const char *argPtr = strchr(Name, '(');
4307 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004308
Steve Naroff54055232008-10-27 17:20:55 +00004309 LParen = argPtr; // output the start.
4310 argPtr++; // skip past the left paren.
4311 unsigned parenCount = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004312
Steve Naroff54055232008-10-27 17:20:55 +00004313 while (*argPtr && parenCount) {
4314 switch (*argPtr) {
4315 case '(': parenCount++; break;
4316 case ')': parenCount--; break;
4317 default: break;
4318 }
4319 if (parenCount) argPtr++;
4320 }
4321 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4322 RParen = argPtr; // output the end
4323}
4324
4325void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4326 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4327 RewriteBlockPointerFunctionArgs(FD);
4328 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004329 }
Steve Naroff54055232008-10-27 17:20:55 +00004330 // Handle Variables and Typedefs.
4331 SourceLocation DeclLoc = ND->getLocation();
4332 QualType DeclT;
4333 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4334 DeclT = VD->getType();
4335 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4336 DeclT = TDD->getUnderlyingType();
4337 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4338 DeclT = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00004339 else
Steve Naroff54055232008-10-27 17:20:55 +00004340 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump1eb44332009-09-09 15:08:12 +00004341
Steve Naroff54055232008-10-27 17:20:55 +00004342 const char *startBuf = SM->getCharacterData(DeclLoc);
4343 const char *endBuf = startBuf;
4344 // scan backward (from the decl location) for the end of the previous decl.
4345 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4346 startBuf--;
Mike Stump1eb44332009-09-09 15:08:12 +00004347
Steve Naroff54055232008-10-27 17:20:55 +00004348 // *startBuf != '^' if we are dealing with a pointer to function that
4349 // may take block argument types (which will be handled below).
4350 if (*startBuf == '^') {
4351 // Replace the '^' with '*', computing a negative offset.
4352 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
4353 ReplaceText(DeclLoc, 1, "*", 1);
4354 }
4355 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4356 // Replace the '^' with '*' for arguments.
4357 DeclLoc = ND->getLocation();
4358 startBuf = SM->getCharacterData(DeclLoc);
4359 const char *argListBegin, *argListEnd;
4360 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4361 while (argListBegin < argListEnd) {
4362 if (*argListBegin == '^') {
4363 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
4364 ReplaceText(CaretLoc, 1, "*", 1);
4365 }
4366 argListBegin++;
4367 }
4368 }
4369 return;
4370}
4371
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004372/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4373/// the declaration into:
4374/// struct __Block_byref_ND {
4375/// void *__isa; // NULL for everything except __weak pointers
4376/// struct __Block_byref_ND *__forwarding;
4377/// int32_t __flags;
4378/// int32_t __size;
4379/// void *__ByrefKeepFuncPtr; // Only if variable is __block ObjC object
4380/// void *__ByrefDestroyFuncPtr; // Only if variable is __block ObjC object
4381/// typex ND;
4382/// };
4383///
4384/// It then replaces declaration of ND variable with:
4385/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4386/// __size=sizeof(struct __Block_byref_ND),
4387/// ND=initializer-if-any};
4388///
4389///
4390void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
4391 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4392 const char *startBuf = SM->getCharacterData(DeclLoc);
4393 const char *endBuf = SM->getCharacterData(ND->getLocEnd());
4394 std::string Name(ND->getNameAsString());
4395 std::string ByrefType = "struct __Block_byref_";
4396 ByrefType += Name;
4397 ByrefType += " {\n";
4398 ByrefType += " void *__isa;\n";
4399 ByrefType += " struct __Block_byref_" + Name + " *__forwarding;\n";
4400 ByrefType += " int __flags;\n";
4401 ByrefType += " int __size;\n";
4402 // FIXME. Add void *__ByrefKeepFuncPtr; void *__ByrefDestroyFuncPtr;
4403 // if needed.
4404 ND->getType().getAsStringInternal(Name, Context->PrintingPolicy);
4405 ByrefType += " " + Name + ";\n";
4406 ByrefType += "};\n";
4407 // Insert this type in global scope. It is needed by helper function.
4408 assert(CurFunctionDef && "RewriteByRefVar - CurFunctionDef is null");
4409 SourceLocation FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4410 InsertText(FunLocStart, ByrefType.c_str(), ByrefType.size());
4411
4412 // struct __Block_byref_ND ND =
4413 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4414 // initializer-if-any};
4415 bool hasInit = (ND->getInit() != 0);
4416 Name = ND->getNameAsString();
4417 ByrefType = "struct __Block_byref_" + Name;
4418 if (!hasInit) {
4419 ByrefType += " " + Name + " = ";
4420 ByrefType += "{0, &" + Name + ", ";
4421 // FIXME. Compute the flag.
4422 ByrefType += "0, ";
4423 ByrefType += "sizeof(struct __Block_byref_" + Name + ")";
4424 ByrefType += "};\n";
4425 ReplaceText(DeclLoc, endBuf-startBuf+Name.size(),
4426 ByrefType.c_str(), ByrefType.size());
4427 }
4428 else {
4429 SourceLocation startLoc = ND->getInit()->getLocStart();
4430 ByrefType += " " + Name;
4431 ReplaceText(DeclLoc, endBuf-startBuf,
4432 ByrefType.c_str(), ByrefType.size());
4433 ByrefType = " = {0, &" + Name + ", ";
4434 // FIXME. Compute the flag.
4435 ByrefType += "0, ";
4436 ByrefType += "sizeof(struct __Block_byref_" + Name + "), ";
4437 InsertText(startLoc, ByrefType.c_str(), ByrefType.size());
Steve Naroffc5143c52009-12-23 17:24:33 +00004438
4439 // Complete the newly synthesized compound expression by inserting a right
4440 // curly brace before the end of the declaration.
4441 // FIXME: This approach avoids rewriting the initializer expression. It
4442 // also assumes there is only one declarator. For example, the following
4443 // isn't currently supported by this routine (in general):
4444 //
4445 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4446 //
4447 const char *startBuf = SM->getCharacterData(startLoc);
4448 const char *semiBuf = strchr(startBuf, ';');
4449 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4450 SourceLocation semiLoc =
4451 startLoc.getFileLocWithOffset(semiBuf-startBuf);
4452
4453 InsertText(semiLoc, "}", 1);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004454 }
Fariborz Jahanian1be6b462009-12-22 00:48:54 +00004455 return;
4456}
4457
Mike Stump1eb44332009-09-09 15:08:12 +00004458void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00004459 // Add initializers for any closure decl refs.
4460 GetBlockDeclRefExprs(Exp->getBody());
4461 if (BlockDeclRefs.size()) {
4462 // Unique all "by copy" declarations.
4463 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4464 if (!BlockDeclRefs[i]->isByRef())
4465 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
4466 // Unique all "by ref" declarations.
4467 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4468 if (BlockDeclRefs[i]->isByRef()) {
4469 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
4470 }
4471 // Find any imported blocks...they will need special attention.
4472 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00004473 if (BlockDeclRefs[i]->isByRef() ||
4474 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4475 BlockDeclRefs[i]->getType()->isBlockPointerType()) {
Steve Naroff00072682008-11-13 17:40:07 +00004476 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff54055232008-10-27 17:20:55 +00004477 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4478 }
4479 }
4480}
4481
Steve Narofffa15fd92008-10-28 20:29:00 +00004482FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
4483 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor72564e72009-02-26 23:50:07 +00004484 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Mike Stump1eb44332009-09-09 15:08:12 +00004485 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00004486 ID, FType, 0, FunctionDecl::Extern, false,
Douglas Gregor2224f842009-02-25 16:33:18 +00004487 false);
Steve Narofffa15fd92008-10-28 20:29:00 +00004488}
4489
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004490Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004491 Blocks.push_back(Exp);
4492
4493 CollectBlockDeclRefInfo(Exp);
4494 std::string FuncName;
Mike Stump1eb44332009-09-09 15:08:12 +00004495
Steve Narofffa15fd92008-10-28 20:29:00 +00004496 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00004497 FuncName = CurFunctionDef->getNameAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00004498 else if (CurMethodDef) {
Chris Lattner077bf5e2008-11-24 03:33:13 +00004499 FuncName = CurMethodDef->getSelector().getAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00004500 // Convert colons to underscores.
4501 std::string::size_type loc = 0;
4502 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4503 FuncName.replace(loc, 1, "_");
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004504 } else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004505 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump1eb44332009-09-09 15:08:12 +00004506
Steve Narofffa15fd92008-10-28 20:29:00 +00004507 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump1eb44332009-09-09 15:08:12 +00004508
Steve Narofffa15fd92008-10-28 20:29:00 +00004509 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4510 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00004511
Steve Narofffa15fd92008-10-28 20:29:00 +00004512 // Get a pointer to the function type so we can cast appropriately.
4513 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
4514
4515 FunctionDecl *FD;
4516 Expr *NewRep;
Mike Stump1eb44332009-09-09 15:08:12 +00004517
Steve Narofffa15fd92008-10-28 20:29:00 +00004518 // Simulate a contructor call...
4519 FD = SynthBlockInitFunctionDecl(Tag.c_str());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004520 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00004521
Steve Narofffa15fd92008-10-28 20:29:00 +00004522 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00004523
Steve Narofffdc03722008-10-29 21:23:59 +00004524 // Initialize the block function.
Steve Narofffa15fd92008-10-28 20:29:00 +00004525 FD = SynthBlockInitFunctionDecl(Func.c_str());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004526 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
4527 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00004528 CastExpr *castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy,
4529 CastExpr::CK_Unknown, Arg,
Ted Kremenek8189cde2009-02-07 01:47:29 +00004530 Context->VoidPtrTy, SourceLocation(),
4531 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00004532 InitExprs.push_back(castExpr);
4533
Steve Naroff01aec112009-12-06 21:14:13 +00004534 // Initialize the block descriptor.
4535 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump1eb44332009-09-09 15:08:12 +00004536
Steve Naroff01aec112009-12-06 21:14:13 +00004537 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
4538 &Context->Idents.get(DescData.c_str()),
4539 Context->VoidPtrTy, 0,
4540 VarDecl::Static);
4541 UnaryOperator *DescRefExpr = new (Context) UnaryOperator(
4542 new (Context) DeclRefExpr(NewVD,
4543 Context->VoidPtrTy, SourceLocation()),
4544 UnaryOperator::AddrOf,
4545 Context->getPointerType(Context->VoidPtrTy),
4546 SourceLocation());
4547 InitExprs.push_back(DescRefExpr);
4548
Steve Narofffa15fd92008-10-28 20:29:00 +00004549 // Add initializers for any closure decl refs.
4550 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00004551 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00004552 // Output all "by copy" declarations.
Mike Stump1eb44332009-09-09 15:08:12 +00004553 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00004554 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004555 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00004556 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner8ec03f52008-11-24 03:54:41 +00004557 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004558 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004559 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004560 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004561 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00004562 Exp = new (Context) CStyleCastExpr(Context->VoidPtrTy,
4563 CastExpr::CK_Unknown, Arg,
4564 Context->VoidPtrTy,
Anders Carlssoncdef2b72009-07-31 00:48:10 +00004565 SourceLocation(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00004566 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004567 } else {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004568 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004569 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004570 }
Mike Stump1eb44332009-09-09 15:08:12 +00004571 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004572 }
4573 // Output all "by ref" declarations.
Mike Stump1eb44332009-09-09 15:08:12 +00004574 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00004575 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004576 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004577 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4578 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00004579 Context->getPointerType(Exp->getType()),
Steve Narofffdc03722008-10-29 21:23:59 +00004580 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00004581 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004582 }
4583 }
Fariborz Jahanianff127882009-12-23 21:52:32 +00004584 if (ImportedBlockDecls.size()) {
4585 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4586 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff01aec112009-12-06 21:14:13 +00004587 unsigned IntSize =
4588 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanianff127882009-12-23 21:52:32 +00004589 Expr *FlagExp = new (Context) IntegerLiteral(llvm::APInt(IntSize, flag),
4590 Context->IntTy, SourceLocation());
4591 InitExprs.push_back(FlagExp);
Steve Naroff01aec112009-12-06 21:14:13 +00004592 }
Ted Kremenek668bf912009-02-09 20:51:47 +00004593 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4594 FType, SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004595 NewRep = new (Context) UnaryOperator(NewRep, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00004596 Context->getPointerType(NewRep->getType()),
Steve Narofffa15fd92008-10-28 20:29:00 +00004597 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00004598 NewRep = new (Context) CStyleCastExpr(FType, CastExpr::CK_Unknown, NewRep,
Anders Carlssoncdef2b72009-07-31 00:48:10 +00004599 FType, SourceLocation(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00004600 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004601 BlockDeclRefs.clear();
4602 BlockByRefDecls.clear();
4603 BlockByCopyDecls.clear();
4604 ImportedBlockDecls.clear();
4605 return NewRep;
4606}
4607
4608//===----------------------------------------------------------------------===//
4609// Function Body / Expression rewriting
4610//===----------------------------------------------------------------------===//
4611
Steve Naroffc77a6362008-12-04 16:24:46 +00004612// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
4613// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
4614// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
4615// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
4616// Since the rewriter isn't capable of rewriting rewritten code, it's important
4617// we get this right.
4618void RewriteObjC::CollectPropertySetters(Stmt *S) {
4619 // Perform a bottom up traversal of all children.
4620 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4621 CI != E; ++CI)
4622 if (*CI)
4623 CollectPropertySetters(*CI);
4624
4625 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
4626 if (BinOp->isAssignmentOp()) {
4627 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
4628 PropSetters[PRE] = BinOp;
4629 }
4630 }
4631}
4632
Steve Narofffa15fd92008-10-28 20:29:00 +00004633Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump1eb44332009-09-09 15:08:12 +00004634 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00004635 isa<DoStmt>(S) || isa<ForStmt>(S))
4636 Stmts.push_back(S);
4637 else if (isa<ObjCForCollectionStmt>(S)) {
4638 Stmts.push_back(S);
Anders Carlssonfc4020a2009-12-22 06:13:42 +00004639 ++BcLabelCount;
4640 ObjCBcLabelNo.push_back(BcLabelCount);
Steve Narofffa15fd92008-10-28 20:29:00 +00004641 }
Mike Stump1eb44332009-09-09 15:08:12 +00004642
Steve Narofffa15fd92008-10-28 20:29:00 +00004643 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00004644
Steve Narofffa15fd92008-10-28 20:29:00 +00004645 // Perform a bottom up rewrite of all children.
4646 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4647 CI != E; ++CI)
4648 if (*CI) {
4649 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Mike Stump1eb44332009-09-09 15:08:12 +00004650 if (newStmt)
Steve Narofffa15fd92008-10-28 20:29:00 +00004651 *CI = newStmt;
4652 }
Mike Stump1eb44332009-09-09 15:08:12 +00004653
Steve Narofffa15fd92008-10-28 20:29:00 +00004654 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4655 // Rewrite the block body in place.
4656 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Mike Stump1eb44332009-09-09 15:08:12 +00004657
Steve Narofffa15fd92008-10-28 20:29:00 +00004658 // Now we snarf the rewritten text and stash it away for later use.
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004659 std::string Str = Rewrite.getRewritenText(BE->getSourceRange());
4660 RewrittenBlockExprs[BE] = Str;
Mike Stump1eb44332009-09-09 15:08:12 +00004661
Steve Narofffa15fd92008-10-28 20:29:00 +00004662 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
4663 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004664 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00004665 return blockTranscribed;
4666 }
4667 // Handle specific things.
4668 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4669 return RewriteAtEncode(AtEncode);
Mike Stump1eb44332009-09-09 15:08:12 +00004670
Steve Narofffa15fd92008-10-28 20:29:00 +00004671 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
4672 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
4673
Steve Naroffc77a6362008-12-04 16:24:46 +00004674 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
4675 BinaryOperator *BinOp = PropSetters[PropRefExpr];
4676 if (BinOp) {
4677 // Because the rewriter doesn't allow us to rewrite rewritten code,
4678 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroffb619d952008-12-09 12:56:34 +00004679 DisableReplaceStmt = true;
4680 // Save the source range. Even if we disable the replacement, the
4681 // rewritten node will have been inserted into the tree. If the synthesized
4682 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump1eb44332009-09-09 15:08:12 +00004683 // self.errorHandler = handler ? handler :
Steve Naroffb619d952008-12-09 12:56:34 +00004684 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
4685 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroffc77a6362008-12-04 16:24:46 +00004686 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroffb619d952008-12-09 12:56:34 +00004687 DisableReplaceStmt = false;
Steve Naroff4c3580e2008-12-04 23:50:32 +00004688 //
4689 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
4690 // we changed the RHS of BinOp, the rewriter would fail (since it needs
4691 // to see the original expression). Consider this example:
4692 //
4693 // Foo *obj1, *obj2;
4694 //
4695 // obj1.i = [obj2 rrrr];
4696 //
4697 // 'BinOp' for the previous expression looks like:
4698 //
4699 // (BinaryOperator 0x231ccf0 'int' '='
4700 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
4701 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
4702 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
4703 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
4704 //
4705 // 'newStmt' represents the rewritten message expression. For example:
4706 //
4707 // (CallExpr 0x231d300 'id':'struct objc_object *'
4708 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
4709 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
4710 // (CStyleCastExpr 0x231d220 'void *'
4711 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
4712 //
4713 // Note that 'newStmt' is passed to RewritePropertySetter so that it
4714 // can be used as the setter argument. ReplaceStmt() will still 'see'
4715 // the original RHS (since we haven't altered BinOp).
4716 //
Mike Stump1eb44332009-09-09 15:08:12 +00004717 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff4c3580e2008-12-04 23:50:32 +00004718 // node. As a result, we now leak the original AST nodes.
4719 //
Steve Naroffb619d952008-12-09 12:56:34 +00004720 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroffc77a6362008-12-04 16:24:46 +00004721 } else {
4722 return RewritePropertyGetter(PropRefExpr);
Steve Naroff15f081d2008-12-03 00:56:33 +00004723 }
4724 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004725 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4726 return RewriteAtSelector(AtSelector);
Mike Stump1eb44332009-09-09 15:08:12 +00004727
Steve Narofffa15fd92008-10-28 20:29:00 +00004728 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4729 return RewriteObjCStringLiteral(AtString);
Mike Stump1eb44332009-09-09 15:08:12 +00004730
Steve Narofffa15fd92008-10-28 20:29:00 +00004731 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00004732#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00004733 // Before we rewrite it, put the original message expression in a comment.
4734 SourceLocation startLoc = MessExpr->getLocStart();
4735 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00004736
Steve Narofffa15fd92008-10-28 20:29:00 +00004737 const char *startBuf = SM->getCharacterData(startLoc);
4738 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00004739
Steve Narofffa15fd92008-10-28 20:29:00 +00004740 std::string messString;
4741 messString += "// ";
4742 messString.append(startBuf, endBuf-startBuf+1);
4743 messString += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004744
4745 // FIXME: Missing definition of
Steve Narofffa15fd92008-10-28 20:29:00 +00004746 // InsertText(clang::SourceLocation, char const*, unsigned int).
4747 // InsertText(startLoc, messString.c_str(), messString.size());
4748 // Tried this, but it didn't work either...
4749 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00004750#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00004751 return RewriteMessageExpr(MessExpr);
4752 }
Mike Stump1eb44332009-09-09 15:08:12 +00004753
Steve Narofffa15fd92008-10-28 20:29:00 +00004754 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4755 return RewriteObjCTryStmt(StmtTry);
4756
4757 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4758 return RewriteObjCSynchronizedStmt(StmtTry);
4759
4760 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4761 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump1eb44332009-09-09 15:08:12 +00004762
Steve Narofffa15fd92008-10-28 20:29:00 +00004763 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4764 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump1eb44332009-09-09 15:08:12 +00004765
4766 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofffa15fd92008-10-28 20:29:00 +00004767 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump1eb44332009-09-09 15:08:12 +00004768 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofffa15fd92008-10-28 20:29:00 +00004769 OrigStmtRange.getEnd());
4770 if (BreakStmt *StmtBreakStmt =
4771 dyn_cast<BreakStmt>(S))
4772 return RewriteBreakStmt(StmtBreakStmt);
4773 if (ContinueStmt *StmtContinueStmt =
4774 dyn_cast<ContinueStmt>(S))
4775 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00004776
4777 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofffa15fd92008-10-28 20:29:00 +00004778 // and cast exprs.
4779 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4780 // FIXME: What we're doing here is modifying the type-specifier that
4781 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump1eb44332009-09-09 15:08:12 +00004782 // a separate type-specifier that we can rewrite.
Steve Naroff3d7e7862009-12-05 15:55:59 +00004783 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4784 // the context of an ObjCForCollectionStmt. For example:
4785 // NSArray *someArray;
4786 // for (id <FooProtocol> index in someArray) ;
4787 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4788 // and it depends on the original text locations/positions.
Benjamin Kramerb2041de2009-12-05 22:16:51 +00004789 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
Steve Naroff3d7e7862009-12-05 15:55:59 +00004790 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump1eb44332009-09-09 15:08:12 +00004791
Steve Narofffa15fd92008-10-28 20:29:00 +00004792 // Blocks rewrite rules.
4793 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4794 DI != DE; ++DI) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004795 Decl *SD = *DI;
Steve Narofffa15fd92008-10-28 20:29:00 +00004796 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004797 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004798 RewriteBlockPointerDecl(ND);
Mike Stump1eb44332009-09-09 15:08:12 +00004799 else if (ND->getType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00004800 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004801 if (VarDecl *VD = dyn_cast<VarDecl>(SD))
4802 if (VD->hasAttr<BlocksAttr>())
4803 RewriteByRefVar(VD);
Steve Narofffa15fd92008-10-28 20:29:00 +00004804 }
4805 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004806 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004807 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00004808 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00004809 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4810 }
4811 }
4812 }
Mike Stump1eb44332009-09-09 15:08:12 +00004813
Steve Narofffa15fd92008-10-28 20:29:00 +00004814 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4815 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump1eb44332009-09-09 15:08:12 +00004816
4817 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00004818 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4819 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump1eb44332009-09-09 15:08:12 +00004820 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4821 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004822 && "Statement stack mismatch");
4823 Stmts.pop_back();
4824 }
4825 // Handle blocks rewriting.
4826 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4827 if (BDRE->isByRef())
Steve Naroff621edce2009-04-29 16:37:50 +00004828 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofffa15fd92008-10-28 20:29:00 +00004829 }
4830 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004831 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004832 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004833 ReplaceStmt(S, BlockCall);
4834 return BlockCall;
4835 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004836 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00004837 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004838 RewriteCastExpr(CE);
4839 }
4840#if 0
4841 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00004842 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004843 // Get the new text.
4844 std::string SStr;
4845 llvm::raw_string_ostream Buf(SStr);
Eli Friedman3a9eb442009-05-30 05:19:26 +00004846 Replacement->printPretty(Buf, *Context);
Steve Narofffa15fd92008-10-28 20:29:00 +00004847 const std::string &Str = Buf.str();
4848
4849 printf("CAST = %s\n", &Str[0]);
4850 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4851 delete S;
4852 return Replacement;
4853 }
4854#endif
4855 // Return this stmt unmodified.
4856 return S;
4857}
4858
Steve Naroff3d7e7862009-12-05 15:55:59 +00004859void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
4860 for (RecordDecl::field_iterator i = RD->field_begin(),
4861 e = RD->field_end(); i != e; ++i) {
4862 FieldDecl *FD = *i;
4863 if (isTopLevelBlockPointerType(FD->getType()))
4864 RewriteBlockPointerDecl(FD);
4865 if (FD->getType()->isObjCQualifiedIdType() ||
4866 FD->getType()->isObjCQualifiedInterfaceType())
4867 RewriteObjCQualifiedInterfaceTypes(FD);
4868 }
4869}
4870
Steve Narofffa15fd92008-10-28 20:29:00 +00004871/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4872/// main file of the input.
4873void RewriteObjC::HandleDeclInMainFile(Decl *D) {
4874 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffcb735302008-12-17 00:20:22 +00004875 if (FD->isOverloadedOperator())
4876 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004877
Steve Narofffa15fd92008-10-28 20:29:00 +00004878 // Since function prototypes don't have ParmDecl's, we check the function
4879 // prototype. This enables us to rewrite function declarations and
4880 // definitions using the same code.
Douglas Gregor72564e72009-02-26 23:50:07 +00004881 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofffa15fd92008-10-28 20:29:00 +00004882
Sebastian Redld3a413d2009-04-26 20:35:05 +00004883 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00004884 if (CompoundStmt *Body = FD->getCompoundBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004885 CurFunctionDef = FD;
Steve Naroffc77a6362008-12-04 16:24:46 +00004886 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00004887 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00004888 Body =
4889 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4890 FD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00004891 CurrentBody = 0;
4892 if (PropParentMap) {
4893 delete PropParentMap;
4894 PropParentMap = 0;
4895 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004896 // This synthesizes and inserts the block "impl" struct, invoke function,
4897 // and any copy/dispose helper functions.
4898 InsertBlockLiteralsWithinFunction(FD);
4899 CurFunctionDef = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004900 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004901 return;
4902 }
4903 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00004904 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004905 CurMethodDef = MD;
Steve Naroffc77a6362008-12-04 16:24:46 +00004906 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00004907 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00004908 Body =
4909 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4910 MD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00004911 CurrentBody = 0;
4912 if (PropParentMap) {
4913 delete PropParentMap;
4914 PropParentMap = 0;
4915 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004916 InsertBlockLiteralsWithinMethod(MD);
4917 CurMethodDef = 0;
4918 }
4919 }
4920 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
4921 ClassImplementation.push_back(CI);
4922 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
4923 CategoryImplementation.push_back(CI);
4924 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
4925 RewriteForwardClassDecl(CD);
4926 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4927 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004928 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004929 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004930 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004931 CheckFunctionPointerDecl(VD->getType(), VD);
4932 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00004933 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004934 RewriteCastExpr(CE);
4935 }
4936 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00004937 } else if (VD->getType()->isRecordType()) {
4938 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
4939 if (RD->isDefinition())
4940 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00004941 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004942 if (VD->getInit()) {
4943 GlobalVarDecl = VD;
Steve Naroffc77a6362008-12-04 16:24:46 +00004944 CollectPropertySetters(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00004945 CurrentBody = VD->getInit();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004946 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00004947 CurrentBody = 0;
4948 if (PropParentMap) {
4949 delete PropParentMap;
4950 PropParentMap = 0;
4951 }
Mike Stump1eb44332009-09-09 15:08:12 +00004952 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00004953 VD->getNameAsCString());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004954 GlobalVarDecl = 0;
4955
4956 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00004957 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004958 RewriteCastExpr(CE);
4959 }
4960 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004961 return;
4962 }
4963 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004964 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004965 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00004966 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00004967 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
Steve Naroff3d7e7862009-12-05 15:55:59 +00004968 else if (TD->getUnderlyingType()->isRecordType()) {
4969 RecordDecl *RD = TD->getUnderlyingType()->getAs<RecordType>()->getDecl();
4970 if (RD->isDefinition())
4971 RewriteRecordBody(RD);
4972 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004973 return;
4974 }
4975 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroff3d7e7862009-12-05 15:55:59 +00004976 if (RD->isDefinition())
4977 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00004978 return;
4979 }
4980 // Nothing yet.
4981}
4982
Chris Lattnerdacbc5d2009-03-28 04:11:33 +00004983void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004984 // Get the top-level buffer that this corresponds to.
Mike Stump1eb44332009-09-09 15:08:12 +00004985
Steve Narofffa15fd92008-10-28 20:29:00 +00004986 // Rewrite tabs if we care.
4987 //RewriteTabs();
Mike Stump1eb44332009-09-09 15:08:12 +00004988
Steve Narofffa15fd92008-10-28 20:29:00 +00004989 if (Diags.hasErrorOccurred())
4990 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004991
Steve Narofffa15fd92008-10-28 20:29:00 +00004992 RewriteInclude();
Mike Stump1eb44332009-09-09 15:08:12 +00004993
Steve Naroff621edce2009-04-29 16:37:50 +00004994 // Here's a great place to add any extra declarations that may be needed.
4995 // Write out meta data for each @protocol(<expr>).
Mike Stump1eb44332009-09-09 15:08:12 +00004996 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00004997 E = ProtocolExprDecls.end(); I != E; ++I)
4998 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
4999
Mike Stump1eb44332009-09-09 15:08:12 +00005000 InsertText(SM->getLocForStartOfFile(MainFileID),
Steve Narofffa15fd92008-10-28 20:29:00 +00005001 Preamble.c_str(), Preamble.size(), false);
Steve Naroff0aab7962008-11-14 14:10:01 +00005002 if (ClassImplementation.size() || CategoryImplementation.size())
5003 RewriteImplementations();
Steve Naroff621edce2009-04-29 16:37:50 +00005004
Steve Narofffa15fd92008-10-28 20:29:00 +00005005 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5006 // we are done.
Mike Stump1eb44332009-09-09 15:08:12 +00005007 if (const RewriteBuffer *RewriteBuf =
Steve Narofffa15fd92008-10-28 20:29:00 +00005008 Rewrite.getRewriteBufferFor(MainFileID)) {
5009 //printf("Changed:\n");
5010 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5011 } else {
5012 fprintf(stderr, "No changes\n");
5013 }
Steve Narofface66252008-11-13 20:07:04 +00005014
Steve Naroff621edce2009-04-29 16:37:50 +00005015 if (ClassImplementation.size() || CategoryImplementation.size() ||
5016 ProtocolExprDecls.size()) {
Steve Naroff0aab7962008-11-14 14:10:01 +00005017 // Rewrite Objective-c meta data*
5018 std::string ResultStr;
5019 SynthesizeMetaDataIntoBuffer(ResultStr);
5020 // Emit metadata.
5021 *OutFile << ResultStr;
5022 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005023 OutFile->flush();
5024}
5025