blob: aa898a8fe6be1fd1a7a534172a145d3dce6facba [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
14#include "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"
Ted Kremeneke3a61982008-05-31 20:11:04 +000018#include "clang/AST/TranslationUnit.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"
Chris Lattner158ecb92007-10-25 17:07:24 +000023#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000024#include "llvm/ADT/SmallPtrSet.h"
Ted Kremeneka95d3752008-09-13 05:16:45 +000025#include "llvm/ADT/OwningPtr.h"
Chris Lattner26de4652007-12-02 01:13:47 +000026#include "llvm/Support/MemoryBuffer.h"
Steve Naroff0113c9d2008-01-28 21:34:52 +000027#include "llvm/Support/CommandLine.h"
Dan Gohman63e2dcc2008-05-21 20:19:16 +000028#include "llvm/Support/Streams.h"
Ted Kremeneka95d3752008-09-13 05:16:45 +000029#include "llvm/Support/raw_ostream.h"
Chris Lattnerc68ab772008-03-22 00:08:40 +000030#include "llvm/System/Path.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000031using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000032using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000033
Steve Naroff0113c9d2008-01-28 21:34:52 +000034static llvm::cl::opt<bool>
35SilenceRewriteMacroWarning("Wno-rewrite-macros", llvm::cl::init(false),
36 llvm::cl::desc("Silence ObjC rewriting warnings"));
37
Chris Lattner77cd2a02007-10-11 00:43:27 +000038namespace {
Steve Naroffb29b4272008-04-14 22:03:09 +000039 class RewriteObjC : public ASTConsumer {
Chris Lattner2c64b7b2007-10-16 21:07:07 +000040 Rewriter Rewrite;
Chris Lattnere365c502007-11-30 22:25:36 +000041 Diagnostic &Diags;
Steve Naroff4f943c22008-03-10 20:43:59 +000042 const LangOptions &LangOpts;
Steve Narofff69cc5d2008-01-30 19:17:43 +000043 unsigned RewriteFailedDiag;
44
Chris Lattner01c57482007-10-17 22:35:30 +000045 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000046 SourceManager *SM;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000047 TranslationUnitDecl *TUDecl;
Chris Lattner8a12c272007-10-11 18:38:32 +000048 unsigned MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000049 const char *MainFileStart, *MainFileEnd;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000050 SourceLocation LastIncLoc;
Steve Naroffba92b2e2008-03-27 22:29:16 +000051
Ted Kremeneka526c5c2008-01-07 19:49:32 +000052 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
53 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
54 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Narofffbfe8252008-05-06 18:26:51 +000055 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000056 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
57 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000058 llvm::SmallVector<Stmt *, 32> Stmts;
59 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroffebf2b562007-10-23 23:50:29 +000060
Steve Naroffd82a9ab2008-03-15 00:55:56 +000061 unsigned NumObjCStringLiterals;
62
Steve Naroffebf2b562007-10-23 23:50:29 +000063 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000064 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000065 FunctionDecl *MsgSendStretFunctionDecl;
66 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000067 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000068 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000069 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000070 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000071 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +000072 FunctionDecl *GetProtocolFunctionDecl;
Steve Naroffc0a123c2008-03-11 17:37:02 +000073 FunctionDecl *SuperContructorFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000074
Steve Naroffbeaf2992007-11-03 11:27:19 +000075 // ObjC string constant support.
Steve Naroff248a7532008-04-15 22:42:06 +000076 VarDecl *ConstantStringClassReference;
Steve Naroffbeaf2992007-11-03 11:27:19 +000077 RecordDecl *NSStringRecord;
Steve Naroffab972d32007-11-04 22:37:50 +000078
Fariborz Jahanianb586cce2008-01-16 00:09:11 +000079 // ObjC foreach break/continue generation support.
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000080 int BcLabelCount;
81
Steve Naroff874e2322007-11-15 10:28:18 +000082 // Needed for super.
Steve Naroff54055232008-10-27 17:20:55 +000083 ObjCMethodDecl *CurMethodDef;
Steve Naroff874e2322007-11-15 10:28:18 +000084 RecordDecl *SuperStructDecl;
Steve Naroffd82a9ab2008-03-15 00:55:56 +000085 RecordDecl *ConstantStringDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000086
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +000087 // Needed for header files being rewritten
88 bool IsHeader;
89
Steve Naroffa7b402d2008-03-28 22:26:09 +000090 std::string InFileName;
91 std::string OutFileName;
92
Steve Naroffba92b2e2008-03-27 22:29:16 +000093 std::string Preamble;
Steve Naroff54055232008-10-27 17:20:55 +000094
95 // Block expressions.
96 llvm::SmallVector<BlockExpr *, 32> Blocks;
97 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
98 llvm::DenseMap<BlockDeclRefExpr *, CallExpr *> BlockCallExprs;
Steve Naroffba92b2e2008-03-27 22:29:16 +000099
Steve Naroff54055232008-10-27 17:20:55 +0000100 // Block related declarations.
101 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDecls;
102 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDecls;
103 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
104
105 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
106
107 FunctionDecl *CurFunctionDef;
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000108 VarDecl *GlobalVarDecl;
109
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000110 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +0000111 public:
Ted Kremeneke3a61982008-05-31 20:11:04 +0000112 virtual void Initialize(ASTContext &context);
113
114 virtual void InitializeTU(TranslationUnit &TU) {
115 TU.SetOwnsDecls(false);
116 Initialize(TU.getContext());
117 }
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000118
Chris Lattner8a12c272007-10-11 18:38:32 +0000119
Chris Lattnerf04da132007-10-24 17:06:59 +0000120 // Top Level Driver code.
121 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000122 void HandleDeclInMainFile(Decl *D);
Steve Naroffb29b4272008-04-14 22:03:09 +0000123 RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000124 Diagnostic &D, const LangOptions &LOpts);
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000125
126 ~RewriteObjC() {}
127
128 virtual void HandleTranslationUnit(TranslationUnit& TU);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000129
130 void ReplaceStmt(Stmt *Old, Stmt *New) {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000131 // If replacement succeeded or warning disabled return with no warning.
132 if (!Rewrite.ReplaceStmt(Old, New) || SilenceRewriteMacroWarning)
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000133 return;
134
Chris Lattner0a14eee2008-11-18 07:04:44 +0000135 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
136 << Old->getSourceRange();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000137 }
138
Steve Naroffba92b2e2008-03-27 22:29:16 +0000139 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
140 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000141 // If insertion succeeded or warning disabled return with no warning.
Steve Naroffba92b2e2008-03-27 22:29:16 +0000142 if (!Rewrite.InsertText(Loc, StrData, StrLen, InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000143 SilenceRewriteMacroWarning)
144 return;
145
146 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
147 }
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000148
Chris Lattneraadaf782008-01-31 19:51:04 +0000149 void RemoveText(SourceLocation Loc, unsigned StrLen) {
150 // If removal succeeded or warning disabled return with no warning.
151 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
152 return;
153
154 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
155 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000156
Chris Lattneraadaf782008-01-31 19:51:04 +0000157 void ReplaceText(SourceLocation Start, unsigned OrigLength,
158 const char *NewStr, unsigned NewLength) {
159 // If removal succeeded or warning disabled return with no warning.
160 if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength) ||
161 SilenceRewriteMacroWarning)
162 return;
163
164 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
165 }
166
Chris Lattnerf04da132007-10-24 17:06:59 +0000167 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000168 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000169 void RewriteInclude();
Chris Lattnerf04da132007-10-24 17:06:59 +0000170 void RewriteTabs();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000171 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffa0876e82008-12-02 17:36:43 +0000172 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
173 ObjCImplementationDecl *IMD,
174 ObjCCategoryImplDecl *CID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000175 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000176 void RewriteImplementationDecl(NamedDecl *Dcl);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000177 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
178 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
179 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
180 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
181 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Chris Lattner55d13b42008-03-16 21:23:50 +0000182 void RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +0000183 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000184 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroff4f95b752008-07-29 18:15:38 +0000185 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffd5255f52007-11-01 13:24:47 +0000186 bool needToScanForQualifiers(QualType T);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000187 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000188 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000189 QualType getConstantStringStructType();
Steve Naroffbaf58c32008-05-31 14:15:04 +0000190 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Chris Lattner311ff022007-10-16 22:36:42 +0000191
Chris Lattnerf04da132007-10-24 17:06:59 +0000192 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000193 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000194 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000195 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart);
Steve Naroffb42f8412007-11-05 14:50:49 +0000196 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000197 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000198 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000199 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000200 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000201 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000202 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
203 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
204 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000205 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
206 SourceLocation OrigEnd);
Steve Naroff934f2762007-10-24 22:48:43 +0000207 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
208 Expr **args, unsigned nargs);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000209 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000210 Stmt *RewriteBreakStmt(BreakStmt *S);
211 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000212 void SynthCountByEnumWithState(std::string &buf);
213
Steve Naroff09b266e2007-10-30 23:14:51 +0000214 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000215 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000216 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000217 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000218 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000219 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000220 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000221 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000222 void SynthGetProtocolFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000223 void SynthSuperContructorFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000224
Chris Lattnerf04da132007-10-24 17:06:59 +0000225 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000226 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000227 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000228
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000229 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000230 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000231
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000232 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
233 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000234 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000235 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000236 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000237 const char *ClassName,
238 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000239
Chris Lattner780f3292008-07-21 21:32:27 +0000240 void RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl>
241 &Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000242 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000243 const char *ClassName,
244 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000245 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000246 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000247 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
248 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000249 std::string &Result);
Steve Narofface66252008-11-13 20:07:04 +0000250 void RewriteImplementations();
251 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Steve Naroff54055232008-10-27 17:20:55 +0000252
253 // Block rewriting.
254 void RewriteBlocksInFunctionTypeProto(QualType funcType, NamedDecl *D);
255 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
256
257 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
258 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
259
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000260 // Block specific rewrite rules.
Steve Naroff54055232008-10-27 17:20:55 +0000261 void RewriteBlockCall(CallExpr *Exp);
262 void RewriteBlockPointerDecl(NamedDecl *VD);
263 void RewriteBlockDeclRefExpr(BlockDeclRefExpr *VD);
264 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
265
266 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
267 const char *funcName, std::string Tag);
268 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
269 const char *funcName, std::string Tag);
270 std::string SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
271 bool hasCopyDisposeHelpers);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +0000272 Stmt *SynthesizeBlockCall(CallExpr *Exp);
Steve Naroff54055232008-10-27 17:20:55 +0000273 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
274 const char *FunName);
275
276 void CollectBlockDeclRefInfo(BlockExpr *Exp);
277 void GetBlockCallExprs(Stmt *S);
278 void GetBlockDeclRefExprs(Stmt *S);
279
280 // We avoid calling Type::isBlockPointerType(), since it operates on the
281 // canonical type. We only care if the top-level type is a closure pointer.
282 bool isBlockPointerType(QualType T) { return isa<BlockPointerType>(T); }
283
284 // FIXME: This predicate seems like it would be useful to add to ASTContext.
285 bool isObjCType(QualType T) {
286 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
287 return false;
288
289 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
290
291 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
292 OCT == Context->getCanonicalType(Context->getObjCClassType()))
293 return true;
294
295 if (const PointerType *PT = OCT->getAsPointerType()) {
296 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
297 isa<ObjCQualifiedIdType>(PT->getPointeeType()))
298 return true;
299 }
300 return false;
301 }
302 bool PointerTypeTakesAnyBlockArguments(QualType QT);
303 void GetExtentOfArgList(const char *Name, const char *&LParen, const char *&RParen);
Steve Naroffb2f9e512008-11-03 23:29:32 +0000304 void RewriteCastExpr(CStyleCastExpr *CE);
Steve Narofffa15fd92008-10-28 20:29:00 +0000305
306 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000307 Stmt *SynthBlockInitExpr(BlockExpr *Exp);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000308 };
309}
310
Steve Naroff54055232008-10-27 17:20:55 +0000311void RewriteObjC::RewriteBlocksInFunctionTypeProto(QualType funcType,
312 NamedDecl *D) {
313 if (FunctionTypeProto *fproto = dyn_cast<FunctionTypeProto>(funcType)) {
314 for (FunctionTypeProto::arg_type_iterator I = fproto->arg_type_begin(),
315 E = fproto->arg_type_end(); I && (I != E); ++I)
316 if (isBlockPointerType(*I)) {
317 // All the args are checked/rewritten. Don't call twice!
318 RewriteBlockPointerDecl(D);
319 break;
320 }
321 }
322}
323
324void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
325 const PointerType *PT = funcType->getAsPointerType();
326 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
327 RewriteBlocksInFunctionTypeProto(PT->getPointeeType(), ND);
328}
329
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000330static bool IsHeaderFile(const std::string &Filename) {
331 std::string::size_type DotPos = Filename.rfind('.');
332
333 if (DotPos == std::string::npos) {
334 // no file extension
335 return false;
336 }
337
338 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
339 // C header: .h
340 // C++ header: .hh or .H;
341 return Ext == "h" || Ext == "hh" || Ext == "H";
342}
343
Steve Naroffb29b4272008-04-14 22:03:09 +0000344RewriteObjC::RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000345 Diagnostic &D, const LangOptions &LOpts)
346 : Diags(D), LangOpts(LOpts) {
347 IsHeader = IsHeaderFile(inFile);
348 InFileName = inFile;
349 OutFileName = outFile;
350 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
351 "rewriting sub-expression within a macro (may not be correct)");
352}
353
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000354ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
Chris Lattnerc68ab772008-03-22 00:08:40 +0000355 const std::string& OutFile,
Steve Naroff4f943c22008-03-10 20:43:59 +0000356 Diagnostic &Diags,
357 const LangOptions &LOpts) {
Steve Naroffb29b4272008-04-14 22:03:09 +0000358 return new RewriteObjC(InFile, OutFile, Diags, LOpts);
Chris Lattnere365c502007-11-30 22:25:36 +0000359}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000360
Steve Naroffb29b4272008-04-14 22:03:09 +0000361void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000362 Context = &context;
363 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000364 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000365 MsgSendFunctionDecl = 0;
366 MsgSendSuperFunctionDecl = 0;
367 MsgSendStretFunctionDecl = 0;
368 MsgSendSuperStretFunctionDecl = 0;
369 MsgSendFpretFunctionDecl = 0;
370 GetClassFunctionDecl = 0;
371 GetMetaClassFunctionDecl = 0;
372 SelGetUidFunctionDecl = 0;
373 CFStringFunctionDecl = 0;
374 GetProtocolFunctionDecl = 0;
375 ConstantStringClassReference = 0;
376 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000377 CurMethodDef = 0;
378 CurFunctionDef = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000379 SuperStructDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000380 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000381 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000382 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000383 NumObjCStringLiterals = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000384
385 // Get the ID and start/end of the main file.
386 MainFileID = SM->getMainFileID();
387 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
388 MainFileStart = MainBuf->getBufferStart();
389 MainFileEnd = MainBuf->getBufferEnd();
Steve Naroffba92b2e2008-03-27 22:29:16 +0000390
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000391 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000392
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000393 // declaring objc_selector outside the parameter list removes a silly
394 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000395 if (IsHeader)
396 Preamble = "#pragma once\n";
397 Preamble += "struct objc_selector; struct objc_class;\n";
398 Preamble += "#ifndef OBJC_SUPER\n";
399 Preamble += "struct objc_super { struct objc_object *object; ";
400 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000401 if (LangOpts.Microsoft) {
402 // Add a constructor for creating temporary objects.
Steve Naroffba92b2e2008-03-27 22:29:16 +0000403 Preamble += "objc_super(struct objc_object *o, struct objc_object *s) : ";
404 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000405 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000406 Preamble += "};\n";
407 Preamble += "#define OBJC_SUPER\n";
408 Preamble += "#endif\n";
409 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
410 Preamble += "typedef struct objc_object Protocol;\n";
411 Preamble += "#define _REWRITER_typedef_Protocol\n";
412 Preamble += "#endif\n";
Steve Naroff3c64d9e2008-03-12 13:19:12 +0000413 if (LangOpts.Microsoft)
Steve Naroff69c827f2008-05-06 22:45:19 +0000414 Preamble += "#define __OBJC_RW_EXTERN extern \"C\" __declspec(dllimport)\n";
415 else
416 Preamble += "#define __OBJC_RW_EXTERN extern\n";
417 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000418 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000419 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000420 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000421 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000422 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000423 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000424 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff1284db82008-05-08 22:02:18 +0000425 Preamble += "__OBJC_RW_EXTERN double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000426 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff0757612008-05-08 17:52:16 +0000427 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000428 Preamble += "(const char *);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000429 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000430 Preamble += "(const char *);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000431 Preamble += "__OBJC_RW_EXTERN void objc_exception_throw(struct objc_object *);\n";
432 Preamble += "__OBJC_RW_EXTERN void objc_exception_try_enter(void *);\n";
433 Preamble += "__OBJC_RW_EXTERN void objc_exception_try_exit(void *);\n";
434 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_exception_extract(void *);\n";
435 Preamble += "__OBJC_RW_EXTERN int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000436 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000437 // @synchronized hooks.
438 Preamble += "__OBJC_RW_EXTERN void objc_sync_enter(struct objc_object *);\n";
439 Preamble += "__OBJC_RW_EXTERN void objc_sync_exit(struct objc_object *);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000440 Preamble += "__OBJC_RW_EXTERN Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000441 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
442 Preamble += "struct __objcFastEnumerationState {\n\t";
443 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000444 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000445 Preamble += "unsigned long *mutationsPtr;\n\t";
446 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff73ebd6d2008-06-02 20:23:21 +0000447 Preamble += "__OBJC_RW_EXTERN void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000448 Preamble += "#define __FASTENUMERATIONSTATE\n";
449 Preamble += "#endif\n";
450 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
451 Preamble += "struct __NSConstantStringImpl {\n";
452 Preamble += " int *isa;\n";
453 Preamble += " int flags;\n";
454 Preamble += " char *str;\n";
455 Preamble += " long length;\n";
456 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000457 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
458 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
459 Preamble += "#else\n";
Steve Naroff73b17cd2008-05-15 21:12:10 +0000460 Preamble += "__OBJC_RW_EXTERN int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000461 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000462 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
463 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000464 // Blocks preamble.
465 Preamble += "#ifndef BLOCK_IMPL\n";
466 Preamble += "#define BLOCK_IMPL\n";
467 Preamble += "struct __block_impl {\n";
468 Preamble += " void *isa;\n";
469 Preamble += " int Flags;\n";
470 Preamble += " int Size;\n";
471 Preamble += " void *FuncPtr;\n";
472 Preamble += "};\n";
473 Preamble += "enum {\n";
474 Preamble += " BLOCK_HAS_COPY_DISPOSE = (1<<25),\n";
475 Preamble += " BLOCK_IS_GLOBAL = (1<<28)\n";
476 Preamble += "};\n";
Steve Naroff54055232008-10-27 17:20:55 +0000477 Preamble += "// Runtime copy/destroy helper functions\n";
478 Preamble += "__OBJC_RW_EXTERN void _Block_copy_assign(void *, void *);\n";
479 Preamble += "__OBJC_RW_EXTERN void _Block_byref_assign_copy(void *, void *);\n";
480 Preamble += "__OBJC_RW_EXTERN void _Block_destroy(void *);\n";
481 Preamble += "__OBJC_RW_EXTERN void _Block_byref_release(void *);\n";
482 Preamble += "__OBJC_RW_EXTERN void *_NSConcreteGlobalBlock;\n";
483 Preamble += "__OBJC_RW_EXTERN void *_NSConcreteStackBlock;\n";
484 Preamble += "#endif\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000485 if (LangOpts.Microsoft) {
486 Preamble += "#undef __OBJC_RW_EXTERN\n";
487 Preamble += "#define __attribute__(X)\n";
488 }
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000489}
490
491
Chris Lattnerf04da132007-10-24 17:06:59 +0000492//===----------------------------------------------------------------------===//
493// Top Level Driver Code
494//===----------------------------------------------------------------------===//
495
Steve Naroffb29b4272008-04-14 22:03:09 +0000496void RewriteObjC::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000497 // Two cases: either the decl could be in the main file, or it could be in a
498 // #included file. If the former, rewrite it now. If the later, check to see
499 // if we rewrote the #include/#import.
500 SourceLocation Loc = D->getLocation();
501 Loc = SM->getLogicalLoc(Loc);
502
503 // If this is for a builtin, ignore it.
504 if (Loc.isInvalid()) return;
505
Steve Naroffebf2b562007-10-23 23:50:29 +0000506 // Look for built-in declarations that we need to refer during the rewrite.
507 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000508 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000509 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000510 // declared in <Foundation/NSString.h>
Chris Lattner8ec03f52008-11-24 03:54:41 +0000511 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000512 ConstantStringClassReference = FVD;
513 return;
514 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000515 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000516 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000517 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000518 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000519 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000520 RewriteProtocolDecl(PD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000521 } else if (ObjCForwardProtocolDecl *FP =
522 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000523 RewriteForwardProtocolDecl(FP);
Steve Naroffebf2b562007-10-23 23:50:29 +0000524 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000525 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000526 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000527 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000528}
529
Chris Lattnerf04da132007-10-24 17:06:59 +0000530//===----------------------------------------------------------------------===//
531// Syntactic (non-AST) Rewriting Code
532//===----------------------------------------------------------------------===//
533
Steve Naroffb29b4272008-04-14 22:03:09 +0000534void RewriteObjC::RewriteInclude() {
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000535 SourceLocation LocStart = SourceLocation::getFileLoc(MainFileID, 0);
536 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
537 const char *MainBufStart = MainBuf.first;
538 const char *MainBufEnd = MainBuf.second;
539 size_t ImportLen = strlen("import");
540 size_t IncludeLen = strlen("include");
541
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000542 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000543 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
544 if (*BufPtr == '#') {
545 if (++BufPtr == MainBufEnd)
546 return;
547 while (*BufPtr == ' ' || *BufPtr == '\t')
548 if (++BufPtr == MainBufEnd)
549 return;
550 if (!strncmp(BufPtr, "import", ImportLen)) {
551 // replace import with include
552 SourceLocation ImportLoc =
553 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattneraadaf782008-01-31 19:51:04 +0000554 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000555 BufPtr += ImportLen;
556 }
557 }
558 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000559}
560
Steve Naroffb29b4272008-04-14 22:03:09 +0000561void RewriteObjC::RewriteTabs() {
Chris Lattnerf04da132007-10-24 17:06:59 +0000562 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
563 const char *MainBufStart = MainBuf.first;
564 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000565
Chris Lattnerf04da132007-10-24 17:06:59 +0000566 // Loop over the whole file, looking for tabs.
567 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
568 if (*BufPtr != '\t')
569 continue;
570
571 // Okay, we found a tab. This tab will turn into at least one character,
572 // but it depends on which 'virtual column' it is in. Compute that now.
573 unsigned VCol = 0;
574 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
575 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
576 ++VCol;
577
578 // Okay, now that we know the virtual column, we know how many spaces to
579 // insert. We assume 8-character tab-stops.
580 unsigned Spaces = 8-(VCol & 7);
581
582 // Get the location of the tab.
583 SourceLocation TabLoc =
584 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
585
586 // Rewrite the single tab character into a sequence of spaces.
Chris Lattneraadaf782008-01-31 19:51:04 +0000587 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerf04da132007-10-24 17:06:59 +0000588 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000589}
590
Steve Naroffeb0646c2008-12-02 15:48:25 +0000591static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
592 ObjCIvarDecl *OID) {
593 std::string S;
594 S = "((struct ";
595 S += ClassDecl->getIdentifier()->getName();
596 S += "_IMPL *)self)->";
597 S += OID->getNameAsCString();
598 return S;
599}
600
Steve Naroffa0876e82008-12-02 17:36:43 +0000601void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
602 ObjCImplementationDecl *IMD,
603 ObjCCategoryImplDecl *CID) {
Steve Naroffd40910b2008-12-01 20:33:01 +0000604 SourceLocation startLoc = PID->getLocStart();
605 InsertText(startLoc, "// ", 3);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000606 const char *startBuf = SM->getCharacterData(startLoc);
607 assert((*startBuf == '@') && "bogus @synthesize location");
608 const char *semiBuf = strchr(startBuf, ';');
609 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
610 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
611
612 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
613 return; // FIXME: is this correct?
614
615 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000616 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000617 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000618 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000619
620 if (!OID)
621 return;
622
623 std::string Getr;
624 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
625 Getr += "{ ";
626 // Synthesize an explicit cast to gain access to the ivar.
627 Getr += "return " + getIvarAccessString(ClassDecl, OID);
628 Getr += "; }";
Steve Naroffeb0646c2008-12-02 15:48:25 +0000629 InsertText(onePastSemiLoc, Getr.c_str(), Getr.size());
Steve Naroffa0876e82008-12-02 17:36:43 +0000630
631 // Add the rewritten getter to trigger meta data generation. An alternate, and
632 // possibly cleaner approach is to hack RewriteObjCMethodsMetaData() to deal
633 // with properties explicitly. The following addInstanceMethod() required far
634 // less code change (and actually models what the rewriter is doing).
635 if (IMD)
636 IMD->addInstanceMethod(PD->getGetterMethodDecl());
637 else
638 CID->addInstanceMethod(PD->getGetterMethodDecl());
Steve Naroffeb0646c2008-12-02 15:48:25 +0000639
640 if (PD->isReadOnly())
641 return;
642
643 // Generate the 'setter' function.
644 std::string Setr;
645 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000646 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000647 // Synthesize an explicit cast to initialize the ivar.
648 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
649 Setr += OID->getNameAsCString();
650 Setr += "; }";
Steve Naroffeb0646c2008-12-02 15:48:25 +0000651 InsertText(onePastSemiLoc, Setr.c_str(), Setr.size());
Steve Naroffa0876e82008-12-02 17:36:43 +0000652
653 // Add the rewritten setter to trigger meta data generation.
654 if (IMD)
655 IMD->addInstanceMethod(PD->getSetterMethodDecl());
656 else
657 CID->addInstanceMethod(PD->getSetterMethodDecl());
Steve Naroffd40910b2008-12-01 20:33:01 +0000658}
Chris Lattner8a12c272007-10-11 18:38:32 +0000659
Steve Naroffb29b4272008-04-14 22:03:09 +0000660void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000661 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000662 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerf04da132007-10-24 17:06:59 +0000663
664 // Get the start location and compute the semi location.
665 SourceLocation startLoc = ClassDecl->getLocation();
666 const char *startBuf = SM->getCharacterData(startLoc);
667 const char *semiPtr = strchr(startBuf, ';');
668
669 // Translate to typedef's that forward reference structs with the same name
670 // as the class. As a convenience, we include the original declaration
671 // as a comment.
672 std::string typedefString;
673 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000674 typedefString.append(startBuf, semiPtr-startBuf+1);
675 typedefString += "\n";
676 for (int i = 0; i < numDecls; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000677 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000678 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000679 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000680 typedefString += "\n";
681 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000682 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000683 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000684 typedefString += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000685 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000686 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000687 }
688
689 // Replace the @class with typedefs corresponding to the classes.
Chris Lattneraadaf782008-01-31 19:51:04 +0000690 ReplaceText(startLoc, semiPtr-startBuf+1,
691 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000692}
693
Steve Naroffb29b4272008-04-14 22:03:09 +0000694void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000695 SourceLocation LocStart = Method->getLocStart();
696 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000697
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000698 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
Steve Naroff94ac21e2008-10-21 13:37:27 +0000699 InsertText(LocStart, "#if 0\n", 6);
700 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000701 } else {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000702 InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000703 }
704}
705
Steve Naroffb29b4272008-04-14 22:03:09 +0000706void RewriteObjC::RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000707{
Chris Lattner55d13b42008-03-16 21:23:50 +0000708 for (unsigned i = 0; i < nProperties; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000709 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000710 SourceLocation Loc = Property->getLocation();
711
Chris Lattneraadaf782008-01-31 19:51:04 +0000712 ReplaceText(Loc, 0, "// ", 3);
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000713
714 // FIXME: handle properties that are declared across multiple lines.
715 }
716}
717
Steve Naroffb29b4272008-04-14 22:03:09 +0000718void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000719 SourceLocation LocStart = CatDecl->getLocStart();
720
721 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000722 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000723
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000724 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000725 E = CatDecl->instmeth_end(); I != E; ++I)
726 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000727 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000728 E = CatDecl->classmeth_end(); I != E; ++I)
729 RewriteMethodDeclaration(*I);
730
Steve Naroff423cb562007-10-30 13:30:57 +0000731 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000732 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000733}
734
Steve Naroffb29b4272008-04-14 22:03:09 +0000735void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000736 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000737
Steve Naroff752d6ef2007-10-30 16:42:30 +0000738 SourceLocation LocStart = PDecl->getLocStart();
739
740 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000741 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000742
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000743 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000744 E = PDecl->instmeth_end(); I != E; ++I)
745 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000746 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000747 E = PDecl->classmeth_end(); I != E; ++I)
748 RewriteMethodDeclaration(*I);
749
Steve Naroff752d6ef2007-10-30 16:42:30 +0000750 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000751 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattneraadaf782008-01-31 19:51:04 +0000752 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000753
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000754 // Must comment out @optional/@required
755 const char *startBuf = SM->getCharacterData(LocStart);
756 const char *endBuf = SM->getCharacterData(LocEnd);
757 for (const char *p = startBuf; p < endBuf; p++) {
758 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
759 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000760 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000761 ReplaceText(OptionalLoc, strlen("@optional"),
762 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000763
764 }
765 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
766 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000767 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000768 ReplaceText(OptionalLoc, strlen("@required"),
769 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000770
771 }
772 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000773}
774
Steve Naroffb29b4272008-04-14 22:03:09 +0000775void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000776 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000777 if (LocStart.isInvalid())
778 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000779 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000780 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000781}
782
Steve Naroffb29b4272008-04-14 22:03:09 +0000783void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000784 std::string &ResultStr) {
Steve Naroffced80a82008-10-30 12:09:33 +0000785 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroff76e429d2008-07-16 14:40:40 +0000786 const FunctionType *FPRetType = 0;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000787 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000788 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000789 ResultStr += "id";
Steve Naroff76e429d2008-07-16 14:40:40 +0000790 else if (OMD->getResultType()->isFunctionPointerType()) {
791 // needs special handling, since pointer-to-functions have special
792 // syntax (where a decaration models use).
793 QualType retType = OMD->getResultType();
794 if (const PointerType* PT = retType->getAsPointerType()) {
795 QualType PointeeTy = PT->getPointeeType();
796 if ((FPRetType = PointeeTy->getAsFunctionType())) {
797 ResultStr += FPRetType->getResultType().getAsString();
798 ResultStr += "(*";
799 }
800 }
801 } else
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000802 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000803 ResultStr += " ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000804
805 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000806 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000807
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000808 if (OMD->isInstance())
809 NameStr += "_I_";
810 else
811 NameStr += "_C_";
812
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000813 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000814 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000815
816 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000817 if (ObjCCategoryImplDecl *CID =
818 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000819 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000820 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000821 }
Steve Naroff563b8282008-04-04 22:23:44 +0000822 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +0000823 {
824 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000825 int len = selString.size();
826 for (int i = 0; i < len; i++)
827 if (selString[i] == ':')
828 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000829 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000830 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000831 // Remember this name for metadata emission
832 MethodInternalNames[OMD] = NameStr;
833 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000834
835 // Rewrite arguments
836 ResultStr += "(";
837
838 // invisible arguments
839 if (OMD->isInstance()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000840 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000841 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +0000842 if (!LangOpts.Microsoft) {
843 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
844 ResultStr += "struct ";
845 }
846 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000847 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000848 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000849 }
850 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000851 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000852
853 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000854 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000855 ResultStr += " _cmd";
856
857 // Method arguments.
Chris Lattner58cce3b2008-03-16 01:07:14 +0000858 for (unsigned i = 0; i < OMD->getNumParams(); i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000859 ParmVarDecl *PDecl = OMD->getParamDecl(i);
860 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +0000861 if (PDecl->getType()->isObjCQualifiedIdType()) {
862 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000863 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +0000864 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000865 std::string Name = PDecl->getNameAsString();
Steve Naroffc8ad87b2008-10-30 14:45:29 +0000866 if (isBlockPointerType(PDecl->getType())) {
867 // Make sure we convert "t (^)(...)" to "t (*)(...)".
868 const BlockPointerType *BPT = PDecl->getType()->getAsBlockPointerType();
869 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name);
870 } else
871 PDecl->getType().getAsStringInternal(Name);
Steve Naroff543409e2008-04-18 21:13:19 +0000872 ResultStr += Name;
873 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000874 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +0000875 if (OMD->isVariadic())
876 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000877 ResultStr += ") ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000878
Steve Naroff76e429d2008-07-16 14:40:40 +0000879 if (FPRetType) {
880 ResultStr += ")"; // close the precedence "scope" for "*".
881
882 // Now, emit the argument types (if any).
883 if (const FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(FPRetType)) {
884 ResultStr += "(";
885 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
886 if (i) ResultStr += ", ";
887 std::string ParamStr = FT->getArgType(i).getAsString();
888 ResultStr += ParamStr;
889 }
890 if (FT->isVariadic()) {
891 if (FT->getNumArgs()) ResultStr += ", ";
892 ResultStr += "...";
893 }
894 ResultStr += ")";
895 } else {
896 ResultStr += "()";
897 }
898 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000899}
Steve Naroffb29b4272008-04-14 22:03:09 +0000900void RewriteObjC::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000901 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
902 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000903
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000904 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000905 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000906 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000907 InsertText(CID->getLocStart(), "// ", 3);
Steve Narofface66252008-11-13 20:07:04 +0000908
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000909 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000910 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
911 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000912 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000913 ObjCMethodDecl *OMD = *I;
914 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000915 SourceLocation LocStart = OMD->getLocStart();
916 SourceLocation LocEnd = OMD->getBody()->getLocStart();
917
918 const char *startBuf = SM->getCharacterData(LocStart);
919 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000920 ReplaceText(LocStart, endBuf-startBuf,
921 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000922 }
923
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000924 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000925 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
926 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000927 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000928 ObjCMethodDecl *OMD = *I;
929 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000930 SourceLocation LocStart = OMD->getLocStart();
931 SourceLocation LocEnd = OMD->getBody()->getLocStart();
932
933 const char *startBuf = SM->getCharacterData(LocStart);
934 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000935 ReplaceText(LocStart, endBuf-startBuf,
936 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000937 }
Steve Naroffd40910b2008-12-01 20:33:01 +0000938 for (ObjCCategoryImplDecl::propimpl_iterator
939 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
940 E = IMD ? IMD->propimpl_end() : CID->propimpl_end(); I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +0000941 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +0000942 }
943
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000944 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000945 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000946 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000947 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000948}
949
Steve Naroffb29b4272008-04-14 22:03:09 +0000950void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000951 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000952 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000953 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +0000954 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000955 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000956 ResultStr += "\n";
957 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000958 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000959 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000960 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000961 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000962 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000963 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000964 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000965 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000966 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Narofff908a872007-10-30 02:23:23 +0000967
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000968 RewriteProperties(ClassDecl->getNumPropertyDecl(),
969 ClassDecl->getPropertyDecl());
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000970 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000971 E = ClassDecl->instmeth_end(); I != E; ++I)
972 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000973 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000974 E = ClassDecl->classmeth_end(); I != E; ++I)
975 RewriteMethodDeclaration(*I);
976
Steve Naroff2feac5e2007-10-30 03:43:13 +0000977 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000978 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000979}
980
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000981Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
982 SourceLocation OrigStart) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000983 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff54055232008-10-27 17:20:55 +0000984 if (CurMethodDef) {
Steve Naroff05b8c782008-03-12 00:25:36 +0000985 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +0000986 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
987 // lookup which class implements the instance variable.
988 ObjCInterfaceDecl *clsDeclared = 0;
989 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
990 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
991
992 // Synthesize an explicit cast to gain access to the ivar.
993 std::string RecName = clsDeclared->getIdentifier()->getName();
994 RecName += "_IMPL";
995 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000996 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +0000997 SourceLocation(), II);
Steve Narofff0757612008-05-08 17:52:16 +0000998 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
999 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001000 CastExpr *castExpr = new CStyleCastExpr(castT, IV->getBase(), castT,
Steve Naroffb2f9e512008-11-03 23:29:32 +00001001 SourceLocation(), SourceLocation());
Steve Narofff0757612008-05-08 17:52:16 +00001002 // Don't forget the parens to enforce the proper binding.
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001003 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
1004 IV->getBase()->getLocEnd(),
1005 castExpr);
Steve Narofff0757612008-05-08 17:52:16 +00001006 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +00001007 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001008 MemberExpr *ME = new MemberExpr(PE, true, D, IV->getLocation(),
1009 D->getType());
Steve Narofff0757612008-05-08 17:52:16 +00001010 ReplaceStmt(IV, ME);
1011 delete IV;
1012 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001013 }
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001014
1015 ReplaceStmt(IV->getBase(), PE);
1016 // Cannot delete IV->getBase(), since PE points to it.
1017 // Replace the old base with the cast. This is important when doing
1018 // embedded rewrites. For example, [newInv->_container addObject:0].
1019 IV->setBase(PE);
1020 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001021 }
Steve Naroff84472a82008-04-18 21:55:08 +00001022 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001023 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
1024
1025 // Explicit ivar refs need to have a cast inserted.
1026 // FIXME: consider sharing some of this code with the code above.
1027 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +00001028 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001029 // lookup which class implements the instance variable.
1030 ObjCInterfaceDecl *clsDeclared = 0;
Steve Narofff0757612008-05-08 17:52:16 +00001031 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001032 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1033
1034 // Synthesize an explicit cast to gain access to the ivar.
1035 std::string RecName = clsDeclared->getIdentifier()->getName();
1036 RecName += "_IMPL";
1037 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001038 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001039 SourceLocation(), II);
Steve Naroff9f525972008-05-06 23:20:07 +00001040 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1041 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001042 CastExpr *castExpr = new CStyleCastExpr(castT, IV->getBase(), castT,
Steve Naroffb2f9e512008-11-03 23:29:32 +00001043 SourceLocation(), SourceLocation());
Steve Naroff9f525972008-05-06 23:20:07 +00001044 // Don't forget the parens to enforce the proper binding.
Chris Lattner8d366162008-05-28 16:38:23 +00001045 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
1046 IV->getBase()->getLocEnd(), castExpr);
Steve Naroff9f525972008-05-06 23:20:07 +00001047 ReplaceStmt(IV->getBase(), PE);
1048 // Cannot delete IV->getBase(), since PE points to it.
1049 // Replace the old base with the cast. This is important when doing
1050 // embedded rewrites. For example, [newInv->_container addObject:0].
1051 IV->setBase(PE);
1052 return IV;
1053 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001054 }
Steve Naroff84472a82008-04-18 21:55:08 +00001055 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +00001056}
1057
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001058/// SynthCountByEnumWithState - To print:
1059/// ((unsigned int (*)
1060/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1061/// (void *)objc_msgSend)((id)l_collection,
1062/// sel_registerName(
1063/// "countByEnumeratingWithState:objects:count:"),
1064/// &enumState,
1065/// (id *)items, (unsigned int)16)
1066///
Steve Naroffb29b4272008-04-14 22:03:09 +00001067void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001068 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1069 "id *, unsigned int))(void *)objc_msgSend)";
1070 buf += "\n\t\t";
1071 buf += "((id)l_collection,\n\t\t";
1072 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1073 buf += "\n\t\t";
1074 buf += "&enumState, "
1075 "(id *)items, (unsigned int)16)";
1076}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001077
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001078/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1079/// statement to exit to its outer synthesized loop.
1080///
Steve Naroffb29b4272008-04-14 22:03:09 +00001081Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001082 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1083 return S;
1084 // replace break with goto __break_label
1085 std::string buf;
1086
1087 SourceLocation startLoc = S->getLocStart();
1088 buf = "goto __break_label_";
1089 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001090 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001091
1092 return 0;
1093}
1094
1095/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1096/// statement to continue with its inner synthesized loop.
1097///
Steve Naroffb29b4272008-04-14 22:03:09 +00001098Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001099 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1100 return S;
1101 // replace continue with goto __continue_label
1102 std::string buf;
1103
1104 SourceLocation startLoc = S->getLocStart();
1105 buf = "goto __continue_label_";
1106 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001107 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001108
1109 return 0;
1110}
1111
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001112/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001113/// It rewrites:
1114/// for ( type elem in collection) { stmts; }
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001115
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001116/// Into:
1117/// {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001118/// type elem;
1119/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001120/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001121/// id l_collection = (id)collection;
1122/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1123/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001124/// if (limit) {
1125/// unsigned long startMutations = *enumState.mutationsPtr;
1126/// do {
1127/// unsigned long counter = 0;
1128/// do {
1129/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001130/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001131/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001132/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001133/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001134/// } while (counter < limit);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001135/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1136/// objects:items count:16]);
1137/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001138/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001139/// }
1140/// else
1141/// elem = nil;
1142/// }
1143///
Steve Naroffb29b4272008-04-14 22:03:09 +00001144Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001145 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001146 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1147 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1148 "ObjCForCollectionStmt Statement stack mismatch");
1149 assert(!ObjCBcLabelNo.empty() &&
1150 "ObjCForCollectionStmt - Label No stack empty");
1151
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001152 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001153 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001154 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001155 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001156 std::string buf;
1157 buf = "\n{\n\t";
1158 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1159 // type elem;
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001160 ScopedDecl* D = DS->getSolitaryDecl();
1161 QualType ElementType = cast<ValueDecl>(D)->getType();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001162 elementTypeAsString = ElementType.getAsString();
1163 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001164 buf += " ";
Chris Lattner8ec03f52008-11-24 03:54:41 +00001165 elementName = D->getNameAsCString();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001166 buf += elementName;
1167 buf += ";\n\t";
1168 }
Chris Lattner06767512008-04-08 05:52:18 +00001169 else {
1170 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner8ec03f52008-11-24 03:54:41 +00001171 elementName = DR->getDecl()->getNameAsCString();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001172 elementTypeAsString
1173 = cast<ValueDecl>(DR->getDecl())->getType().getAsString();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001174 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001175
1176 // struct __objcFastEnumerationState enumState = { 0 };
1177 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1178 // id items[16];
1179 buf += "id items[16];\n\t";
1180 // id l_collection = (id)
1181 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001182 // Find start location of 'collection' the hard way!
1183 const char *startCollectionBuf = startBuf;
1184 startCollectionBuf += 3; // skip 'for'
1185 startCollectionBuf = strchr(startCollectionBuf, '(');
1186 startCollectionBuf++; // skip '('
1187 // find 'in' and skip it.
1188 while (*startCollectionBuf != ' ' ||
1189 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1190 (*(startCollectionBuf+3) != ' ' &&
1191 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1192 startCollectionBuf++;
1193 startCollectionBuf += 3;
1194
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001195 // Replace: "for (type element in" with string constructed thus far.
Chris Lattneraadaf782008-01-31 19:51:04 +00001196 ReplaceText(startLoc, startCollectionBuf - startBuf,
1197 buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001198 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001199 SourceLocation rightParenLoc = S->getRParenLoc();
1200 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1201 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001202 buf = ";\n\t";
1203
1204 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1205 // objects:items count:16];
1206 // which is synthesized into:
1207 // unsigned int limit =
1208 // ((unsigned int (*)
1209 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1210 // (void *)objc_msgSend)((id)l_collection,
1211 // sel_registerName(
1212 // "countByEnumeratingWithState:objects:count:"),
1213 // (struct __objcFastEnumerationState *)&state,
1214 // (id *)items, (unsigned int)16);
1215 buf += "unsigned long limit =\n\t\t";
1216 SynthCountByEnumWithState(buf);
1217 buf += ";\n\t";
1218 /// if (limit) {
1219 /// unsigned long startMutations = *enumState.mutationsPtr;
1220 /// do {
1221 /// unsigned long counter = 0;
1222 /// do {
1223 /// if (startMutations != *enumState.mutationsPtr)
1224 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001225 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001226 buf += "if (limit) {\n\t";
1227 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1228 buf += "do {\n\t\t";
1229 buf += "unsigned long counter = 0;\n\t\t";
1230 buf += "do {\n\t\t\t";
1231 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1232 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1233 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001234 buf += " = (";
1235 buf += elementTypeAsString;
1236 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001237 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattneraadaf782008-01-31 19:51:04 +00001238 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001239
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001240 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001241 /// } while (counter < limit);
1242 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1243 /// objects:items count:16]);
1244 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001245 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001246 /// }
1247 /// else
1248 /// elem = nil;
1249 /// }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001250 ///
1251 buf = ";\n\t";
1252 buf += "__continue_label_";
1253 buf += utostr(ObjCBcLabelNo.back());
1254 buf += ": ;";
1255 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001256 buf += "} while (counter < limit);\n\t";
1257 buf += "} while (limit = ";
1258 SynthCountByEnumWithState(buf);
1259 buf += ");\n\t";
1260 buf += elementName;
1261 buf += " = nil;\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001262 buf += "__break_label_";
1263 buf += utostr(ObjCBcLabelNo.back());
1264 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001265 buf += "}\n\t";
1266 buf += "else\n\t\t";
1267 buf += elementName;
1268 buf += " = nil;\n";
1269 buf += "}\n";
Steve Naroff600e4e82008-07-21 18:26:02 +00001270
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001271 // Insert all these *after* the statement body.
Steve Naroff600e4e82008-07-21 18:26:02 +00001272 if (isa<CompoundStmt>(S->getBody())) {
1273 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1274 InsertText(endBodyLoc, buf.c_str(), buf.size());
1275 } else {
1276 /* Need to treat single statements specially. For example:
1277 *
1278 * for (A *a in b) if (stuff()) break;
1279 * for (A *a in b) xxxyy;
1280 *
1281 * The following code simply scans ahead to the semi to find the actual end.
1282 */
1283 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1284 const char *semiBuf = strchr(stmtBuf, ';');
1285 assert(semiBuf && "Can't find ';'");
1286 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1287 InsertText(endBodyLoc, buf.c_str(), buf.size());
1288 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001289 Stmts.pop_back();
1290 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001291 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001292}
1293
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001294/// RewriteObjCSynchronizedStmt -
1295/// This routine rewrites @synchronized(expr) stmt;
1296/// into:
1297/// objc_sync_enter(expr);
1298/// @try stmt @finally { objc_sync_exit(expr); }
1299///
Steve Naroffb29b4272008-04-14 22:03:09 +00001300Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001301 // Get the start location and compute the semi location.
1302 SourceLocation startLoc = S->getLocStart();
1303 const char *startBuf = SM->getCharacterData(startLoc);
1304
1305 assert((*startBuf == '@') && "bogus @synchronized location");
1306
1307 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001308 buf = "objc_sync_enter((id)";
1309 const char *lparenBuf = startBuf;
1310 while (*lparenBuf != '(') lparenBuf++;
1311 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Steve Naroffc7089f12008-08-19 13:04:19 +00001312 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1313 // the sync expression is typically a message expression that's already
1314 // been rewritten! (which implies the SourceLocation's are invalid).
1315 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001316 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001317 while (*endBuf != ')') endBuf--;
1318 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001319 buf = ");\n";
1320 // declare a new scope with two variables, _stack and _rethrow.
1321 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1322 buf += "int buf[18/*32-bit i386*/];\n";
1323 buf += "char *pointers[4];} _stack;\n";
1324 buf += "id volatile _rethrow = 0;\n";
1325 buf += "objc_exception_try_enter(&_stack);\n";
1326 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00001327 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001328 startLoc = S->getSynchBody()->getLocEnd();
1329 startBuf = SM->getCharacterData(startLoc);
1330
Steve Naroffc7089f12008-08-19 13:04:19 +00001331 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001332 SourceLocation lastCurlyLoc = startLoc;
1333 buf = "}\nelse {\n";
1334 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1335 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb2a39452008-07-16 19:47:39 +00001336 buf += " objc_sync_exit(";
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001337 Expr *syncExpr = new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00001338 S->getSynchExpr(),
1339 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00001340 SourceLocation(), SourceLocation());
Ted Kremeneka95d3752008-09-13 05:16:45 +00001341 std::string syncExprBufS;
1342 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Steve Naroff3498cc92008-08-21 13:03:03 +00001343 syncExpr->printPretty(syncExprBuf);
Steve Naroffb2a39452008-07-16 19:47:39 +00001344 buf += syncExprBuf.str();
1345 buf += ");\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001346 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1347 buf += "}\n";
1348 buf += "}";
1349
Chris Lattneraadaf782008-01-31 19:51:04 +00001350 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001351 return 0;
1352}
1353
Steve Naroffb29b4272008-04-14 22:03:09 +00001354Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001355 // Get the start location and compute the semi location.
1356 SourceLocation startLoc = S->getLocStart();
1357 const char *startBuf = SM->getCharacterData(startLoc);
1358
1359 assert((*startBuf == '@') && "bogus @try location");
1360
1361 std::string buf;
1362 // declare a new scope with two variables, _stack and _rethrow.
1363 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1364 buf += "int buf[18/*32-bit i386*/];\n";
1365 buf += "char *pointers[4];} _stack;\n";
1366 buf += "id volatile _rethrow = 0;\n";
1367 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001368 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001369
Chris Lattneraadaf782008-01-31 19:51:04 +00001370 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001371
1372 startLoc = S->getTryBody()->getLocEnd();
1373 startBuf = SM->getCharacterData(startLoc);
1374
1375 assert((*startBuf == '}') && "bogus @try block");
Steve Naroffc9ba1722008-07-16 15:31:30 +00001376
Steve Naroff75730982007-11-07 04:08:17 +00001377 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffc9ba1722008-07-16 15:31:30 +00001378 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1379 if (catchList) {
1380 startLoc = startLoc.getFileLocWithOffset(1);
1381 buf = " /* @catch begin */ else {\n";
1382 buf += " id _caught = objc_exception_extract(&_stack);\n";
1383 buf += " objc_exception_try_enter (&_stack);\n";
1384 buf += " if (_setjmp(_stack.buf))\n";
1385 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1386 buf += " else { /* @catch continue */";
1387
1388 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001389 } else { /* no catch list */
1390 buf = "}\nelse {\n";
1391 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1392 buf += "}";
1393 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffc9ba1722008-07-16 15:31:30 +00001394 }
Steve Naroff75730982007-11-07 04:08:17 +00001395 bool sawIdTypedCatch = false;
1396 Stmt *lastCatchBody = 0;
Steve Naroff75730982007-11-07 04:08:17 +00001397 while (catchList) {
1398 Stmt *catchStmt = catchList->getCatchParamStmt();
1399
1400 if (catchList == S->getCatchStmts())
1401 buf = "if ("; // we are generating code for the first catch clause
1402 else
1403 buf = "else if (";
1404 startLoc = catchList->getLocStart();
1405 startBuf = SM->getCharacterData(startLoc);
1406
1407 assert((*startBuf == '@') && "bogus @catch location");
1408
1409 const char *lParenLoc = strchr(startBuf, '(');
1410
Steve Naroffbe4b3332008-02-01 22:08:12 +00001411 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001412 // Now rewrite the body...
1413 lastCatchBody = catchList->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001414 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1415 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner06767512008-04-08 05:52:18 +00001416 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1417 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001418 assert((*bodyBuf == '{') && "bogus @catch body location");
1419
1420 buf += "1) { id _tmp = _caught;";
1421 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1422 buf.c_str(), buf.size());
1423 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Ted Kremenek50a25e22008-10-06 22:39:38 +00001424 QualType t = dyn_cast<ValueDecl>(declStmt->getSolitaryDecl())->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001425 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001426 buf += "1) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001427 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001428 sawIdTypedCatch = true;
1429 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001430 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroff75730982007-11-07 04:08:17 +00001431
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001432 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001433 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001434 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001435 buf += cls->getDecl()->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001436 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001437 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001438 }
1439 }
1440 // Now rewrite the body...
1441 lastCatchBody = catchList->getCatchBody();
1442 SourceLocation rParenLoc = catchList->getRParenLoc();
1443 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1444 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1445 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1446 assert((*rParenBuf == ')') && "bogus @catch paren location");
1447 assert((*bodyBuf == '{') && "bogus @catch body location");
1448
1449 buf = " = _caught;";
1450 // Here we replace ") {" with "= _caught;" (which initializes and
1451 // declares the @catch parameter).
Chris Lattneraadaf782008-01-31 19:51:04 +00001452 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001453 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001454 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001455 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001456 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001457 catchList = catchList->getNextCatchStmt();
1458 }
1459 // Complete the catch list...
1460 if (lastCatchBody) {
1461 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001462 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1463 "bogus @catch body location");
Steve Naroff75730982007-11-07 04:08:17 +00001464
Steve Naroff378f47a2008-09-11 15:29:03 +00001465 // Insert the last (implicit) else clause *before* the right curly brace.
1466 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1467 buf = "} /* last catch end */\n";
1468 buf += "else {\n";
1469 buf += " _rethrow = _caught;\n";
1470 buf += " objc_exception_try_exit(&_stack);\n";
1471 buf += "} } /* @catch end */\n";
1472 if (!S->getFinallyStmt())
1473 buf += "}\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001474 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001475
1476 // Set lastCurlyLoc
1477 lastCurlyLoc = lastCatchBody->getLocEnd();
1478 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001479 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001480 startLoc = finalStmt->getLocStart();
1481 startBuf = SM->getCharacterData(startLoc);
1482 assert((*startBuf == '@') && "bogus @finally start");
1483
1484 buf = "/* @finally */";
Chris Lattneraadaf782008-01-31 19:51:04 +00001485 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001486
1487 Stmt *body = finalStmt->getFinallyBody();
1488 SourceLocation startLoc = body->getLocStart();
1489 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001490 assert(*SM->getCharacterData(startLoc) == '{' &&
1491 "bogus @finally body location");
1492 assert(*SM->getCharacterData(endLoc) == '}' &&
1493 "bogus @finally body location");
Steve Naroff75730982007-11-07 04:08:17 +00001494
1495 startLoc = startLoc.getFileLocWithOffset(1);
1496 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001497 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001498 endLoc = endLoc.getFileLocWithOffset(-1);
1499 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001500 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001501
1502 // Set lastCurlyLoc
1503 lastCurlyLoc = body->getLocEnd();
Steve Naroff378f47a2008-09-11 15:29:03 +00001504 } else { /* no finally clause - make sure we synthesize an implicit one */
1505 buf = "{ /* implicit finally clause */\n";
1506 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1507 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1508 buf += "}";
1509 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001510 }
1511 // Now emit the final closing curly brace...
1512 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1513 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001514 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001515 return 0;
1516}
1517
Steve Naroffb29b4272008-04-14 22:03:09 +00001518Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001519 return 0;
1520}
1521
Steve Naroffb29b4272008-04-14 22:03:09 +00001522Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001523 return 0;
1524}
1525
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001526// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff2bd03922007-11-07 15:32:26 +00001527// the throw expression is typically a message expression that's already
1528// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001529Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001530 // Get the start location and compute the semi location.
1531 SourceLocation startLoc = S->getLocStart();
1532 const char *startBuf = SM->getCharacterData(startLoc);
1533
1534 assert((*startBuf == '@') && "bogus @throw location");
1535
1536 std::string buf;
1537 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001538 if (S->getThrowExpr())
1539 buf = "objc_exception_throw(";
1540 else // add an implicit argument
1541 buf = "objc_exception_throw(_caught";
Steve Naroff4ba0acb2008-07-25 15:41:30 +00001542
1543 // handle "@ throw" correctly.
1544 const char *wBuf = strchr(startBuf, 'w');
1545 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1546 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
1547
Steve Naroff2bd03922007-11-07 15:32:26 +00001548 const char *semiBuf = strchr(startBuf, ';');
1549 assert((*semiBuf == ';') && "@throw: can't find ';'");
1550 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1551 buf = ");";
Chris Lattneraadaf782008-01-31 19:51:04 +00001552 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001553 return 0;
1554}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001555
Steve Naroffb29b4272008-04-14 22:03:09 +00001556Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001557 // Create a new string expression.
1558 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001559 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001560 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001561 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1562 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +00001563 SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001564 ReplaceStmt(Exp, Replacement);
Chris Lattnere365c502007-11-30 22:25:36 +00001565
Chris Lattner07506182007-11-30 22:53:43 +00001566 // Replace this subexpr in the parent.
Chris Lattnere64b7772007-10-24 16:57:36 +00001567 delete Exp;
1568 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001569}
1570
Steve Naroffb29b4272008-04-14 22:03:09 +00001571Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroffb42f8412007-11-05 14:50:49 +00001572 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1573 // Create a call to sel_registerName("selName").
1574 llvm::SmallVector<Expr*, 8> SelExprs;
1575 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner077bf5e2008-11-24 03:33:13 +00001576 SelExprs.push_back(new StringLiteral(Exp->getSelector().getAsString().c_str(),
1577 Exp->getSelector().getAsString().size(),
Steve Naroffb42f8412007-11-05 14:50:49 +00001578 false, argType, SourceLocation(),
1579 SourceLocation()));
1580 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1581 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001582 ReplaceStmt(Exp, SelExp);
Steve Naroffb42f8412007-11-05 14:50:49 +00001583 delete Exp;
1584 return SelExp;
1585}
1586
Steve Naroffb29b4272008-04-14 22:03:09 +00001587CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff934f2762007-10-24 22:48:43 +00001588 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001589 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001590 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +00001591
1592 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +00001593 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +00001594
1595 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001596 QualType pToFunc = Context->getPointerType(msgSendType);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001597 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE,
1598 /*isLvalue=*/false);
Steve Naroffebf2b562007-10-23 23:50:29 +00001599
1600 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +00001601
Steve Naroff934f2762007-10-24 22:48:43 +00001602 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1603}
1604
Steve Naroffd5255f52007-11-01 13:24:47 +00001605static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1606 const char *&startRef, const char *&endRef) {
1607 while (startBuf < endBuf) {
1608 if (*startBuf == '<')
1609 startRef = startBuf; // mark the start.
1610 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001611 if (startRef && *startRef == '<') {
1612 endRef = startBuf; // mark the end.
1613 return true;
1614 }
1615 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001616 }
1617 startBuf++;
1618 }
1619 return false;
1620}
1621
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001622static void scanToNextArgument(const char *&argRef) {
1623 int angle = 0;
1624 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1625 if (*argRef == '<')
1626 angle++;
1627 else if (*argRef == '>')
1628 angle--;
1629 argRef++;
1630 }
1631 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1632}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001633
Steve Naroffb29b4272008-04-14 22:03:09 +00001634bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001635
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001636 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001637 return true;
1638
Steve Naroffd5255f52007-11-01 13:24:47 +00001639 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +00001640 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001641 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff9165ad32007-10-31 04:38:33 +00001642 return true; // we have "Class <Protocol> *".
1643 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001644 return false;
1645}
1646
Steve Naroff4f95b752008-07-29 18:15:38 +00001647void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1648 QualType Type = E->getType();
1649 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00001650 SourceLocation Loc, EndLoc;
1651
1652 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
1653 Loc = ECE->getLParenLoc();
1654 EndLoc = ECE->getRParenLoc();
1655 } else {
1656 Loc = E->getLocStart();
1657 EndLoc = E->getLocEnd();
1658 }
1659 // This will defend against trying to rewrite synthesized expressions.
1660 if (Loc.isInvalid() || EndLoc.isInvalid())
1661 return;
1662
Steve Naroff4f95b752008-07-29 18:15:38 +00001663 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00001664 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00001665 const char *startRef = 0, *endRef = 0;
1666 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1667 // Get the locations of the startRef, endRef.
1668 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1669 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1670 // Comment out the protocol references.
1671 InsertText(LessLoc, "/*", 2);
1672 InsertText(GreaterLoc, "*/", 2);
1673 }
1674 }
1675}
1676
Steve Naroffb29b4272008-04-14 22:03:09 +00001677void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001678 SourceLocation Loc;
1679 QualType Type;
1680 const FunctionTypeProto *proto = 0;
1681 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1682 Loc = VD->getLocation();
1683 Type = VD->getType();
1684 }
1685 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1686 Loc = FD->getLocation();
1687 // Check for ObjC 'id' and class types that have been adorned with protocol
1688 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1689 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1690 assert(funcType && "missing function type");
1691 proto = dyn_cast<FunctionTypeProto>(funcType);
1692 if (!proto)
1693 return;
1694 Type = proto->getResultType();
1695 }
1696 else
1697 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001698
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001699 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001700 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001701
1702 const char *endBuf = SM->getCharacterData(Loc);
1703 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00001704 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001705 startBuf--; // scan backward (from the decl location) for return type.
1706 const char *startRef = 0, *endRef = 0;
1707 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1708 // Get the locations of the startRef, endRef.
1709 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1710 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1711 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001712 InsertText(LessLoc, "/*", 2);
1713 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001714 }
1715 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001716 if (!proto)
1717 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001718 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001719 const char *startBuf = SM->getCharacterData(Loc);
1720 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001721 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1722 if (needToScanForQualifiers(proto->getArgType(i))) {
1723 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001724
Steve Naroffd5255f52007-11-01 13:24:47 +00001725 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001726 // scan forward (from the decl location) for argument types.
1727 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001728 const char *startRef = 0, *endRef = 0;
1729 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1730 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001731 SourceLocation LessLoc =
1732 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1733 SourceLocation GreaterLoc =
1734 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001735 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001736 InsertText(LessLoc, "/*", 2);
1737 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001738 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001739 startBuf = ++endBuf;
1740 }
1741 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00001742 // If the function name is derived from a macro expansion, then the
1743 // argument buffer will not follow the name. Need to speak with Chris.
1744 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001745 startBuf++; // scan forward (from the decl location) for argument types.
1746 startBuf++;
1747 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001748 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001749}
1750
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001751// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00001752void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001753 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1754 llvm::SmallVector<QualType, 16> ArgTys;
1755 ArgTys.push_back(Context->getPointerType(
1756 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001757 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001758 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001759 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001760 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001761 SourceLocation(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001762 SelGetUidIdent, getFuncType,
1763 FunctionDecl::Extern, false, 0);
1764}
1765
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001766// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
Steve Naroffb29b4272008-04-14 22:03:09 +00001767void RewriteObjC::SynthGetProtocolFunctionDecl() {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001768 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1769 llvm::SmallVector<QualType, 16> ArgTys;
1770 ArgTys.push_back(Context->getPointerType(
1771 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001772 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001773 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001774 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001775 GetProtocolFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001776 SourceLocation(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001777 SelGetProtoIdent, getFuncType,
1778 FunctionDecl::Extern, false, 0);
1779}
1780
Steve Naroffb29b4272008-04-14 22:03:09 +00001781void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001782 // declared in <objc/objc.h>
Chris Lattner8ec03f52008-11-24 03:54:41 +00001783 if (strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001784 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001785 return;
1786 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001787 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001788}
1789
Steve Naroffc0a123c2008-03-11 17:37:02 +00001790// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00001791void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00001792 if (SuperContructorFunctionDecl)
1793 return;
1794 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_super");
1795 llvm::SmallVector<QualType, 16> ArgTys;
1796 QualType argT = Context->getObjCIdType();
1797 assert(!argT.isNull() && "Can't find 'id' type");
1798 ArgTys.push_back(argT);
1799 ArgTys.push_back(argT);
1800 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1801 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001802 false, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001803 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001804 SourceLocation(),
Steve Naroffc0a123c2008-03-11 17:37:02 +00001805 msgSendIdent, msgSendType,
1806 FunctionDecl::Extern, false, 0);
1807}
1808
Steve Naroff09b266e2007-10-30 23:14:51 +00001809// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001810void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00001811 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1812 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001813 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001814 assert(!argT.isNull() && "Can't find 'id' type");
1815 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001816 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001817 assert(!argT.isNull() && "Can't find 'SEL' type");
1818 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001819 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001820 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001821 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001822 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001823 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001824 msgSendIdent, msgSendType,
1825 FunctionDecl::Extern, false, 0);
1826}
1827
Steve Naroff874e2322007-11-15 10:28:18 +00001828// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001829void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00001830 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1831 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001832 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001833 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00001834 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00001835 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1836 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1837 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001838 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00001839 assert(!argT.isNull() && "Can't find 'SEL' type");
1840 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001841 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00001842 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001843 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001844 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001845 SourceLocation(),
Steve Naroff874e2322007-11-15 10:28:18 +00001846 msgSendIdent, msgSendType,
1847 FunctionDecl::Extern, false, 0);
1848}
1849
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001850// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001851void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001852 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1853 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001854 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001855 assert(!argT.isNull() && "Can't find 'id' type");
1856 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001857 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001858 assert(!argT.isNull() && "Can't find 'SEL' type");
1859 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001860 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001861 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001862 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001863 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001864 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001865 msgSendIdent, msgSendType,
1866 FunctionDecl::Extern, false, 0);
1867}
1868
1869// SynthMsgSendSuperStretFunctionDecl -
1870// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001871void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001872 IdentifierInfo *msgSendIdent =
1873 &Context->Idents.get("objc_msgSendSuper_stret");
1874 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001875 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001876 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00001877 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001878 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1879 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1880 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001881 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001882 assert(!argT.isNull() && "Can't find 'SEL' type");
1883 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001884 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001885 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001886 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001887 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnera98e58d2008-03-15 21:24:04 +00001888 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001889 msgSendIdent, msgSendType,
1890 FunctionDecl::Extern, false, 0);
1891}
1892
Steve Naroff1284db82008-05-08 22:02:18 +00001893// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001894void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001895 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1896 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001897 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001898 assert(!argT.isNull() && "Can't find 'id' type");
1899 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001900 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001901 assert(!argT.isNull() && "Can't find 'SEL' type");
1902 ArgTys.push_back(argT);
Steve Naroff1284db82008-05-08 22:02:18 +00001903 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001904 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001905 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001906 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001907 SourceLocation(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001908 msgSendIdent, msgSendType,
1909 FunctionDecl::Extern, false, 0);
1910}
1911
Steve Naroff09b266e2007-10-30 23:14:51 +00001912// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00001913void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00001914 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1915 llvm::SmallVector<QualType, 16> ArgTys;
1916 ArgTys.push_back(Context->getPointerType(
1917 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001918 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001919 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001920 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001921 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001922 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001923 getClassIdent, getClassType,
1924 FunctionDecl::Extern, false, 0);
1925}
1926
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001927// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00001928void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001929 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1930 llvm::SmallVector<QualType, 16> ArgTys;
1931 ArgTys.push_back(Context->getPointerType(
1932 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001933 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001934 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001935 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001936 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001937 SourceLocation(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001938 getClassIdent, getClassType,
1939 FunctionDecl::Extern, false, 0);
1940}
1941
Steve Naroffb29b4272008-04-14 22:03:09 +00001942Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001943 QualType strType = getConstantStringStructType();
1944
1945 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00001946
1947 std::string tmpName = InFileName;
1948 unsigned i;
1949 for (i=0; i < tmpName.length(); i++) {
1950 char c = tmpName.at(i);
1951 // replace any non alphanumeric characters with '_'.
1952 if (!isalpha(c) && (c < '0' || c > '9'))
1953 tmpName[i] = '_';
1954 }
1955 S += tmpName;
1956 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001957 S += utostr(NumObjCStringLiterals++);
1958
Steve Naroffba92b2e2008-03-27 22:29:16 +00001959 Preamble += "static __NSConstantStringImpl " + S;
1960 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
1961 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001962 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00001963 std::string prettyBufS;
1964 llvm::raw_string_ostream prettyBuf(prettyBufS);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001965 Exp->getString()->printPretty(prettyBuf);
Steve Naroffba92b2e2008-03-27 22:29:16 +00001966 Preamble += prettyBuf.str();
1967 Preamble += ",";
Steve Naroff3652c2d2008-03-15 01:36:04 +00001968 // The minus 2 removes the begin/end double quotes.
Steve Naroffba92b2e2008-03-27 22:29:16 +00001969 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001970
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001971 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Steve Naroff248a7532008-04-15 22:42:06 +00001972 &Context->Idents.get(S.c_str()), strType,
1973 VarDecl::Static, NULL);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001974 DeclRefExpr *DRE = new DeclRefExpr(NewVD, strType, SourceLocation());
1975 Expr *Unop = new UnaryOperator(DRE, UnaryOperator::AddrOf,
1976 Context->getPointerType(DRE->getType()),
1977 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00001978 // cast to NSConstantString *
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001979 CastExpr *cast = new CStyleCastExpr(Exp->getType(), Unop,
Steve Naroffb2f9e512008-11-03 23:29:32 +00001980 Exp->getType(), SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001981 ReplaceStmt(Exp, cast);
Steve Naroff96984642007-11-08 14:30:50 +00001982 delete Exp;
1983 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00001984}
1985
Steve Naroffb29b4272008-04-14 22:03:09 +00001986ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001987 // check if we are sending a message to 'super'
Steve Naroff54055232008-10-27 17:20:55 +00001988 if (!CurMethodDef || !CurMethodDef->isInstance()) return 0;
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001989
Douglas Gregorcd9b46e2008-11-04 14:56:14 +00001990 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
1991 const PointerType *PT = Super->getType()->getAsPointerType();
Chris Lattner0d17f6f2008-06-21 18:04:54 +00001992 assert(PT);
1993 ObjCInterfaceType *IT = cast<ObjCInterfaceType>(PT->getPointeeType());
1994 return IT->getDecl();
1995 }
1996 return 0;
Steve Naroff874e2322007-11-15 10:28:18 +00001997}
1998
1999// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002000QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002001 if (!SuperStructDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002002 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002003 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002004 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002005 QualType FieldTypes[2];
2006
2007 // struct objc_object *receiver;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002008 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002009 // struct objc_class *super;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002010 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff874e2322007-11-15 10:28:18 +00002011 // Create fields
2012 FieldDecl *FieldDecls[2];
2013
2014 for (unsigned i = 0; i < 2; ++i)
Chris Lattnerb048c982008-04-06 04:47:34 +00002015 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00002016 FieldTypes[i]);
Steve Naroff874e2322007-11-15 10:28:18 +00002017
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002018 SuperStructDecl->defineBody(*Context, FieldDecls, 4);
Steve Naroff874e2322007-11-15 10:28:18 +00002019 }
2020 return Context->getTagDeclType(SuperStructDecl);
2021}
2022
Steve Naroffb29b4272008-04-14 22:03:09 +00002023QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002024 if (!ConstantStringDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002025 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002026 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002027 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002028 QualType FieldTypes[4];
2029
2030 // struct objc_object *receiver;
2031 FieldTypes[0] = Context->getObjCIdType();
2032 // int flags;
2033 FieldTypes[1] = Context->IntTy;
2034 // char *str;
2035 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2036 // long length;
2037 FieldTypes[3] = Context->LongTy;
2038 // Create fields
Steve Naroff9630ec52008-03-27 22:59:54 +00002039 FieldDecl *FieldDecls[4];
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002040
2041 for (unsigned i = 0; i < 4; ++i)
Chris Lattnerb048c982008-04-06 04:47:34 +00002042 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00002043 FieldTypes[i]);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002044
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002045 ConstantStringDecl->defineBody(*Context, FieldDecls, 4);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002046 }
2047 return Context->getTagDeclType(ConstantStringDecl);
2048}
2049
Steve Naroffb29b4272008-04-14 22:03:09 +00002050Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002051 if (!SelGetUidFunctionDecl)
2052 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002053 if (!MsgSendFunctionDecl)
2054 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002055 if (!MsgSendSuperFunctionDecl)
2056 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002057 if (!MsgSendStretFunctionDecl)
2058 SynthMsgSendStretFunctionDecl();
2059 if (!MsgSendSuperStretFunctionDecl)
2060 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002061 if (!MsgSendFpretFunctionDecl)
2062 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002063 if (!GetClassFunctionDecl)
2064 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002065 if (!GetMetaClassFunctionDecl)
2066 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002067
Steve Naroff874e2322007-11-15 10:28:18 +00002068 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002069 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2070 // May need to use objc_msgSend_stret() as well.
2071 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002072 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002073 QualType resultType = mDecl->getResultType();
Chris Lattner8b51fd72008-07-26 22:36:27 +00002074 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002075 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002076 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002077 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002078 }
Steve Naroff874e2322007-11-15 10:28:18 +00002079
Steve Naroff934f2762007-10-24 22:48:43 +00002080 // Synthesize a call to objc_msgSend().
2081 llvm::SmallVector<Expr*, 8> MsgExprs;
2082 IdentifierInfo *clsName = Exp->getClassName();
2083
2084 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2085 if (clsName) { // class message.
Steve Narofffc93d522008-07-24 19:44:33 +00002086 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2087 // the 'super' idiom within a class method.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002088 if (!strcmp(clsName->getName(), "super")) {
2089 MsgSendFlavor = MsgSendSuperFunctionDecl;
2090 if (MsgSendStretFlavor)
2091 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2092 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2093
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002094 ObjCInterfaceDecl *SuperDecl =
Steve Naroff54055232008-10-27 17:20:55 +00002095 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002096
2097 llvm::SmallVector<Expr*, 4> InitExprs;
2098
2099 // set the receiver to self, the first argument to all methods.
Chris Lattner41110242008-06-17 18:05:57 +00002100 InitExprs.push_back(new DeclRefExpr(
Steve Naroff54055232008-10-27 17:20:55 +00002101 CurMethodDef->getSelfDecl(),
Chris Lattner41110242008-06-17 18:05:57 +00002102 Context->getObjCIdType(),
2103 SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002104 llvm::SmallVector<Expr*, 8> ClsExprs;
2105 QualType argType = Context->getPointerType(Context->CharTy);
2106 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2107 SuperDecl->getIdentifier()->getLength(),
2108 false, argType, SourceLocation(),
2109 SourceLocation()));
2110 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2111 &ClsExprs[0],
2112 ClsExprs.size());
2113 // To turn off a warning, type-cast to 'id'
Douglas Gregor49badde2008-10-27 19:41:14 +00002114 InitExprs.push_back( // set 'super class', using objc_getClass().
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002115 new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002116 Cls, Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002117 SourceLocation(), SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002118 // struct objc_super
2119 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00002120 Expr *SuperRep;
Steve Naroffc0a123c2008-03-11 17:37:02 +00002121
Steve Naroff23f41272008-03-11 18:14:26 +00002122 if (LangOpts.Microsoft) {
2123 SynthSuperContructorFunctionDecl();
2124 // Simulate a contructor call...
2125 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2126 superType, SourceLocation());
2127 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2128 superType, SourceLocation());
2129 } else {
2130 // (struct objc_super) { <exprs from above> }
2131 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2132 &InitExprs[0], InitExprs.size(),
Chris Lattner418f6c72008-10-26 23:43:26 +00002133 SourceLocation(), false);
2134 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE,
2135 false);
Steve Naroff23f41272008-03-11 18:14:26 +00002136 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002137 // struct objc_super *
2138 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2139 Context->getPointerType(SuperRep->getType()),
2140 SourceLocation());
2141 MsgExprs.push_back(Unop);
2142 } else {
2143 llvm::SmallVector<Expr*, 8> ClsExprs;
2144 QualType argType = Context->getPointerType(Context->CharTy);
2145 ClsExprs.push_back(new StringLiteral(clsName->getName(),
2146 clsName->getLength(),
2147 false, argType, SourceLocation(),
2148 SourceLocation()));
2149 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2150 &ClsExprs[0],
2151 ClsExprs.size());
2152 MsgExprs.push_back(Cls);
2153 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002154 } else { // instance message.
2155 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00002156
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002157 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00002158 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002159 if (MsgSendStretFlavor)
2160 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00002161 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2162
2163 llvm::SmallVector<Expr*, 4> InitExprs;
2164
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002165 InitExprs.push_back(
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002166 new CStyleCastExpr(Context->getObjCIdType(),
Steve Naroff54055232008-10-27 17:20:55 +00002167 new DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Narofff616ebb2008-07-16 22:35:27 +00002168 Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002169 SourceLocation()),
2170 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002171 SourceLocation(), SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00002172
2173 llvm::SmallVector<Expr*, 8> ClsExprs;
2174 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002175 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2176 SuperDecl->getIdentifier()->getLength(),
Steve Naroff874e2322007-11-15 10:28:18 +00002177 false, argType, SourceLocation(),
2178 SourceLocation()));
2179 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002180 &ClsExprs[0],
2181 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00002182 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002183 InitExprs.push_back(
Douglas Gregor49badde2008-10-27 19:41:14 +00002184 // set 'super class', using objc_getClass().
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002185 new CStyleCastExpr(Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002186 Cls, Context->getObjCIdType(), SourceLocation(), SourceLocation()));
Steve Naroff874e2322007-11-15 10:28:18 +00002187 // struct objc_super
2188 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00002189 Expr *SuperRep;
2190
2191 if (LangOpts.Microsoft) {
2192 SynthSuperContructorFunctionDecl();
2193 // Simulate a contructor call...
2194 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2195 superType, SourceLocation());
2196 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2197 superType, SourceLocation());
2198 } else {
2199 // (struct objc_super) { <exprs from above> }
2200 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2201 &InitExprs[0], InitExprs.size(),
Chris Lattner418f6c72008-10-26 23:43:26 +00002202 SourceLocation(), false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002203 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
2204 }
Steve Naroff874e2322007-11-15 10:28:18 +00002205 // struct objc_super *
2206 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2207 Context->getPointerType(SuperRep->getType()),
2208 SourceLocation());
2209 MsgExprs.push_back(Unop);
2210 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002211 // Remove all type-casts because it may contain objc-style types; e.g.
2212 // Foo<Proto> *.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002213 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002214 recExpr = CE->getSubExpr();
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002215 recExpr = new CStyleCastExpr(Context->getObjCIdType(), recExpr,
Douglas Gregor49badde2008-10-27 19:41:14 +00002216 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002217 SourceLocation(), SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00002218 MsgExprs.push_back(recExpr);
2219 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002220 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00002221 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002222 llvm::SmallVector<Expr*, 8> SelExprs;
2223 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner077bf5e2008-11-24 03:33:13 +00002224 SelExprs.push_back(new StringLiteral(Exp->getSelector().getAsString().c_str(),
2225 Exp->getSelector().getAsString().size(),
Steve Naroff934f2762007-10-24 22:48:43 +00002226 false, argType, SourceLocation(),
2227 SourceLocation()));
2228 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2229 &SelExprs[0], SelExprs.size());
2230 MsgExprs.push_back(SelExp);
2231
2232 // Now push any user supplied arguments.
2233 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002234 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002235 // Make all implicit casts explicit...ICE comes in handy:-)
2236 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2237 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregor49badde2008-10-27 19:41:14 +00002238 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002239 ? Context->getObjCIdType()
Douglas Gregor49badde2008-10-27 19:41:14 +00002240 : ICE->getType();
Steve Naroffb2f9e512008-11-03 23:29:32 +00002241 userExpr = new CStyleCastExpr(type, userExpr, type, SourceLocation(), SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002242 }
2243 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002244 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002245 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002246 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002247 userExpr = CE->getSubExpr();
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002248 userExpr = new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002249 userExpr, Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002250 SourceLocation(), SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002251 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00002252 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002253 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00002254 // We've transferred the ownership to MsgExprs. Null out the argument in
2255 // the original expression, since we will delete it below.
2256 Exp->setArg(i, 0);
2257 }
Steve Naroffab972d32007-11-04 22:37:50 +00002258 // Generate the funky cast.
2259 CastExpr *cast;
2260 llvm::SmallVector<QualType, 8> ArgTypes;
2261 QualType returnType;
2262
2263 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002264 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2265 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2266 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002267 ArgTypes.push_back(Context->getObjCIdType());
2268 ArgTypes.push_back(Context->getObjCSelType());
2269 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002270 // Push any user argument types.
Chris Lattner58cce3b2008-03-16 01:07:14 +00002271 for (unsigned i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002272 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
2273 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002274 : mDecl->getParamDecl(i)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00002275 // Make sure we convert "t (^)(...)" to "t (*)(...)".
2276 if (isBlockPointerType(t)) {
2277 const BlockPointerType *BPT = t->getAsBlockPointerType();
2278 t = Context->getPointerType(BPT->getPointeeType());
2279 }
Steve Naroff352336b2007-11-05 14:36:37 +00002280 ArgTypes.push_back(t);
2281 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002282 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
2283 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00002284 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002285 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002286 }
2287 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002288 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00002289
2290 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002291 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
2292 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002293
2294 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2295 // If we don't do this cast, we get the following bizarre warning/note:
2296 // xx.m:13: warning: function called through a non-compatible type
2297 // xx.m:13: note: if this code is reached, the program will abort
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002298 cast = new CStyleCastExpr(Context->getPointerType(Context->VoidTy), DRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002299 Context->getPointerType(Context->VoidTy),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002300 SourceLocation(), SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00002301
Steve Naroffab972d32007-11-04 22:37:50 +00002302 // Now do the "normal" pointer to function cast.
2303 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002304 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00002305 // If we don't have a method decl, force a variadic cast.
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002306 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Naroffab972d32007-11-04 22:37:50 +00002307 castType = Context->getPointerType(castType);
Steve Naroffb2f9e512008-11-03 23:29:32 +00002308 cast = new CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002309
2310 // Don't forget the parens to enforce the proper binding.
2311 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2312
2313 const FunctionType *FT = msgSendType->getAsFunctionType();
2314 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2315 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002316 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002317 if (MsgSendStretFlavor) {
2318 // We have the method which returns a struct/union. Must also generate
2319 // call to objc_msgSend_stret and hang both varieties on a conditional
2320 // expression which dictate which one to envoke depending on size of
2321 // method's return type.
2322
2323 // Create a reference to the objc_msgSend_stret() declaration.
2324 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
2325 SourceLocation());
2326 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002327 cast = new CStyleCastExpr(Context->getPointerType(Context->VoidTy), STDRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002328 Context->getPointerType(Context->VoidTy),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002329 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002330 // Now do the "normal" pointer to function cast.
2331 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002332 &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002333 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002334 castType = Context->getPointerType(castType);
Steve Naroffb2f9e512008-11-03 23:29:32 +00002335 cast = new CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002336
2337 // Don't forget the parens to enforce the proper binding.
2338 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2339
2340 FT = msgSendType->getAsFunctionType();
2341 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2342 FT->getResultType(), SourceLocation());
2343
2344 // Build sizeof(returnType)
Sebastian Redl05189992008-11-11 17:56:53 +00002345 SizeOfAlignOfExpr *sizeofExpr = new SizeOfAlignOfExpr(true, true,
2346 returnType.getAsOpaquePtr(),
2347 Context->getSizeType(),
2348 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002349 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2350 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2351 // For X86 it is more complicated and some kind of target specific routine
2352 // is needed to decide what to do.
Chris Lattner98be4942008-03-05 18:54:05 +00002353 unsigned IntSize =
2354 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002355 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2356 Context->IntTy,
2357 SourceLocation());
2358 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2359 BinaryOperator::LE,
2360 Context->IntTy,
2361 SourceLocation());
2362 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2363 ConditionalOperator *CondExpr =
2364 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002365 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002366 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002367 return ReplacingStmt;
2368}
2369
Steve Naroffb29b4272008-04-14 22:03:09 +00002370Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002371 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff80c28552008-10-27 20:54:44 +00002372
Steve Naroff934f2762007-10-24 22:48:43 +00002373 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002374 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff934f2762007-10-24 22:48:43 +00002375
Chris Lattnere64b7772007-10-24 16:57:36 +00002376 delete Exp;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002377 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002378}
2379
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002380/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2381/// call to objc_getProtocol("proto-name").
Steve Naroffb29b4272008-04-14 22:03:09 +00002382Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002383 if (!GetProtocolFunctionDecl)
2384 SynthGetProtocolFunctionDecl();
2385 // Create a call to objc_getProtocol("ProtocolName").
2386 llvm::SmallVector<Expr*, 8> ProtoExprs;
2387 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner8ec03f52008-11-24 03:54:41 +00002388 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getNameAsCString(),
2389 strlen(Exp->getProtocol()->getNameAsCString()),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002390 false, argType, SourceLocation(),
2391 SourceLocation()));
2392 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2393 &ProtoExprs[0],
2394 ProtoExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002395 ReplaceStmt(Exp, ProtoExp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002396 delete Exp;
2397 return ProtoExp;
2398
2399}
2400
Steve Naroffbaf58c32008-05-31 14:15:04 +00002401bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
2402 const char *endBuf) {
2403 while (startBuf < endBuf) {
2404 if (*startBuf == '#') {
2405 // Skip whitespace.
2406 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2407 ;
2408 if (!strncmp(startBuf, "if", strlen("if")) ||
2409 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2410 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2411 !strncmp(startBuf, "define", strlen("define")) ||
2412 !strncmp(startBuf, "undef", strlen("undef")) ||
2413 !strncmp(startBuf, "else", strlen("else")) ||
2414 !strncmp(startBuf, "elif", strlen("elif")) ||
2415 !strncmp(startBuf, "endif", strlen("endif")) ||
2416 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2417 !strncmp(startBuf, "include", strlen("include")) ||
2418 !strncmp(startBuf, "import", strlen("import")) ||
2419 !strncmp(startBuf, "include_next", strlen("include_next")))
2420 return true;
2421 }
2422 startBuf++;
2423 }
2424 return false;
2425}
2426
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002427/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002428/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00002429void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002430 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002431 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Chris Lattner8ec03f52008-11-24 03:54:41 +00002432 assert(CDecl->getNameAsCString() &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002433 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002434 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002435 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002436 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002437 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002438 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00002439 SourceLocation LocStart = CDecl->getLocStart();
2440 SourceLocation LocEnd = CDecl->getLocEnd();
2441
2442 const char *startBuf = SM->getCharacterData(LocStart);
2443 const char *endBuf = SM->getCharacterData(LocEnd);
Steve Naroffbaf58c32008-05-31 14:15:04 +00002444
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002445 // If no ivars and no root or if its root, directly or indirectly,
2446 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002447 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2448 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002449 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattneraadaf782008-01-31 19:51:04 +00002450 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002451 return;
2452 }
2453
2454 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002455 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002456 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002457 Result += CDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002458 if (LangOpts.Microsoft)
2459 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00002460
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002461 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002462 const char *cursor = strchr(startBuf, '{');
2463 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002464 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00002465 // If the buffer contains preprocessor directives, we do more fine-grained
2466 // rewrites. This is intended to fix code that looks like (which occurs in
2467 // NSURL.h, for example):
2468 //
2469 // #ifdef XYZ
2470 // @interface Foo : NSObject
2471 // #else
2472 // @interface FooBar : NSObject
2473 // #endif
2474 // {
2475 // int i;
2476 // }
2477 // @end
2478 //
2479 // This clause is segregated to avoid breaking the common case.
2480 if (BufferContainsPPDirectives(startBuf, cursor)) {
2481 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
2482 CDecl->getClassLoc();
2483 const char *endHeader = SM->getCharacterData(L);
2484 endHeader += Lexer::MeasureTokenLength(L, *SM);
2485
Chris Lattner3db6cae2008-07-21 18:19:38 +00002486 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00002487 // advance to the end of the referenced protocols.
2488 while (endHeader < cursor && *endHeader != '>') endHeader++;
2489 endHeader++;
2490 }
2491 // rewrite the original header
2492 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2493 } else {
2494 // rewrite the original header *without* disturbing the '{'
2495 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
2496 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002497 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002498 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002499 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002500 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002501 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00002502 Result += "_IVARS;\n";
Steve Narofffea763e82007-11-14 19:25:57 +00002503
2504 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002505 SourceLocation OnePastCurly =
2506 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2507 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002508 }
2509 cursor++; // past '{'
2510
2511 // Now comment out any visibility specifiers.
2512 while (cursor < endBuf) {
2513 if (*cursor == '@') {
2514 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002515 // Skip whitespace.
2516 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2517 /*scan*/;
2518
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002519 // FIXME: presence of @public, etc. inside comment results in
2520 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002521 if (!strncmp(cursor, "public", strlen("public")) ||
2522 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00002523 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002524 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002525 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002526 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002527 // FIXME: If there are cases where '<' is used in ivar declaration part
2528 // of user code, then scan the ivar list and use needToScanForQualifiers
2529 // for type checking.
2530 else if (*cursor == '<') {
2531 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002532 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002533 cursor = strchr(cursor, '>');
2534 cursor++;
2535 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002536 InsertText(atLoc, " */", 3);
Steve Naroffced80a82008-10-30 12:09:33 +00002537 } else if (*cursor == '^') { // rewrite block specifier.
2538 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2539 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002540 }
Steve Narofffea763e82007-11-14 19:25:57 +00002541 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002542 }
Steve Narofffea763e82007-11-14 19:25:57 +00002543 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002544 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00002545 } else { // we don't have any instance variables - insert super struct.
2546 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2547 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002548 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002549 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002550 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00002551 Result += "_IVARS;\n};\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00002552 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002553 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002554 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002555 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00002556 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002557}
2558
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002559// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002560/// class methods.
Steve Naroffb29b4272008-04-14 22:03:09 +00002561void RewriteObjC::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002562 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002563 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002564 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002565 const char *ClassName,
2566 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002567 if (MethodBegin == MethodEnd) return;
2568
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002569 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002570 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002571 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002572 SEL _cmd;
2573 char *method_types;
2574 void *_imp;
2575 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002576 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002577 Result += "\nstruct _objc_method {\n";
2578 Result += "\tSEL _cmd;\n";
2579 Result += "\tchar *method_types;\n";
2580 Result += "\tvoid *_imp;\n";
2581 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002582
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002583 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002584 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002585
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002586 // Build _objc_method_list for class's methods if needed
Steve Naroff946a6932008-03-11 00:12:29 +00002587
2588 /* struct {
2589 struct _objc_method_list *next_method;
2590 int method_count;
2591 struct _objc_method method_list[];
2592 }
2593 */
2594 Result += "\nstatic struct {\n";
2595 Result += "\tstruct _objc_method_list *next_method;\n";
2596 Result += "\tint method_count;\n";
2597 Result += "\tstruct _objc_method method_list[";
2598 Result += utostr(MethodEnd-MethodBegin);
2599 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002600 Result += prefix;
2601 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2602 Result += "_METHODS_";
2603 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002604 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002605 Result += IsInstanceMethod ? "inst" : "cls";
2606 Result += "_meth\")))= ";
2607 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002608
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002609 Result += "\t,{{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002610 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002611 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002612 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002613 Result += "\", \"";
2614 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002615 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002616 Result += MethodInternalNames[*MethodBegin];
2617 Result += "}\n";
2618 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2619 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002620 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002621 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002622 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002623 Result += "\", \"";
2624 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002625 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002626 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002627 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002628 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002629 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002630}
2631
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002632/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00002633void RewriteObjC::
2634RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
2635 const char *prefix,
2636 const char *ClassName,
2637 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002638 static bool objc_protocol_methods = false;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002639 if (Protocols.empty()) return;
2640
2641 for (unsigned i = 0; i != Protocols.size(); i++) {
2642 ObjCProtocolDecl *PDecl = Protocols[i];
2643 // Output struct protocol_methods holder of method selector and type.
2644 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
2645 /* struct protocol_methods {
2646 SEL _cmd;
2647 char *method_types;
2648 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002649 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002650 Result += "\nstruct protocol_methods {\n";
2651 Result += "\tSEL _cmd;\n";
2652 Result += "\tchar *method_types;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002653 Result += "};\n";
Steve Narofffbfe8252008-05-06 18:26:51 +00002654
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002655 objc_protocol_methods = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002656 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002657 // Do not synthesize the protocol more than once.
2658 if (ObjCSynthesizedProtocols.count(PDecl))
2659 continue;
2660
2661 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2662 unsigned NumMethods = PDecl->getNumInstanceMethods();
2663 /* struct _objc_protocol_method_list {
2664 int protocol_method_count;
2665 struct protocol_methods protocols[];
2666 }
2667 */
2668 Result += "\nstatic struct {\n";
2669 Result += "\tint protocol_method_count;\n";
2670 Result += "\tstruct protocol_methods protocols[";
2671 Result += utostr(NumMethods);
2672 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002673 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002674 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
2675 "{\n\t" + utostr(NumMethods) + "\n";
2676
2677 // Output instance methods declared in this protocol.
2678 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
2679 E = PDecl->instmeth_end(); I != E; ++I) {
2680 if (I == PDecl->instmeth_begin())
2681 Result += "\t ,{{(SEL)\"";
2682 else
2683 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002684 Result += (*I)->getSelector().getAsString().c_str();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002685 std::string MethodTypeString;
2686 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2687 Result += "\", \"";
2688 Result += MethodTypeString;
2689 Result += "\"}\n";
2690 }
2691 Result += "\t }\n};\n";
2692 }
2693
2694 // Output class methods declared in this protocol.
2695 int NumMethods = PDecl->getNumClassMethods();
2696 if (NumMethods > 0) {
2697 /* struct _objc_protocol_method_list {
2698 int protocol_method_count;
2699 struct protocol_methods protocols[];
2700 }
2701 */
2702 Result += "\nstatic struct {\n";
2703 Result += "\tint protocol_method_count;\n";
2704 Result += "\tstruct protocol_methods protocols[";
2705 Result += utostr(NumMethods);
2706 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002707 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002708 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2709 "{\n\t";
2710 Result += utostr(NumMethods);
2711 Result += "\n";
2712
2713 // Output instance methods declared in this protocol.
2714 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
2715 E = PDecl->classmeth_end(); I != E; ++I) {
2716 if (I == PDecl->classmeth_begin())
2717 Result += "\t ,{{(SEL)\"";
2718 else
2719 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002720 Result += (*I)->getSelector().getAsString().c_str();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002721 std::string MethodTypeString;
2722 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2723 Result += "\", \"";
2724 Result += MethodTypeString;
2725 Result += "\"}\n";
2726 }
2727 Result += "\t }\n};\n";
2728 }
2729
2730 // Output:
2731 /* struct _objc_protocol {
2732 // Objective-C 1.0 extensions
2733 struct _objc_protocol_extension *isa;
2734 char *protocol_name;
2735 struct _objc_protocol **protocol_list;
2736 struct _objc_protocol_method_list *instance_methods;
2737 struct _objc_protocol_method_list *class_methods;
2738 };
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002739 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002740 static bool objc_protocol = false;
2741 if (!objc_protocol) {
2742 Result += "\nstruct _objc_protocol {\n";
2743 Result += "\tstruct _objc_protocol_extension *isa;\n";
2744 Result += "\tchar *protocol_name;\n";
2745 Result += "\tstruct _objc_protocol **protocol_list;\n";
2746 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2747 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2748 Result += "};\n";
2749
2750 objc_protocol = true;
2751 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002752
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002753 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002754 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002755 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
2756 "{\n\t0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002757 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002758 Result += "\", 0, ";
2759 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2760 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002761 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002762 Result += ", ";
2763 }
2764 else
2765 Result += "0, ";
2766 if (PDecl->getNumClassMethods() > 0) {
2767 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002768 Result += PDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002769 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002770 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002771 else
2772 Result += "0\n";
2773 Result += "};\n";
2774
2775 // Mark this protocol as having been generated.
2776 if (!ObjCSynthesizedProtocols.insert(PDecl))
2777 assert(false && "protocol already synthesized");
2778 }
2779 // Output the top lovel protocol meta-data for the class.
2780 /* struct _objc_protocol_list {
2781 struct _objc_protocol_list *next;
2782 int protocol_count;
2783 struct _objc_protocol *class_protocols[];
2784 }
2785 */
2786 Result += "\nstatic struct {\n";
2787 Result += "\tstruct _objc_protocol_list *next;\n";
2788 Result += "\tint protocol_count;\n";
2789 Result += "\tstruct _objc_protocol *class_protocols[";
2790 Result += utostr(Protocols.size());
2791 Result += "];\n} _OBJC_";
2792 Result += prefix;
2793 Result += "_PROTOCOLS_";
2794 Result += ClassName;
2795 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2796 "{\n\t0, ";
2797 Result += utostr(Protocols.size());
2798 Result += "\n";
2799
2800 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002801 Result += Protocols[0]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002802 Result += " \n";
2803
2804 for (unsigned i = 1; i != Protocols.size(); i++) {
2805 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002806 Result += Protocols[i]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002807 Result += "\n";
2808 }
2809 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002810}
2811
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002812/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002813/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00002814void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002815 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002816 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002817 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002818 ObjCCategoryDecl *CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002819 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2820 CDecl = CDecl->getNextClassCategory())
2821 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2822 break;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002823
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002824 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00002825 FullCategoryName += '_';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002826 FullCategoryName += IDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00002827
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002828 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002829 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002830 true, "CATEGORY_", FullCategoryName.c_str(),
2831 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002832
2833 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002834 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002835 false, "CATEGORY_", FullCategoryName.c_str(),
2836 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002837
2838 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002839 // Null CDecl is case of a category implementation with no category interface
2840 if (CDecl)
Chris Lattner780f3292008-07-21 21:32:27 +00002841 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Chris Lattnereb44eee2007-12-23 01:40:15 +00002842 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002843
2844 /* struct _objc_category {
2845 char *category_name;
2846 char *class_name;
2847 struct _objc_method_list *instance_methods;
2848 struct _objc_method_list *class_methods;
2849 struct _objc_protocol_list *protocols;
2850 // Objective-C 1.0 extensions
2851 uint32_t size; // sizeof (struct _objc_category)
2852 struct _objc_property_list *instance_properties; // category's own
2853 // @property decl.
2854 };
2855 */
2856
2857 static bool objc_category = false;
2858 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002859 Result += "\nstruct _objc_category {\n";
2860 Result += "\tchar *category_name;\n";
2861 Result += "\tchar *class_name;\n";
2862 Result += "\tstruct _objc_method_list *instance_methods;\n";
2863 Result += "\tstruct _objc_method_list *class_methods;\n";
2864 Result += "\tstruct _objc_protocol_list *protocols;\n";
2865 Result += "\tunsigned int size;\n";
2866 Result += "\tstruct _objc_property_list *instance_properties;\n";
2867 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002868 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002869 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002870 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2871 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002872 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002873 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002874 Result += "\"\n\t, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002875 Result += ClassDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002876 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002877
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002878 if (IDecl->getNumInstanceMethods() > 0) {
2879 Result += "\t, (struct _objc_method_list *)"
2880 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2881 Result += FullCategoryName;
2882 Result += "\n";
2883 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002884 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002885 Result += "\t, 0\n";
2886 if (IDecl->getNumClassMethods() > 0) {
2887 Result += "\t, (struct _objc_method_list *)"
2888 "&_OBJC_CATEGORY_CLASS_METHODS_";
2889 Result += FullCategoryName;
2890 Result += "\n";
2891 }
2892 else
2893 Result += "\t, 0\n";
2894
Chris Lattner780f3292008-07-21 21:32:27 +00002895 if (CDecl && !CDecl->getReferencedProtocols().empty()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002896 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2897 Result += FullCategoryName;
2898 Result += "\n";
2899 }
2900 else
2901 Result += "\t, 0\n";
2902 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002903}
2904
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002905/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2906/// ivar offset.
Steve Naroffb29b4272008-04-14 22:03:09 +00002907void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002908 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002909 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00002910 if (ivar->isBitField()) {
2911 // FIXME: The hack below doesn't work for bitfields. For now, we simply
2912 // place all bitfields at offset 0.
2913 Result += "0";
2914 } else {
2915 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002916 Result += IDecl->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00002917 if (LangOpts.Microsoft)
2918 Result += "_IMPL";
2919 Result += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002920 Result += ivar->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00002921 Result += ")";
2922 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002923}
2924
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002925//===----------------------------------------------------------------------===//
2926// Meta Data Emission
2927//===----------------------------------------------------------------------===//
2928
Steve Naroffb29b4272008-04-14 22:03:09 +00002929void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002930 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002931 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002932
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002933 // Explictly declared @interface's are already synthesized.
2934 if (CDecl->ImplicitInterfaceDecl()) {
2935 // FIXME: Implementation of a class with no @interface (legacy) doese not
2936 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002937 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002938 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002939
Chris Lattnerbe6df082007-12-12 07:56:42 +00002940 // Build _objc_ivar_list metadata for classes ivars if needed
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002941 unsigned NumIvars = !IDecl->ivar_empty()
2942 ? IDecl->ivar_size()
2943 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002944 if (NumIvars > 0) {
2945 static bool objc_ivar = false;
2946 if (!objc_ivar) {
2947 /* struct _objc_ivar {
2948 char *ivar_name;
2949 char *ivar_type;
2950 int ivar_offset;
2951 };
2952 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002953 Result += "\nstruct _objc_ivar {\n";
2954 Result += "\tchar *ivar_name;\n";
2955 Result += "\tchar *ivar_type;\n";
2956 Result += "\tint ivar_offset;\n";
2957 Result += "};\n";
2958
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002959 objc_ivar = true;
2960 }
2961
Steve Naroff946a6932008-03-11 00:12:29 +00002962 /* struct {
2963 int ivar_count;
2964 struct _objc_ivar ivar_list[nIvars];
2965 };
2966 */
2967 Result += "\nstatic struct {\n";
2968 Result += "\tint ivar_count;\n";
2969 Result += "\tstruct _objc_ivar ivar_list[";
2970 Result += utostr(NumIvars);
2971 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002972 Result += IDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00002973 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002974 "{\n\t";
2975 Result += utostr(NumIvars);
2976 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002977
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002978 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002979 if (!IDecl->ivar_empty()) {
Chris Lattnerbe6df082007-12-12 07:56:42 +00002980 IVI = IDecl->ivar_begin();
2981 IVE = IDecl->ivar_end();
2982 } else {
2983 IVI = CDecl->ivar_begin();
2984 IVE = CDecl->ivar_end();
2985 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002986 Result += "\t,{{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002987 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002988 Result += "\", \"";
2989 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002990 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002991 Result += StrEncoding;
2992 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002993 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002994 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002995 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002996 Result += "\t ,{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002997 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002998 Result += "\", \"";
2999 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003000 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003001 Result += StrEncoding;
3002 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003003 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003004 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003005 }
3006
3007 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003008 }
3009
3010 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003011 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003012 true, "", IDecl->getNameAsCString(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003013
3014 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003015 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003016 false, "", IDecl->getNameAsCString(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003017
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003018 // Protocols referenced in class declaration?
Chris Lattner780f3292008-07-21 21:32:27 +00003019 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003020 "CLASS", CDecl->getNameAsCString(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003021
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003022
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003023 // Declaration of class/meta-class metadata
3024 /* struct _objc_class {
3025 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003026 const char *super_class_name;
3027 char *name;
3028 long version;
3029 long info;
3030 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003031 struct _objc_ivar_list *ivars;
3032 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003033 struct objc_cache *cache;
3034 struct objc_protocol_list *protocols;
3035 const char *ivar_layout;
3036 struct _objc_class_ext *ext;
3037 };
3038 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003039 static bool objc_class = false;
3040 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003041 Result += "\nstruct _objc_class {\n";
3042 Result += "\tstruct _objc_class *isa;\n";
3043 Result += "\tconst char *super_class_name;\n";
3044 Result += "\tchar *name;\n";
3045 Result += "\tlong version;\n";
3046 Result += "\tlong info;\n";
3047 Result += "\tlong instance_size;\n";
3048 Result += "\tstruct _objc_ivar_list *ivars;\n";
3049 Result += "\tstruct _objc_method_list *methods;\n";
3050 Result += "\tstruct objc_cache *cache;\n";
3051 Result += "\tstruct _objc_protocol_list *protocols;\n";
3052 Result += "\tconst char *ivar_layout;\n";
3053 Result += "\tstruct _objc_class_ext *ext;\n";
3054 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003055 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003056 }
3057
3058 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003059 ObjCInterfaceDecl *RootClass = 0;
3060 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003061 while (SuperClass) {
3062 RootClass = SuperClass;
3063 SuperClass = SuperClass->getSuperClass();
3064 }
3065 SuperClass = CDecl->getSuperClass();
3066
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003067 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003068 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003069 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003070 "{\n\t(struct _objc_class *)\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003071 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003072 Result += "\"";
3073
3074 if (SuperClass) {
3075 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003076 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003077 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003078 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003079 Result += "\"";
3080 }
3081 else {
3082 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003083 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003084 Result += "\"";
3085 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003086 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003087 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003088 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffb26d7132007-12-05 21:49:40 +00003089 if (IDecl->getNumClassMethods() > 0) {
Steve Naroff23f41272008-03-11 18:14:26 +00003090 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003091 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003092 Result += "\n";
3093 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003094 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003095 Result += ", 0\n";
Chris Lattner3db6cae2008-07-21 18:19:38 +00003096 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003097 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003098 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003099 Result += ",0,0\n";
3100 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003101 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003102 Result += "\t,0,0,0,0\n";
3103 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003104
3105 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003106 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003107 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003108 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003109 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003110 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003111 if (SuperClass) {
3112 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003113 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003114 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003115 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003116 Result += "\"";
3117 }
3118 else {
3119 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003120 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003121 Result += "\"";
3122 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003123 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003124 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003125 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003126 Result += ",0";
3127 else {
3128 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003129 Result += ",sizeof(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003130 Result += CDecl->getNameAsString();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003131 if (LangOpts.Microsoft)
3132 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003133 Result += ")";
3134 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003135 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00003136 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003137 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003138 Result += "\n\t";
3139 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003140 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003141 Result += ",0";
3142 if (IDecl->getNumInstanceMethods() > 0) {
Steve Naroff946a6932008-03-11 00:12:29 +00003143 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003144 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003145 Result += ", 0\n\t";
3146 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003147 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003148 Result += ",0,0";
Chris Lattner3db6cae2008-07-21 18:19:38 +00003149 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003150 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003151 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003152 Result += ", 0,0\n";
3153 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003154 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003155 Result += ",0,0,0\n";
3156 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003157}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003158
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003159/// RewriteImplementations - This routine rewrites all method implementations
3160/// and emits meta-data.
3161
Steve Narofface66252008-11-13 20:07:04 +00003162void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003163 int ClsDefCount = ClassImplementation.size();
3164 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003165
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003166 // Rewrite implemented methods
3167 for (int i = 0; i < ClsDefCount; i++)
3168 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003169
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003170 for (int i = 0; i < CatDefCount; i++)
3171 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00003172}
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003173
Steve Narofface66252008-11-13 20:07:04 +00003174void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3175 int ClsDefCount = ClassImplementation.size();
3176 int CatDefCount = CategoryImplementation.size();
3177
Steve Naroff5df5b762008-05-07 21:23:49 +00003178 // This is needed for determining instance variable offsets.
Steve Naroffa11440b2008-08-05 18:47:23 +00003179 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003180 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003181 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003182 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003183
3184 // For each implemented category, write out all its meta data.
3185 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003186 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003187
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003188 // Write objc_symtab metadata
3189 /*
3190 struct _objc_symtab
3191 {
3192 long sel_ref_cnt;
3193 SEL *refs;
3194 short cls_def_cnt;
3195 short cat_def_cnt;
3196 void *defs[cls_def_cnt + cat_def_cnt];
3197 };
3198 */
3199
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003200 Result += "\nstruct _objc_symtab {\n";
3201 Result += "\tlong sel_ref_cnt;\n";
3202 Result += "\tSEL *refs;\n";
3203 Result += "\tshort cls_def_cnt;\n";
3204 Result += "\tshort cat_def_cnt;\n";
3205 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3206 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003207
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003208 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00003209 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003210 Result += "\t0, 0, " + utostr(ClsDefCount)
3211 + ", " + utostr(CatDefCount) + "\n";
3212 for (int i = 0; i < ClsDefCount; i++) {
3213 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003214 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003215 Result += "\n";
3216 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003217
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003218 for (int i = 0; i < CatDefCount; i++) {
3219 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003220 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003221 Result += "_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003222 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003223 Result += "\n";
3224 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003225
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003226 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003227
3228 // Write objc_module metadata
3229
3230 /*
3231 struct _objc_module {
3232 long version;
3233 long size;
3234 const char *name;
3235 struct _objc_symtab *symtab;
3236 }
3237 */
3238
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003239 Result += "\nstruct _objc_module {\n";
3240 Result += "\tlong version;\n";
3241 Result += "\tlong size;\n";
3242 Result += "\tconst char *name;\n";
3243 Result += "\tstruct _objc_symtab *symtab;\n";
3244 Result += "};\n\n";
3245 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00003246 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003247 Result += "\t" + utostr(OBJC_ABI_VERSION) +
3248 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003249 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003250
3251 if (LangOpts.Microsoft) {
3252 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00003253 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003254 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3255 Result += "&_OBJC_MODULES;\n";
3256 Result += "#pragma data_seg(pop)\n\n";
3257 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003258}
Chris Lattner311ff022007-10-16 22:36:42 +00003259
Steve Naroff54055232008-10-27 17:20:55 +00003260std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3261 const char *funcName,
3262 std::string Tag) {
3263 const FunctionType *AFT = CE->getFunctionType();
3264 QualType RT = AFT->getResultType();
3265 std::string StructRef = "struct " + Tag;
3266 std::string S = "static " + RT.getAsString() + " __" +
3267 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003268
Steve Naroff54055232008-10-27 17:20:55 +00003269 BlockDecl *BD = CE->getBlockDecl();
3270
3271 if (isa<FunctionTypeNoProto>(AFT)) {
3272 S += "()";
3273 } else if (BD->param_empty()) {
3274 S += "(" + StructRef + " *__cself)";
3275 } else {
3276 const FunctionTypeProto *FT = cast<FunctionTypeProto>(AFT);
3277 assert(FT && "SynthesizeBlockFunc: No function proto");
3278 S += '(';
3279 // first add the implicit argument.
3280 S += StructRef + " *__cself, ";
3281 std::string ParamStr;
3282 for (BlockDecl::param_iterator AI = BD->param_begin(),
3283 E = BD->param_end(); AI != E; ++AI) {
3284 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003285 ParamStr = (*AI)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003286 (*AI)->getType().getAsStringInternal(ParamStr);
3287 S += ParamStr;
3288 }
3289 if (FT->isVariadic()) {
3290 if (!BD->param_empty()) S += ", ";
3291 S += "...";
3292 }
3293 S += ')';
3294 }
3295 S += " {\n";
3296
3297 // Create local declarations to avoid rewriting all closure decl ref exprs.
3298 // First, emit a declaration for all "by ref" decls.
3299 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3300 E = BlockByRefDecls.end(); I != E; ++I) {
3301 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003302 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003303 Context->getPointerType((*I)->getType()).getAsStringInternal(Name);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003304 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Steve Naroff54055232008-10-27 17:20:55 +00003305 }
3306 // Next, emit a declaration for all "by copy" declarations.
3307 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3308 E = BlockByCopyDecls.end(); I != E; ++I) {
3309 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003310 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003311 // Handle nested closure invocation. For example:
3312 //
3313 // void (^myImportedClosure)(void);
3314 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3315 //
3316 // void (^anotherClosure)(void);
3317 // anotherClosure = ^(void) {
3318 // myImportedClosure(); // import and invoke the closure
3319 // };
3320 //
3321 if (isBlockPointerType((*I)->getType()))
3322 S += "struct __block_impl *";
3323 else
3324 (*I)->getType().getAsStringInternal(Name);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003325 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff54055232008-10-27 17:20:55 +00003326 }
3327 std::string RewrittenStr = RewrittenBlockExprs[CE];
3328 const char *cstr = RewrittenStr.c_str();
3329 while (*cstr++ != '{') ;
3330 S += cstr;
3331 S += "\n";
3332 return S;
3333}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003334
Steve Naroff54055232008-10-27 17:20:55 +00003335std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3336 const char *funcName,
3337 std::string Tag) {
3338 std::string StructRef = "struct " + Tag;
3339 std::string S = "static void __";
3340
3341 S += funcName;
3342 S += "_block_copy_" + utostr(i);
3343 S += "(" + StructRef;
3344 S += "*dst, " + StructRef;
3345 S += "*src) {";
3346 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3347 E = ImportedBlockDecls.end(); I != E; ++I) {
3348 S += "_Block_copy_assign(&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003349 S += (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003350 S += ", src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003351 S += (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003352 S += ");}";
3353 }
3354 S += "\nstatic void __";
3355 S += funcName;
3356 S += "_block_dispose_" + utostr(i);
3357 S += "(" + StructRef;
3358 S += "*src) {";
3359 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3360 E = ImportedBlockDecls.end(); I != E; ++I) {
3361 S += "_Block_destroy(src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003362 S += (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003363 S += ");";
3364 }
3365 S += "}\n";
3366 return S;
3367}
3368
3369std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3370 bool hasCopyDisposeHelpers) {
Steve Naroffced80a82008-10-30 12:09:33 +00003371 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00003372 std::string Constructor = " " + Tag;
3373
3374 S += " {\n struct __block_impl impl;\n";
3375
3376 if (hasCopyDisposeHelpers)
3377 S += " void *copy;\n void *dispose;\n";
3378
3379 Constructor += "(void *fp";
3380
3381 if (hasCopyDisposeHelpers)
3382 Constructor += ", void *copyHelp, void *disposeHelp";
3383
3384 if (BlockDeclRefs.size()) {
3385 // Output all "by copy" declarations.
3386 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3387 E = BlockByCopyDecls.end(); I != E; ++I) {
3388 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003389 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003390 std::string ArgName = "_" + FieldName;
3391 // Handle nested closure invocation. For example:
3392 //
3393 // void (^myImportedBlock)(void);
3394 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3395 //
3396 // void (^anotherBlock)(void);
3397 // anotherBlock = ^(void) {
3398 // myImportedBlock(); // import and invoke the closure
3399 // };
3400 //
3401 if (isBlockPointerType((*I)->getType())) {
3402 S += "struct __block_impl *";
3403 Constructor += ", void *" + ArgName;
3404 } else {
3405 (*I)->getType().getAsStringInternal(FieldName);
3406 (*I)->getType().getAsStringInternal(ArgName);
3407 Constructor += ", " + ArgName;
3408 }
3409 S += FieldName + ";\n";
3410 }
3411 // Output all "by ref" declarations.
3412 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3413 E = BlockByRefDecls.end(); I != E; ++I) {
3414 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003415 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003416 std::string ArgName = "_" + FieldName;
3417 // Handle nested closure invocation. For example:
3418 //
3419 // void (^myImportedBlock)(void);
3420 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3421 //
3422 // void (^anotherBlock)(void);
3423 // anotherBlock = ^(void) {
3424 // myImportedBlock(); // import and invoke the closure
3425 // };
3426 //
3427 if (isBlockPointerType((*I)->getType())) {
3428 S += "struct __block_impl *";
3429 Constructor += ", void *" + ArgName;
3430 } else {
3431 Context->getPointerType((*I)->getType()).getAsStringInternal(FieldName);
3432 Context->getPointerType((*I)->getType()).getAsStringInternal(ArgName);
3433 Constructor += ", " + ArgName;
3434 }
3435 S += FieldName + "; // by ref\n";
3436 }
3437 // Finish writing the constructor.
3438 // FIXME: handle NSConcreteGlobalBlock.
3439 Constructor += ", int flags=0) {\n";
3440 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3441 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3442
3443 if (hasCopyDisposeHelpers)
3444 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3445
3446 // Initialize all "by copy" arguments.
3447 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3448 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003449 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003450 Constructor += " ";
3451 if (isBlockPointerType((*I)->getType()))
3452 Constructor += Name + " = (struct __block_impl *)_";
3453 else
3454 Constructor += Name + " = _";
3455 Constructor += Name + ";\n";
3456 }
3457 // Initialize all "by ref" arguments.
3458 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3459 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003460 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003461 Constructor += " ";
3462 if (isBlockPointerType((*I)->getType()))
3463 Constructor += Name + " = (struct __block_impl *)_";
3464 else
3465 Constructor += Name + " = _";
3466 Constructor += Name + ";\n";
3467 }
3468 } else {
3469 // Finish writing the constructor.
3470 // FIXME: handle NSConcreteGlobalBlock.
3471 Constructor += ", int flags=0) {\n";
3472 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3473 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3474 if (hasCopyDisposeHelpers)
3475 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3476 }
3477 Constructor += " ";
3478 Constructor += "}\n";
3479 S += Constructor;
3480 S += "};\n";
3481 return S;
3482}
3483
3484void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3485 const char *FunName) {
3486 // Insert closures that were part of the function.
3487 for (unsigned i = 0; i < Blocks.size(); i++) {
3488
3489 CollectBlockDeclRefInfo(Blocks[i]);
3490
3491 std::string Tag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
3492
3493 std::string CI = SynthesizeBlockImpl(Blocks[i], Tag,
3494 ImportedBlockDecls.size() > 0);
3495
3496 InsertText(FunLocStart, CI.c_str(), CI.size());
3497
3498 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, Tag);
3499
3500 InsertText(FunLocStart, CF.c_str(), CF.size());
3501
3502 if (ImportedBlockDecls.size()) {
3503 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, Tag);
3504 InsertText(FunLocStart, HF.c_str(), HF.size());
3505 }
3506
3507 BlockDeclRefs.clear();
3508 BlockByRefDecls.clear();
3509 BlockByCopyDecls.clear();
3510 BlockCallExprs.clear();
3511 ImportedBlockDecls.clear();
3512 }
3513 Blocks.clear();
3514 RewrittenBlockExprs.clear();
3515}
3516
3517void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3518 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner8ec03f52008-11-24 03:54:41 +00003519 const char *FuncName = FD->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003520
3521 SynthesizeBlockLiterals(FunLocStart, FuncName);
3522}
3523
3524void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00003525 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3526 //SourceLocation FunLocStart = MD->getLocStart();
3527 // FIXME: This hack works around a bug in Rewrite.InsertText().
3528 SourceLocation FunLocStart = MD->getLocStart().getFileLocWithOffset(-1);
Chris Lattner077bf5e2008-11-24 03:33:13 +00003529 std::string FuncName = MD->getSelector().getAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003530 // Convert colons to underscores.
3531 std::string::size_type loc = 0;
3532 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3533 FuncName.replace(loc, 1, "_");
3534
3535 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
3536}
3537
3538void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
3539 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3540 CI != E; ++CI)
3541 if (*CI) {
3542 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3543 GetBlockDeclRefExprs(CBE->getBody());
3544 else
3545 GetBlockDeclRefExprs(*CI);
3546 }
3547 // Handle specific things.
3548 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
3549 // FIXME: Handle enums.
3550 if (!isa<FunctionDecl>(CDRE->getDecl()))
3551 BlockDeclRefs.push_back(CDRE);
3552 return;
3553}
3554
3555void RewriteObjC::GetBlockCallExprs(Stmt *S) {
3556 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3557 CI != E; ++CI)
3558 if (*CI) {
3559 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3560 GetBlockCallExprs(CBE->getBody());
3561 else
3562 GetBlockCallExprs(*CI);
3563 }
3564
3565 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
3566 if (CE->getCallee()->getType()->isBlockPointerType()) {
3567 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
3568 }
3569 }
3570 return;
3571}
3572
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003573Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00003574 // Navigate to relevant type information.
3575 const char *closureName = 0;
3576 const BlockPointerType *CPT = 0;
3577
3578 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003579 closureName = DRE->getDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003580 CPT = DRE->getType()->getAsBlockPointerType();
3581 } else if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003582 closureName = CDRE->getDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003583 CPT = CDRE->getType()->getAsBlockPointerType();
3584 } else if (MemberExpr *MExpr = dyn_cast<MemberExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003585 closureName = MExpr->getMemberDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003586 CPT = MExpr->getType()->getAsBlockPointerType();
3587 } else {
3588 assert(1 && "RewriteBlockClass: Bad type");
3589 }
3590 assert(CPT && "RewriteBlockClass: Bad type");
3591 const FunctionType *FT = CPT->getPointeeType()->getAsFunctionType();
3592 assert(FT && "RewriteBlockClass: Bad type");
3593 const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(FT);
3594 // FTP will be null for closures that don't take arguments.
3595
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003596 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
3597 SourceLocation(),
3598 &Context->Idents.get("__block_impl"));
3599 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00003600
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003601 // Generate a funky cast.
3602 llvm::SmallVector<QualType, 8> ArgTypes;
3603
3604 // Push the block argument type.
3605 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00003606 if (FTP) {
3607 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003608 E = FTP->arg_type_end(); I && (I != E); ++I) {
3609 QualType t = *I;
3610 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3611 if (isBlockPointerType(t)) {
3612 const BlockPointerType *BPT = t->getAsBlockPointerType();
3613 t = Context->getPointerType(BPT->getPointeeType());
3614 }
3615 ArgTypes.push_back(t);
3616 }
Steve Naroff54055232008-10-27 17:20:55 +00003617 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003618 // Now do the pointer to function cast.
3619 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
3620 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
3621
3622 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Steve Naroff54055232008-10-27 17:20:55 +00003623
Steve Naroffb2f9e512008-11-03 23:29:32 +00003624 CastExpr *BlkCast = new CStyleCastExpr(PtrBlock, Exp->getCallee(), PtrBlock, SourceLocation(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003625 // Don't forget the parens to enforce the proper binding.
3626 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), BlkCast);
3627 //PE->dump();
Steve Naroff54055232008-10-27 17:20:55 +00003628
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003629 FieldDecl *FD = FieldDecl::Create(*Context, SourceLocation(),
3630 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy);
3631 MemberExpr *ME = new MemberExpr(PE, true, FD, SourceLocation(), FD->getType());
3632
Steve Naroffb2f9e512008-11-03 23:29:32 +00003633 CastExpr *FunkCast = new CStyleCastExpr(PtrToFuncCastType, ME, PtrToFuncCastType, SourceLocation(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003634 PE = new ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
3635
3636 llvm::SmallVector<Expr*, 8> BlkExprs;
3637 // Add the implicit argument.
3638 BlkExprs.push_back(BlkCast);
3639 // Add the user arguments.
Steve Naroff54055232008-10-27 17:20:55 +00003640 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3641 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003642 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00003643 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003644 CallExpr *CE = new CallExpr(PE, &BlkExprs[0], BlkExprs.size(), Exp->getType(), SourceLocation());
3645 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00003646}
3647
3648void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003649 Stmt *BlockCall = SynthesizeBlockCall(Exp);
3650 ReplaceStmt(Exp, BlockCall);
Steve Naroff54055232008-10-27 17:20:55 +00003651}
3652
3653void RewriteObjC::RewriteBlockDeclRefExpr(BlockDeclRefExpr *BDRE) {
3654 // FIXME: Add more elaborate code generation required by the ABI.
3655 InsertText(BDRE->getLocStart(), "*", 1);
3656}
3657
Steve Naroffb2f9e512008-11-03 23:29:32 +00003658void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3659 SourceLocation LocStart = CE->getLParenLoc();
3660 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00003661
3662 // Need to avoid trying to rewrite synthesized casts.
3663 if (LocStart.isInvalid())
3664 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00003665 // Need to avoid trying to rewrite casts contained in macros.
3666 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3667 return;
Steve Narofffa15fd92008-10-28 20:29:00 +00003668
Steve Naroff54055232008-10-27 17:20:55 +00003669 const char *startBuf = SM->getCharacterData(LocStart);
3670 const char *endBuf = SM->getCharacterData(LocEnd);
3671
3672 // advance the location to startArgList.
3673 const char *argPtr = startBuf;
3674
3675 while (*argPtr++ && (argPtr < endBuf)) {
3676 switch (*argPtr) {
3677 case '^':
3678 // Replace the '^' with '*'.
3679 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
3680 ReplaceText(LocStart, 1, "*", 1);
3681 break;
3682 }
3683 }
3684 return;
3685}
3686
3687void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
3688 SourceLocation DeclLoc = FD->getLocation();
3689 unsigned parenCount = 0;
3690
3691 // We have 1 or more arguments that have closure pointers.
3692 const char *startBuf = SM->getCharacterData(DeclLoc);
3693 const char *startArgList = strchr(startBuf, '(');
3694
3695 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
3696
3697 parenCount++;
3698 // advance the location to startArgList.
3699 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
3700 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
3701
3702 const char *argPtr = startArgList;
3703
3704 while (*argPtr++ && parenCount) {
3705 switch (*argPtr) {
3706 case '^':
3707 // Replace the '^' with '*'.
3708 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
3709 ReplaceText(DeclLoc, 1, "*", 1);
3710 break;
3711 case '(':
3712 parenCount++;
3713 break;
3714 case ')':
3715 parenCount--;
3716 break;
3717 }
3718 }
3719 return;
3720}
3721
3722bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
3723 const FunctionTypeProto *FTP;
3724 const PointerType *PT = QT->getAsPointerType();
3725 if (PT) {
3726 FTP = PT->getPointeeType()->getAsFunctionTypeProto();
3727 } else {
3728 const BlockPointerType *BPT = QT->getAsBlockPointerType();
3729 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
3730 FTP = BPT->getPointeeType()->getAsFunctionTypeProto();
3731 }
3732 if (FTP) {
3733 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
3734 E = FTP->arg_type_end(); I != E; ++I)
3735 if (isBlockPointerType(*I))
3736 return true;
3737 }
3738 return false;
3739}
3740
3741void RewriteObjC::GetExtentOfArgList(const char *Name,
3742 const char *&LParen, const char *&RParen) {
3743 const char *argPtr = strchr(Name, '(');
3744 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
3745
3746 LParen = argPtr; // output the start.
3747 argPtr++; // skip past the left paren.
3748 unsigned parenCount = 1;
3749
3750 while (*argPtr && parenCount) {
3751 switch (*argPtr) {
3752 case '(': parenCount++; break;
3753 case ')': parenCount--; break;
3754 default: break;
3755 }
3756 if (parenCount) argPtr++;
3757 }
3758 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
3759 RParen = argPtr; // output the end
3760}
3761
3762void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
3763 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3764 RewriteBlockPointerFunctionArgs(FD);
3765 return;
3766 }
3767 // Handle Variables and Typedefs.
3768 SourceLocation DeclLoc = ND->getLocation();
3769 QualType DeclT;
3770 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3771 DeclT = VD->getType();
3772 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
3773 DeclT = TDD->getUnderlyingType();
3774 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
3775 DeclT = FD->getType();
3776 else
3777 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
3778
3779 const char *startBuf = SM->getCharacterData(DeclLoc);
3780 const char *endBuf = startBuf;
3781 // scan backward (from the decl location) for the end of the previous decl.
3782 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
3783 startBuf--;
3784
3785 // *startBuf != '^' if we are dealing with a pointer to function that
3786 // may take block argument types (which will be handled below).
3787 if (*startBuf == '^') {
3788 // Replace the '^' with '*', computing a negative offset.
3789 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
3790 ReplaceText(DeclLoc, 1, "*", 1);
3791 }
3792 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
3793 // Replace the '^' with '*' for arguments.
3794 DeclLoc = ND->getLocation();
3795 startBuf = SM->getCharacterData(DeclLoc);
3796 const char *argListBegin, *argListEnd;
3797 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
3798 while (argListBegin < argListEnd) {
3799 if (*argListBegin == '^') {
3800 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
3801 ReplaceText(CaretLoc, 1, "*", 1);
3802 }
3803 argListBegin++;
3804 }
3805 }
3806 return;
3807}
3808
3809void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
3810 // Add initializers for any closure decl refs.
3811 GetBlockDeclRefExprs(Exp->getBody());
3812 if (BlockDeclRefs.size()) {
3813 // Unique all "by copy" declarations.
3814 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3815 if (!BlockDeclRefs[i]->isByRef())
3816 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
3817 // Unique all "by ref" declarations.
3818 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3819 if (BlockDeclRefs[i]->isByRef()) {
3820 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
3821 }
3822 // Find any imported blocks...they will need special attention.
3823 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3824 if (isBlockPointerType(BlockDeclRefs[i]->getType())) {
Steve Naroff00072682008-11-13 17:40:07 +00003825 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff54055232008-10-27 17:20:55 +00003826 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
3827 }
3828 }
3829}
3830
Steve Narofffa15fd92008-10-28 20:29:00 +00003831FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
3832 IdentifierInfo *ID = &Context->Idents.get(name);
3833 QualType FType = Context->getFunctionTypeNoProto(Context->VoidPtrTy);
3834 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
3835 ID, FType, FunctionDecl::Extern, false, 0);
3836}
3837
Steve Naroff8e2f57a2008-10-29 18:15:37 +00003838Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Narofffa15fd92008-10-28 20:29:00 +00003839 Blocks.push_back(Exp);
3840
3841 CollectBlockDeclRefInfo(Exp);
3842 std::string FuncName;
3843
3844 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00003845 FuncName = CurFunctionDef->getNameAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00003846 else if (CurMethodDef) {
Chris Lattner077bf5e2008-11-24 03:33:13 +00003847 FuncName = CurMethodDef->getSelector().getAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00003848 // Convert colons to underscores.
3849 std::string::size_type loc = 0;
3850 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3851 FuncName.replace(loc, 1, "_");
Steve Naroff8e2f57a2008-10-29 18:15:37 +00003852 } else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003853 FuncName = std::string(GlobalVarDecl->getNameAsString());
Steve Narofffa15fd92008-10-28 20:29:00 +00003854
3855 std::string BlockNumber = utostr(Blocks.size()-1);
3856
3857 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
3858 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
3859
3860 // Get a pointer to the function type so we can cast appropriately.
3861 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
3862
3863 FunctionDecl *FD;
3864 Expr *NewRep;
3865
3866 // Simulate a contructor call...
3867 FD = SynthBlockInitFunctionDecl(Tag.c_str());
3868 DeclRefExpr *DRE = new DeclRefExpr(FD, FType, SourceLocation());
3869
3870 llvm::SmallVector<Expr*, 4> InitExprs;
3871
Steve Narofffdc03722008-10-29 21:23:59 +00003872 // Initialize the block function.
Steve Narofffa15fd92008-10-28 20:29:00 +00003873 FD = SynthBlockInitFunctionDecl(Func.c_str());
3874 DeclRefExpr *Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3875 CastExpr *castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00003876 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00003877 InitExprs.push_back(castExpr);
Steve Narofffa15fd92008-10-28 20:29:00 +00003878
3879 if (ImportedBlockDecls.size()) {
3880 std::string Buf = "__" + FuncName + "_block_copy_" + BlockNumber;
Steve Narofffdc03722008-10-29 21:23:59 +00003881 FD = SynthBlockInitFunctionDecl(Buf.c_str());
3882 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3883 castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00003884 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffdc03722008-10-29 21:23:59 +00003885 InitExprs.push_back(castExpr);
3886
Steve Narofffa15fd92008-10-28 20:29:00 +00003887 Buf = "__" + FuncName + "_block_dispose_" + BlockNumber;
Steve Narofffdc03722008-10-29 21:23:59 +00003888 FD = SynthBlockInitFunctionDecl(Buf.c_str());
3889 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3890 castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00003891 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffdc03722008-10-29 21:23:59 +00003892 InitExprs.push_back(castExpr);
Steve Narofffa15fd92008-10-28 20:29:00 +00003893 }
3894 // Add initializers for any closure decl refs.
3895 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00003896 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00003897 // Output all "by copy" declarations.
3898 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3899 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00003900 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00003901 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner8ec03f52008-11-24 03:54:41 +00003902 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00003903 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00003904 } else if (isBlockPointerType((*I)->getType())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003905 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00003906 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3907 Exp = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00003908 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00003909 } else {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003910 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00003911 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00003912 }
Steve Narofffdc03722008-10-29 21:23:59 +00003913 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00003914 }
3915 // Output all "by ref" declarations.
3916 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3917 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003918 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00003919 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3920 Exp = new UnaryOperator(Exp, UnaryOperator::AddrOf,
3921 Context->getPointerType(Exp->getType()),
3922 SourceLocation());
Steve Naroff707b0fe2008-11-14 21:36:12 +00003923 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00003924 }
3925 }
Steve Narofffa15fd92008-10-28 20:29:00 +00003926 NewRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
3927 FType, SourceLocation());
3928 NewRep = new UnaryOperator(NewRep, UnaryOperator::AddrOf,
3929 Context->getPointerType(NewRep->getType()),
3930 SourceLocation());
Steve Naroffb2f9e512008-11-03 23:29:32 +00003931 NewRep = new CStyleCastExpr(FType, NewRep, FType, SourceLocation(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00003932 BlockDeclRefs.clear();
3933 BlockByRefDecls.clear();
3934 BlockByCopyDecls.clear();
3935 ImportedBlockDecls.clear();
3936 return NewRep;
3937}
3938
3939//===----------------------------------------------------------------------===//
3940// Function Body / Expression rewriting
3941//===----------------------------------------------------------------------===//
3942
3943Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
3944 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
3945 isa<DoStmt>(S) || isa<ForStmt>(S))
3946 Stmts.push_back(S);
3947 else if (isa<ObjCForCollectionStmt>(S)) {
3948 Stmts.push_back(S);
3949 ObjCBcLabelNo.push_back(++BcLabelCount);
3950 }
3951
3952 SourceRange OrigStmtRange = S->getSourceRange();
3953
3954 // Perform a bottom up rewrite of all children.
3955 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3956 CI != E; ++CI)
3957 if (*CI) {
3958 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
3959 if (newStmt)
3960 *CI = newStmt;
3961 }
3962
3963 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
3964 // Rewrite the block body in place.
3965 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
3966
3967 // Now we snarf the rewritten text and stash it away for later use.
Steve Naroff8e2f57a2008-10-29 18:15:37 +00003968 std::string Str = Rewrite.getRewritenText(BE->getSourceRange());
3969 RewrittenBlockExprs[BE] = Str;
Steve Narofffa15fd92008-10-28 20:29:00 +00003970
3971 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
3972 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00003973 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00003974 return blockTranscribed;
3975 }
3976 // Handle specific things.
3977 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
3978 return RewriteAtEncode(AtEncode);
3979
3980 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
3981 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
3982
3983 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
3984 return RewriteAtSelector(AtSelector);
3985
3986 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
3987 return RewriteObjCStringLiteral(AtString);
3988
3989 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
3990 // Before we rewrite it, put the original message expression in a comment.
3991 SourceLocation startLoc = MessExpr->getLocStart();
3992 SourceLocation endLoc = MessExpr->getLocEnd();
3993
3994 const char *startBuf = SM->getCharacterData(startLoc);
3995 const char *endBuf = SM->getCharacterData(endLoc);
3996
3997 std::string messString;
3998 messString += "// ";
3999 messString.append(startBuf, endBuf-startBuf+1);
4000 messString += "\n";
4001
4002 // FIXME: Missing definition of
4003 // InsertText(clang::SourceLocation, char const*, unsigned int).
4004 // InsertText(startLoc, messString.c_str(), messString.size());
4005 // Tried this, but it didn't work either...
4006 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
4007 return RewriteMessageExpr(MessExpr);
4008 }
4009
4010 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4011 return RewriteObjCTryStmt(StmtTry);
4012
4013 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4014 return RewriteObjCSynchronizedStmt(StmtTry);
4015
4016 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4017 return RewriteObjCThrowStmt(StmtThrow);
4018
4019 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4020 return RewriteObjCProtocolExpr(ProtocolExp);
4021
4022 if (ObjCForCollectionStmt *StmtForCollection =
4023 dyn_cast<ObjCForCollectionStmt>(S))
4024 return RewriteObjCForCollectionStmt(StmtForCollection,
4025 OrigStmtRange.getEnd());
4026 if (BreakStmt *StmtBreakStmt =
4027 dyn_cast<BreakStmt>(S))
4028 return RewriteBreakStmt(StmtBreakStmt);
4029 if (ContinueStmt *StmtContinueStmt =
4030 dyn_cast<ContinueStmt>(S))
4031 return RewriteContinueStmt(StmtContinueStmt);
4032
4033 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
4034 // and cast exprs.
4035 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4036 // FIXME: What we're doing here is modifying the type-specifier that
4037 // precedes the first Decl. In the future the DeclGroup should have
4038 // a separate type-specifier that we can rewrite.
4039 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
4040
4041 // Blocks rewrite rules.
4042 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4043 DI != DE; ++DI) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004044 ScopedDecl *SD = *DI;
4045 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
4046 if (isBlockPointerType(ND->getType()))
4047 RewriteBlockPointerDecl(ND);
4048 else if (ND->getType()->isFunctionPointerType())
4049 CheckFunctionPointerDecl(ND->getType(), ND);
4050 }
4051 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
4052 if (isBlockPointerType(TD->getUnderlyingType()))
4053 RewriteBlockPointerDecl(TD);
4054 else if (TD->getUnderlyingType()->isFunctionPointerType())
4055 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4056 }
4057 }
4058 }
4059
4060 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4061 RewriteObjCQualifiedInterfaceTypes(CE);
4062
4063 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4064 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4065 assert(!Stmts.empty() && "Statement stack is empty");
4066 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4067 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
4068 && "Statement stack mismatch");
4069 Stmts.pop_back();
4070 }
4071 // Handle blocks rewriting.
4072 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4073 if (BDRE->isByRef())
4074 RewriteBlockDeclRefExpr(BDRE);
4075 }
4076 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004077 if (CE->getCallee()->getType()->isBlockPointerType()) {
4078 Stmt *BlockCall = SynthesizeBlockCall(CE);
4079 ReplaceStmt(S, BlockCall);
4080 return BlockCall;
4081 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004082 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00004083 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004084 RewriteCastExpr(CE);
4085 }
4086#if 0
4087 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
4088 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
4089 // Get the new text.
4090 std::string SStr;
4091 llvm::raw_string_ostream Buf(SStr);
4092 Replacement->printPretty(Buf);
4093 const std::string &Str = Buf.str();
4094
4095 printf("CAST = %s\n", &Str[0]);
4096 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4097 delete S;
4098 return Replacement;
4099 }
4100#endif
4101 // Return this stmt unmodified.
4102 return S;
4103}
4104
4105/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4106/// main file of the input.
4107void RewriteObjC::HandleDeclInMainFile(Decl *D) {
4108 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4109 // Since function prototypes don't have ParmDecl's, we check the function
4110 // prototype. This enables us to rewrite function declarations and
4111 // definitions using the same code.
4112 RewriteBlocksInFunctionTypeProto(FD->getType(), FD);
4113
4114 if (Stmt *Body = FD->getBody()) {
4115 CurFunctionDef = FD;
4116 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
4117 // This synthesizes and inserts the block "impl" struct, invoke function,
4118 // and any copy/dispose helper functions.
4119 InsertBlockLiteralsWithinFunction(FD);
4120 CurFunctionDef = 0;
4121 }
4122 return;
4123 }
4124 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4125 if (Stmt *Body = MD->getBody()) {
4126 //Body->dump();
4127 CurMethodDef = MD;
4128 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
4129 InsertBlockLiteralsWithinMethod(MD);
4130 CurMethodDef = 0;
4131 }
4132 }
4133 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
4134 ClassImplementation.push_back(CI);
4135 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
4136 CategoryImplementation.push_back(CI);
4137 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
4138 RewriteForwardClassDecl(CD);
4139 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4140 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004141 if (isBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004142 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004143 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004144 CheckFunctionPointerDecl(VD->getType(), VD);
4145 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00004146 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004147 RewriteCastExpr(CE);
4148 }
4149 }
4150 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004151 if (VD->getInit()) {
4152 GlobalVarDecl = VD;
4153 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Douglas Gregor2e1cd422008-11-17 14:58:09 +00004154 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00004155 VD->getNameAsCString());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004156 GlobalVarDecl = 0;
4157
4158 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00004159 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004160 RewriteCastExpr(CE);
4161 }
4162 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004163 return;
4164 }
4165 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
4166 if (isBlockPointerType(TD->getUnderlyingType()))
4167 RewriteBlockPointerDecl(TD);
4168 else if (TD->getUnderlyingType()->isFunctionPointerType())
4169 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4170 return;
4171 }
4172 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
4173 if (RD->isDefinition()) {
4174 for (RecordDecl::field_const_iterator i = RD->field_begin(),
4175 e = RD->field_end(); i != e; ++i) {
4176 FieldDecl *FD = *i;
4177 if (isBlockPointerType(FD->getType()))
4178 RewriteBlockPointerDecl(FD);
4179 }
4180 }
4181 return;
4182 }
4183 // Nothing yet.
4184}
4185
4186void RewriteObjC::HandleTranslationUnit(TranslationUnit& TU) {
4187 // Get the top-level buffer that this corresponds to.
4188
4189 // Rewrite tabs if we care.
4190 //RewriteTabs();
4191
4192 if (Diags.hasErrorOccurred())
4193 return;
4194
4195 // Create the output file.
4196
4197 llvm::OwningPtr<llvm::raw_ostream> OwnedStream;
4198 llvm::raw_ostream *OutFile;
4199 if (OutFileName == "-") {
4200 OutFile = &llvm::outs();
4201 } else if (!OutFileName.empty()) {
4202 std::string Err;
Daniel Dunbar26fb2722008-11-13 05:09:21 +00004203 OutFile = new llvm::raw_fd_ostream(OutFileName.c_str(), false, Err);
Steve Narofffa15fd92008-10-28 20:29:00 +00004204 OwnedStream.reset(OutFile);
4205 } else if (InFileName == "-") {
4206 OutFile = &llvm::outs();
4207 } else {
4208 llvm::sys::Path Path(InFileName);
4209 Path.eraseSuffix();
4210 Path.appendSuffix("cpp");
4211 std::string Err;
Daniel Dunbar26fb2722008-11-13 05:09:21 +00004212 OutFile = new llvm::raw_fd_ostream(Path.toString().c_str(), false, Err);
Steve Narofffa15fd92008-10-28 20:29:00 +00004213 OwnedStream.reset(OutFile);
4214 }
4215
4216 RewriteInclude();
4217
4218 InsertText(SourceLocation::getFileLoc(MainFileID, 0),
4219 Preamble.c_str(), Preamble.size(), false);
4220
Steve Naroff0aab7962008-11-14 14:10:01 +00004221 if (ClassImplementation.size() || CategoryImplementation.size())
4222 RewriteImplementations();
Steve Narofffa15fd92008-10-28 20:29:00 +00004223
4224 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
4225 // we are done.
4226 if (const RewriteBuffer *RewriteBuf =
4227 Rewrite.getRewriteBufferFor(MainFileID)) {
4228 //printf("Changed:\n");
4229 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4230 } else {
4231 fprintf(stderr, "No changes\n");
4232 }
Steve Narofface66252008-11-13 20:07:04 +00004233
Steve Naroff0aab7962008-11-14 14:10:01 +00004234 if (ClassImplementation.size() || CategoryImplementation.size()) {
4235 // Rewrite Objective-c meta data*
4236 std::string ResultStr;
4237 SynthesizeMetaDataIntoBuffer(ResultStr);
4238 // Emit metadata.
4239 *OutFile << ResultStr;
4240 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004241 OutFile->flush();
4242}
4243