blob: 06a4a5caed80aefd61b011155a3851d5d38833ad [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.
Steve Naroff3539cdb2008-12-02 17:54:50 +0000627 // FIXME: deal with code generation implications for various property
628 // attributes (copy, retain, nonatomic).
629 // See objc-act.c:objc_synthesize_new_getter() for details.
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000630 Getr += "return " + getIvarAccessString(ClassDecl, OID);
631 Getr += "; }";
Steve Naroffeb0646c2008-12-02 15:48:25 +0000632 InsertText(onePastSemiLoc, Getr.c_str(), Getr.size());
Steve Naroffa0876e82008-12-02 17:36:43 +0000633
634 // Add the rewritten getter to trigger meta data generation. An alternate, and
635 // possibly cleaner approach is to hack RewriteObjCMethodsMetaData() to deal
636 // with properties explicitly. The following addInstanceMethod() required far
637 // less code change (and actually models what the rewriter is doing).
638 if (IMD)
639 IMD->addInstanceMethod(PD->getGetterMethodDecl());
640 else
641 CID->addInstanceMethod(PD->getGetterMethodDecl());
Steve Naroffeb0646c2008-12-02 15:48:25 +0000642
643 if (PD->isReadOnly())
644 return;
645
646 // Generate the 'setter' function.
647 std::string Setr;
648 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000649 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000650 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff3539cdb2008-12-02 17:54:50 +0000651 // FIXME: deal with code generation implications for various property
652 // attributes (copy, retain, nonatomic).
653 // See objc-act.c:objc_synthesize_new_getter() for details.
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000654 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
655 Setr += OID->getNameAsCString();
656 Setr += "; }";
Steve Naroffeb0646c2008-12-02 15:48:25 +0000657 InsertText(onePastSemiLoc, Setr.c_str(), Setr.size());
Steve Naroffa0876e82008-12-02 17:36:43 +0000658
659 // Add the rewritten setter to trigger meta data generation.
660 if (IMD)
661 IMD->addInstanceMethod(PD->getSetterMethodDecl());
662 else
663 CID->addInstanceMethod(PD->getSetterMethodDecl());
Steve Naroffd40910b2008-12-01 20:33:01 +0000664}
Chris Lattner8a12c272007-10-11 18:38:32 +0000665
Steve Naroffb29b4272008-04-14 22:03:09 +0000666void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000667 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000668 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerf04da132007-10-24 17:06:59 +0000669
670 // Get the start location and compute the semi location.
671 SourceLocation startLoc = ClassDecl->getLocation();
672 const char *startBuf = SM->getCharacterData(startLoc);
673 const char *semiPtr = strchr(startBuf, ';');
674
675 // Translate to typedef's that forward reference structs with the same name
676 // as the class. As a convenience, we include the original declaration
677 // as a comment.
678 std::string typedefString;
679 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000680 typedefString.append(startBuf, semiPtr-startBuf+1);
681 typedefString += "\n";
682 for (int i = 0; i < numDecls; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000683 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000684 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000685 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000686 typedefString += "\n";
687 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000688 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000689 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000690 typedefString += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000691 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000692 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000693 }
694
695 // Replace the @class with typedefs corresponding to the classes.
Chris Lattneraadaf782008-01-31 19:51:04 +0000696 ReplaceText(startLoc, semiPtr-startBuf+1,
697 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000698}
699
Steve Naroffb29b4272008-04-14 22:03:09 +0000700void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000701 SourceLocation LocStart = Method->getLocStart();
702 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000703
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000704 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
Steve Naroff94ac21e2008-10-21 13:37:27 +0000705 InsertText(LocStart, "#if 0\n", 6);
706 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000707 } else {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000708 InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000709 }
710}
711
Steve Naroffb29b4272008-04-14 22:03:09 +0000712void RewriteObjC::RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000713{
Chris Lattner55d13b42008-03-16 21:23:50 +0000714 for (unsigned i = 0; i < nProperties; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000715 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000716 SourceLocation Loc = Property->getLocation();
717
Chris Lattneraadaf782008-01-31 19:51:04 +0000718 ReplaceText(Loc, 0, "// ", 3);
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000719
720 // FIXME: handle properties that are declared across multiple lines.
721 }
722}
723
Steve Naroffb29b4272008-04-14 22:03:09 +0000724void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000725 SourceLocation LocStart = CatDecl->getLocStart();
726
727 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000728 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000729
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000730 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000731 E = CatDecl->instmeth_end(); I != E; ++I)
732 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000733 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000734 E = CatDecl->classmeth_end(); I != E; ++I)
735 RewriteMethodDeclaration(*I);
736
Steve Naroff423cb562007-10-30 13:30:57 +0000737 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000738 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000739}
740
Steve Naroffb29b4272008-04-14 22:03:09 +0000741void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000742 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000743
Steve Naroff752d6ef2007-10-30 16:42:30 +0000744 SourceLocation LocStart = PDecl->getLocStart();
745
746 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000747 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000748
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000749 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000750 E = PDecl->instmeth_end(); I != E; ++I)
751 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000752 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000753 E = PDecl->classmeth_end(); I != E; ++I)
754 RewriteMethodDeclaration(*I);
755
Steve Naroff752d6ef2007-10-30 16:42:30 +0000756 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000757 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattneraadaf782008-01-31 19:51:04 +0000758 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000759
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000760 // Must comment out @optional/@required
761 const char *startBuf = SM->getCharacterData(LocStart);
762 const char *endBuf = SM->getCharacterData(LocEnd);
763 for (const char *p = startBuf; p < endBuf; p++) {
764 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
765 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000766 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000767 ReplaceText(OptionalLoc, strlen("@optional"),
768 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000769
770 }
771 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
772 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000773 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000774 ReplaceText(OptionalLoc, strlen("@required"),
775 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000776
777 }
778 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000779}
780
Steve Naroffb29b4272008-04-14 22:03:09 +0000781void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000782 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000783 if (LocStart.isInvalid())
784 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000785 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000786 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000787}
788
Steve Naroffb29b4272008-04-14 22:03:09 +0000789void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000790 std::string &ResultStr) {
Steve Naroffced80a82008-10-30 12:09:33 +0000791 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroff76e429d2008-07-16 14:40:40 +0000792 const FunctionType *FPRetType = 0;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000793 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000794 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000795 ResultStr += "id";
Steve Naroff76e429d2008-07-16 14:40:40 +0000796 else if (OMD->getResultType()->isFunctionPointerType()) {
797 // needs special handling, since pointer-to-functions have special
798 // syntax (where a decaration models use).
799 QualType retType = OMD->getResultType();
800 if (const PointerType* PT = retType->getAsPointerType()) {
801 QualType PointeeTy = PT->getPointeeType();
802 if ((FPRetType = PointeeTy->getAsFunctionType())) {
803 ResultStr += FPRetType->getResultType().getAsString();
804 ResultStr += "(*";
805 }
806 }
807 } else
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000808 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000809 ResultStr += " ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000810
811 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000812 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000813
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000814 if (OMD->isInstance())
815 NameStr += "_I_";
816 else
817 NameStr += "_C_";
818
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000819 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000820 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000821
822 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000823 if (ObjCCategoryImplDecl *CID =
824 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000825 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000826 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000827 }
Steve Naroff563b8282008-04-04 22:23:44 +0000828 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +0000829 {
830 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000831 int len = selString.size();
832 for (int i = 0; i < len; i++)
833 if (selString[i] == ':')
834 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000835 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000836 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000837 // Remember this name for metadata emission
838 MethodInternalNames[OMD] = NameStr;
839 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000840
841 // Rewrite arguments
842 ResultStr += "(";
843
844 // invisible arguments
845 if (OMD->isInstance()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000846 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000847 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +0000848 if (!LangOpts.Microsoft) {
849 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
850 ResultStr += "struct ";
851 }
852 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000853 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000854 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000855 }
856 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000857 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000858
859 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000860 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000861 ResultStr += " _cmd";
862
863 // Method arguments.
Chris Lattner58cce3b2008-03-16 01:07:14 +0000864 for (unsigned i = 0; i < OMD->getNumParams(); i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000865 ParmVarDecl *PDecl = OMD->getParamDecl(i);
866 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +0000867 if (PDecl->getType()->isObjCQualifiedIdType()) {
868 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000869 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +0000870 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000871 std::string Name = PDecl->getNameAsString();
Steve Naroffc8ad87b2008-10-30 14:45:29 +0000872 if (isBlockPointerType(PDecl->getType())) {
873 // Make sure we convert "t (^)(...)" to "t (*)(...)".
874 const BlockPointerType *BPT = PDecl->getType()->getAsBlockPointerType();
875 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name);
876 } else
877 PDecl->getType().getAsStringInternal(Name);
Steve Naroff543409e2008-04-18 21:13:19 +0000878 ResultStr += Name;
879 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000880 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +0000881 if (OMD->isVariadic())
882 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000883 ResultStr += ") ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000884
Steve Naroff76e429d2008-07-16 14:40:40 +0000885 if (FPRetType) {
886 ResultStr += ")"; // close the precedence "scope" for "*".
887
888 // Now, emit the argument types (if any).
889 if (const FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(FPRetType)) {
890 ResultStr += "(";
891 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
892 if (i) ResultStr += ", ";
893 std::string ParamStr = FT->getArgType(i).getAsString();
894 ResultStr += ParamStr;
895 }
896 if (FT->isVariadic()) {
897 if (FT->getNumArgs()) ResultStr += ", ";
898 ResultStr += "...";
899 }
900 ResultStr += ")";
901 } else {
902 ResultStr += "()";
903 }
904 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000905}
Steve Naroffb29b4272008-04-14 22:03:09 +0000906void RewriteObjC::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000907 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
908 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000909
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000910 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000911 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000912 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000913 InsertText(CID->getLocStart(), "// ", 3);
Steve Narofface66252008-11-13 20:07:04 +0000914
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000915 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000916 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
917 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000918 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000919 ObjCMethodDecl *OMD = *I;
920 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000921 SourceLocation LocStart = OMD->getLocStart();
922 SourceLocation LocEnd = OMD->getBody()->getLocStart();
923
924 const char *startBuf = SM->getCharacterData(LocStart);
925 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000926 ReplaceText(LocStart, endBuf-startBuf,
927 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000928 }
929
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000930 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000931 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
932 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000933 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000934 ObjCMethodDecl *OMD = *I;
935 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000936 SourceLocation LocStart = OMD->getLocStart();
937 SourceLocation LocEnd = OMD->getBody()->getLocStart();
938
939 const char *startBuf = SM->getCharacterData(LocStart);
940 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000941 ReplaceText(LocStart, endBuf-startBuf,
942 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000943 }
Steve Naroffd40910b2008-12-01 20:33:01 +0000944 for (ObjCCategoryImplDecl::propimpl_iterator
945 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
946 E = IMD ? IMD->propimpl_end() : CID->propimpl_end(); I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +0000947 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +0000948 }
949
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000950 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000951 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000952 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000953 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000954}
955
Steve Naroffb29b4272008-04-14 22:03:09 +0000956void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000957 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000958 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000959 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +0000960 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000961 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000962 ResultStr += "\n";
963 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000964 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000965 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000966 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000967 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000968 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000969 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000970 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000971 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000972 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Narofff908a872007-10-30 02:23:23 +0000973
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000974 RewriteProperties(ClassDecl->getNumPropertyDecl(),
975 ClassDecl->getPropertyDecl());
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000976 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000977 E = ClassDecl->instmeth_end(); I != E; ++I)
978 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000979 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000980 E = ClassDecl->classmeth_end(); I != E; ++I)
981 RewriteMethodDeclaration(*I);
982
Steve Naroff2feac5e2007-10-30 03:43:13 +0000983 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000984 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000985}
986
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000987Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
988 SourceLocation OrigStart) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000989 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff54055232008-10-27 17:20:55 +0000990 if (CurMethodDef) {
Steve Naroff05b8c782008-03-12 00:25:36 +0000991 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +0000992 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
993 // lookup which class implements the instance variable.
994 ObjCInterfaceDecl *clsDeclared = 0;
995 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
996 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
997
998 // Synthesize an explicit cast to gain access to the ivar.
999 std::string RecName = clsDeclared->getIdentifier()->getName();
1000 RecName += "_IMPL";
1001 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001002 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001003 SourceLocation(), II);
Steve Narofff0757612008-05-08 17:52:16 +00001004 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1005 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001006 CastExpr *castExpr = new CStyleCastExpr(castT, IV->getBase(), castT,
Steve Naroffb2f9e512008-11-03 23:29:32 +00001007 SourceLocation(), SourceLocation());
Steve Narofff0757612008-05-08 17:52:16 +00001008 // Don't forget the parens to enforce the proper binding.
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001009 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
1010 IV->getBase()->getLocEnd(),
1011 castExpr);
Steve Narofff0757612008-05-08 17:52:16 +00001012 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +00001013 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001014 MemberExpr *ME = new MemberExpr(PE, true, D, IV->getLocation(),
1015 D->getType());
Steve Narofff0757612008-05-08 17:52:16 +00001016 ReplaceStmt(IV, ME);
1017 delete IV;
1018 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001019 }
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001020
1021 ReplaceStmt(IV->getBase(), PE);
1022 // Cannot delete IV->getBase(), since PE points to it.
1023 // Replace the old base with the cast. This is important when doing
1024 // embedded rewrites. For example, [newInv->_container addObject:0].
1025 IV->setBase(PE);
1026 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001027 }
Steve Naroff84472a82008-04-18 21:55:08 +00001028 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001029 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
1030
1031 // Explicit ivar refs need to have a cast inserted.
1032 // FIXME: consider sharing some of this code with the code above.
1033 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +00001034 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001035 // lookup which class implements the instance variable.
1036 ObjCInterfaceDecl *clsDeclared = 0;
Steve Narofff0757612008-05-08 17:52:16 +00001037 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001038 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1039
1040 // Synthesize an explicit cast to gain access to the ivar.
1041 std::string RecName = clsDeclared->getIdentifier()->getName();
1042 RecName += "_IMPL";
1043 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001044 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001045 SourceLocation(), II);
Steve Naroff9f525972008-05-06 23:20:07 +00001046 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1047 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001048 CastExpr *castExpr = new CStyleCastExpr(castT, IV->getBase(), castT,
Steve Naroffb2f9e512008-11-03 23:29:32 +00001049 SourceLocation(), SourceLocation());
Steve Naroff9f525972008-05-06 23:20:07 +00001050 // Don't forget the parens to enforce the proper binding.
Chris Lattner8d366162008-05-28 16:38:23 +00001051 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
1052 IV->getBase()->getLocEnd(), castExpr);
Steve Naroff9f525972008-05-06 23:20:07 +00001053 ReplaceStmt(IV->getBase(), PE);
1054 // Cannot delete IV->getBase(), since PE points to it.
1055 // Replace the old base with the cast. This is important when doing
1056 // embedded rewrites. For example, [newInv->_container addObject:0].
1057 IV->setBase(PE);
1058 return IV;
1059 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001060 }
Steve Naroff84472a82008-04-18 21:55:08 +00001061 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +00001062}
1063
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001064/// SynthCountByEnumWithState - To print:
1065/// ((unsigned int (*)
1066/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1067/// (void *)objc_msgSend)((id)l_collection,
1068/// sel_registerName(
1069/// "countByEnumeratingWithState:objects:count:"),
1070/// &enumState,
1071/// (id *)items, (unsigned int)16)
1072///
Steve Naroffb29b4272008-04-14 22:03:09 +00001073void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001074 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1075 "id *, unsigned int))(void *)objc_msgSend)";
1076 buf += "\n\t\t";
1077 buf += "((id)l_collection,\n\t\t";
1078 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1079 buf += "\n\t\t";
1080 buf += "&enumState, "
1081 "(id *)items, (unsigned int)16)";
1082}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001083
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001084/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1085/// statement to exit to its outer synthesized loop.
1086///
Steve Naroffb29b4272008-04-14 22:03:09 +00001087Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001088 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1089 return S;
1090 // replace break with goto __break_label
1091 std::string buf;
1092
1093 SourceLocation startLoc = S->getLocStart();
1094 buf = "goto __break_label_";
1095 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001096 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001097
1098 return 0;
1099}
1100
1101/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1102/// statement to continue with its inner synthesized loop.
1103///
Steve Naroffb29b4272008-04-14 22:03:09 +00001104Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001105 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1106 return S;
1107 // replace continue with goto __continue_label
1108 std::string buf;
1109
1110 SourceLocation startLoc = S->getLocStart();
1111 buf = "goto __continue_label_";
1112 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001113 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001114
1115 return 0;
1116}
1117
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001118/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001119/// It rewrites:
1120/// for ( type elem in collection) { stmts; }
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001121
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001122/// Into:
1123/// {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001124/// type elem;
1125/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001126/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001127/// id l_collection = (id)collection;
1128/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1129/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001130/// if (limit) {
1131/// unsigned long startMutations = *enumState.mutationsPtr;
1132/// do {
1133/// unsigned long counter = 0;
1134/// do {
1135/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001136/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001137/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001138/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001139/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001140/// } while (counter < limit);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001141/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1142/// objects:items count:16]);
1143/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001144/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001145/// }
1146/// else
1147/// elem = nil;
1148/// }
1149///
Steve Naroffb29b4272008-04-14 22:03:09 +00001150Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001151 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001152 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1153 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1154 "ObjCForCollectionStmt Statement stack mismatch");
1155 assert(!ObjCBcLabelNo.empty() &&
1156 "ObjCForCollectionStmt - Label No stack empty");
1157
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001158 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001159 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001160 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001161 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001162 std::string buf;
1163 buf = "\n{\n\t";
1164 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1165 // type elem;
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001166 ScopedDecl* D = DS->getSolitaryDecl();
1167 QualType ElementType = cast<ValueDecl>(D)->getType();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001168 elementTypeAsString = ElementType.getAsString();
1169 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001170 buf += " ";
Chris Lattner8ec03f52008-11-24 03:54:41 +00001171 elementName = D->getNameAsCString();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001172 buf += elementName;
1173 buf += ";\n\t";
1174 }
Chris Lattner06767512008-04-08 05:52:18 +00001175 else {
1176 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner8ec03f52008-11-24 03:54:41 +00001177 elementName = DR->getDecl()->getNameAsCString();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001178 elementTypeAsString
1179 = cast<ValueDecl>(DR->getDecl())->getType().getAsString();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001180 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001181
1182 // struct __objcFastEnumerationState enumState = { 0 };
1183 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1184 // id items[16];
1185 buf += "id items[16];\n\t";
1186 // id l_collection = (id)
1187 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001188 // Find start location of 'collection' the hard way!
1189 const char *startCollectionBuf = startBuf;
1190 startCollectionBuf += 3; // skip 'for'
1191 startCollectionBuf = strchr(startCollectionBuf, '(');
1192 startCollectionBuf++; // skip '('
1193 // find 'in' and skip it.
1194 while (*startCollectionBuf != ' ' ||
1195 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1196 (*(startCollectionBuf+3) != ' ' &&
1197 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1198 startCollectionBuf++;
1199 startCollectionBuf += 3;
1200
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001201 // Replace: "for (type element in" with string constructed thus far.
Chris Lattneraadaf782008-01-31 19:51:04 +00001202 ReplaceText(startLoc, startCollectionBuf - startBuf,
1203 buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001204 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001205 SourceLocation rightParenLoc = S->getRParenLoc();
1206 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1207 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001208 buf = ";\n\t";
1209
1210 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1211 // objects:items count:16];
1212 // which is synthesized into:
1213 // unsigned int limit =
1214 // ((unsigned int (*)
1215 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1216 // (void *)objc_msgSend)((id)l_collection,
1217 // sel_registerName(
1218 // "countByEnumeratingWithState:objects:count:"),
1219 // (struct __objcFastEnumerationState *)&state,
1220 // (id *)items, (unsigned int)16);
1221 buf += "unsigned long limit =\n\t\t";
1222 SynthCountByEnumWithState(buf);
1223 buf += ";\n\t";
1224 /// if (limit) {
1225 /// unsigned long startMutations = *enumState.mutationsPtr;
1226 /// do {
1227 /// unsigned long counter = 0;
1228 /// do {
1229 /// if (startMutations != *enumState.mutationsPtr)
1230 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001231 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001232 buf += "if (limit) {\n\t";
1233 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1234 buf += "do {\n\t\t";
1235 buf += "unsigned long counter = 0;\n\t\t";
1236 buf += "do {\n\t\t\t";
1237 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1238 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1239 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001240 buf += " = (";
1241 buf += elementTypeAsString;
1242 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001243 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattneraadaf782008-01-31 19:51:04 +00001244 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001245
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001246 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001247 /// } while (counter < limit);
1248 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1249 /// objects:items count:16]);
1250 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001251 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001252 /// }
1253 /// else
1254 /// elem = nil;
1255 /// }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001256 ///
1257 buf = ";\n\t";
1258 buf += "__continue_label_";
1259 buf += utostr(ObjCBcLabelNo.back());
1260 buf += ": ;";
1261 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001262 buf += "} while (counter < limit);\n\t";
1263 buf += "} while (limit = ";
1264 SynthCountByEnumWithState(buf);
1265 buf += ");\n\t";
1266 buf += elementName;
1267 buf += " = nil;\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001268 buf += "__break_label_";
1269 buf += utostr(ObjCBcLabelNo.back());
1270 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001271 buf += "}\n\t";
1272 buf += "else\n\t\t";
1273 buf += elementName;
1274 buf += " = nil;\n";
1275 buf += "}\n";
Steve Naroff600e4e82008-07-21 18:26:02 +00001276
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001277 // Insert all these *after* the statement body.
Steve Naroff600e4e82008-07-21 18:26:02 +00001278 if (isa<CompoundStmt>(S->getBody())) {
1279 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1280 InsertText(endBodyLoc, buf.c_str(), buf.size());
1281 } else {
1282 /* Need to treat single statements specially. For example:
1283 *
1284 * for (A *a in b) if (stuff()) break;
1285 * for (A *a in b) xxxyy;
1286 *
1287 * The following code simply scans ahead to the semi to find the actual end.
1288 */
1289 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1290 const char *semiBuf = strchr(stmtBuf, ';');
1291 assert(semiBuf && "Can't find ';'");
1292 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1293 InsertText(endBodyLoc, buf.c_str(), buf.size());
1294 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001295 Stmts.pop_back();
1296 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001297 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001298}
1299
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001300/// RewriteObjCSynchronizedStmt -
1301/// This routine rewrites @synchronized(expr) stmt;
1302/// into:
1303/// objc_sync_enter(expr);
1304/// @try stmt @finally { objc_sync_exit(expr); }
1305///
Steve Naroffb29b4272008-04-14 22:03:09 +00001306Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001307 // Get the start location and compute the semi location.
1308 SourceLocation startLoc = S->getLocStart();
1309 const char *startBuf = SM->getCharacterData(startLoc);
1310
1311 assert((*startBuf == '@') && "bogus @synchronized location");
1312
1313 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001314 buf = "objc_sync_enter((id)";
1315 const char *lparenBuf = startBuf;
1316 while (*lparenBuf != '(') lparenBuf++;
1317 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Steve Naroffc7089f12008-08-19 13:04:19 +00001318 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1319 // the sync expression is typically a message expression that's already
1320 // been rewritten! (which implies the SourceLocation's are invalid).
1321 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001322 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001323 while (*endBuf != ')') endBuf--;
1324 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001325 buf = ");\n";
1326 // declare a new scope with two variables, _stack and _rethrow.
1327 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1328 buf += "int buf[18/*32-bit i386*/];\n";
1329 buf += "char *pointers[4];} _stack;\n";
1330 buf += "id volatile _rethrow = 0;\n";
1331 buf += "objc_exception_try_enter(&_stack);\n";
1332 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00001333 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001334 startLoc = S->getSynchBody()->getLocEnd();
1335 startBuf = SM->getCharacterData(startLoc);
1336
Steve Naroffc7089f12008-08-19 13:04:19 +00001337 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001338 SourceLocation lastCurlyLoc = startLoc;
1339 buf = "}\nelse {\n";
1340 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1341 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb2a39452008-07-16 19:47:39 +00001342 buf += " objc_sync_exit(";
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001343 Expr *syncExpr = new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00001344 S->getSynchExpr(),
1345 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00001346 SourceLocation(), SourceLocation());
Ted Kremeneka95d3752008-09-13 05:16:45 +00001347 std::string syncExprBufS;
1348 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Steve Naroff3498cc92008-08-21 13:03:03 +00001349 syncExpr->printPretty(syncExprBuf);
Steve Naroffb2a39452008-07-16 19:47:39 +00001350 buf += syncExprBuf.str();
1351 buf += ");\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001352 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1353 buf += "}\n";
1354 buf += "}";
1355
Chris Lattneraadaf782008-01-31 19:51:04 +00001356 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001357 return 0;
1358}
1359
Steve Naroffb29b4272008-04-14 22:03:09 +00001360Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001361 // Get the start location and compute the semi location.
1362 SourceLocation startLoc = S->getLocStart();
1363 const char *startBuf = SM->getCharacterData(startLoc);
1364
1365 assert((*startBuf == '@') && "bogus @try location");
1366
1367 std::string buf;
1368 // declare a new scope with two variables, _stack and _rethrow.
1369 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1370 buf += "int buf[18/*32-bit i386*/];\n";
1371 buf += "char *pointers[4];} _stack;\n";
1372 buf += "id volatile _rethrow = 0;\n";
1373 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001374 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001375
Chris Lattneraadaf782008-01-31 19:51:04 +00001376 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001377
1378 startLoc = S->getTryBody()->getLocEnd();
1379 startBuf = SM->getCharacterData(startLoc);
1380
1381 assert((*startBuf == '}') && "bogus @try block");
Steve Naroffc9ba1722008-07-16 15:31:30 +00001382
Steve Naroff75730982007-11-07 04:08:17 +00001383 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffc9ba1722008-07-16 15:31:30 +00001384 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1385 if (catchList) {
1386 startLoc = startLoc.getFileLocWithOffset(1);
1387 buf = " /* @catch begin */ else {\n";
1388 buf += " id _caught = objc_exception_extract(&_stack);\n";
1389 buf += " objc_exception_try_enter (&_stack);\n";
1390 buf += " if (_setjmp(_stack.buf))\n";
1391 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1392 buf += " else { /* @catch continue */";
1393
1394 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001395 } else { /* no catch list */
1396 buf = "}\nelse {\n";
1397 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1398 buf += "}";
1399 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffc9ba1722008-07-16 15:31:30 +00001400 }
Steve Naroff75730982007-11-07 04:08:17 +00001401 bool sawIdTypedCatch = false;
1402 Stmt *lastCatchBody = 0;
Steve Naroff75730982007-11-07 04:08:17 +00001403 while (catchList) {
1404 Stmt *catchStmt = catchList->getCatchParamStmt();
1405
1406 if (catchList == S->getCatchStmts())
1407 buf = "if ("; // we are generating code for the first catch clause
1408 else
1409 buf = "else if (";
1410 startLoc = catchList->getLocStart();
1411 startBuf = SM->getCharacterData(startLoc);
1412
1413 assert((*startBuf == '@') && "bogus @catch location");
1414
1415 const char *lParenLoc = strchr(startBuf, '(');
1416
Steve Naroffbe4b3332008-02-01 22:08:12 +00001417 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001418 // Now rewrite the body...
1419 lastCatchBody = catchList->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001420 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1421 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner06767512008-04-08 05:52:18 +00001422 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1423 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001424 assert((*bodyBuf == '{') && "bogus @catch body location");
1425
1426 buf += "1) { id _tmp = _caught;";
1427 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1428 buf.c_str(), buf.size());
1429 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Ted Kremenek50a25e22008-10-06 22:39:38 +00001430 QualType t = dyn_cast<ValueDecl>(declStmt->getSolitaryDecl())->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001431 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001432 buf += "1) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001433 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001434 sawIdTypedCatch = true;
1435 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001436 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroff75730982007-11-07 04:08:17 +00001437
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001438 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001439 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001440 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001441 buf += cls->getDecl()->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001442 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001443 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001444 }
1445 }
1446 // Now rewrite the body...
1447 lastCatchBody = catchList->getCatchBody();
1448 SourceLocation rParenLoc = catchList->getRParenLoc();
1449 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1450 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1451 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1452 assert((*rParenBuf == ')') && "bogus @catch paren location");
1453 assert((*bodyBuf == '{') && "bogus @catch body location");
1454
1455 buf = " = _caught;";
1456 // Here we replace ") {" with "= _caught;" (which initializes and
1457 // declares the @catch parameter).
Chris Lattneraadaf782008-01-31 19:51:04 +00001458 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001459 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001460 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001461 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001462 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001463 catchList = catchList->getNextCatchStmt();
1464 }
1465 // Complete the catch list...
1466 if (lastCatchBody) {
1467 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001468 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1469 "bogus @catch body location");
Steve Naroff75730982007-11-07 04:08:17 +00001470
Steve Naroff378f47a2008-09-11 15:29:03 +00001471 // Insert the last (implicit) else clause *before* the right curly brace.
1472 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1473 buf = "} /* last catch end */\n";
1474 buf += "else {\n";
1475 buf += " _rethrow = _caught;\n";
1476 buf += " objc_exception_try_exit(&_stack);\n";
1477 buf += "} } /* @catch end */\n";
1478 if (!S->getFinallyStmt())
1479 buf += "}\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001480 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001481
1482 // Set lastCurlyLoc
1483 lastCurlyLoc = lastCatchBody->getLocEnd();
1484 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001485 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001486 startLoc = finalStmt->getLocStart();
1487 startBuf = SM->getCharacterData(startLoc);
1488 assert((*startBuf == '@') && "bogus @finally start");
1489
1490 buf = "/* @finally */";
Chris Lattneraadaf782008-01-31 19:51:04 +00001491 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001492
1493 Stmt *body = finalStmt->getFinallyBody();
1494 SourceLocation startLoc = body->getLocStart();
1495 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001496 assert(*SM->getCharacterData(startLoc) == '{' &&
1497 "bogus @finally body location");
1498 assert(*SM->getCharacterData(endLoc) == '}' &&
1499 "bogus @finally body location");
Steve Naroff75730982007-11-07 04:08:17 +00001500
1501 startLoc = startLoc.getFileLocWithOffset(1);
1502 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001503 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001504 endLoc = endLoc.getFileLocWithOffset(-1);
1505 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001506 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001507
1508 // Set lastCurlyLoc
1509 lastCurlyLoc = body->getLocEnd();
Steve Naroff378f47a2008-09-11 15:29:03 +00001510 } else { /* no finally clause - make sure we synthesize an implicit one */
1511 buf = "{ /* implicit finally clause */\n";
1512 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1513 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1514 buf += "}";
1515 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001516 }
1517 // Now emit the final closing curly brace...
1518 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1519 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001520 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001521 return 0;
1522}
1523
Steve Naroffb29b4272008-04-14 22:03:09 +00001524Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001525 return 0;
1526}
1527
Steve Naroffb29b4272008-04-14 22:03:09 +00001528Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001529 return 0;
1530}
1531
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001532// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff2bd03922007-11-07 15:32:26 +00001533// the throw expression is typically a message expression that's already
1534// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001535Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001536 // Get the start location and compute the semi location.
1537 SourceLocation startLoc = S->getLocStart();
1538 const char *startBuf = SM->getCharacterData(startLoc);
1539
1540 assert((*startBuf == '@') && "bogus @throw location");
1541
1542 std::string buf;
1543 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001544 if (S->getThrowExpr())
1545 buf = "objc_exception_throw(";
1546 else // add an implicit argument
1547 buf = "objc_exception_throw(_caught";
Steve Naroff4ba0acb2008-07-25 15:41:30 +00001548
1549 // handle "@ throw" correctly.
1550 const char *wBuf = strchr(startBuf, 'w');
1551 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1552 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
1553
Steve Naroff2bd03922007-11-07 15:32:26 +00001554 const char *semiBuf = strchr(startBuf, ';');
1555 assert((*semiBuf == ';') && "@throw: can't find ';'");
1556 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1557 buf = ");";
Chris Lattneraadaf782008-01-31 19:51:04 +00001558 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001559 return 0;
1560}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001561
Steve Naroffb29b4272008-04-14 22:03:09 +00001562Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001563 // Create a new string expression.
1564 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001565 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001566 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001567 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1568 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +00001569 SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001570 ReplaceStmt(Exp, Replacement);
Chris Lattnere365c502007-11-30 22:25:36 +00001571
Chris Lattner07506182007-11-30 22:53:43 +00001572 // Replace this subexpr in the parent.
Chris Lattnere64b7772007-10-24 16:57:36 +00001573 delete Exp;
1574 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001575}
1576
Steve Naroffb29b4272008-04-14 22:03:09 +00001577Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroffb42f8412007-11-05 14:50:49 +00001578 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1579 // Create a call to sel_registerName("selName").
1580 llvm::SmallVector<Expr*, 8> SelExprs;
1581 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner077bf5e2008-11-24 03:33:13 +00001582 SelExprs.push_back(new StringLiteral(Exp->getSelector().getAsString().c_str(),
1583 Exp->getSelector().getAsString().size(),
Steve Naroffb42f8412007-11-05 14:50:49 +00001584 false, argType, SourceLocation(),
1585 SourceLocation()));
1586 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1587 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001588 ReplaceStmt(Exp, SelExp);
Steve Naroffb42f8412007-11-05 14:50:49 +00001589 delete Exp;
1590 return SelExp;
1591}
1592
Steve Naroffb29b4272008-04-14 22:03:09 +00001593CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff934f2762007-10-24 22:48:43 +00001594 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001595 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001596 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +00001597
1598 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +00001599 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +00001600
1601 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001602 QualType pToFunc = Context->getPointerType(msgSendType);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001603 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE,
1604 /*isLvalue=*/false);
Steve Naroffebf2b562007-10-23 23:50:29 +00001605
1606 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +00001607
Steve Naroff934f2762007-10-24 22:48:43 +00001608 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1609}
1610
Steve Naroffd5255f52007-11-01 13:24:47 +00001611static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1612 const char *&startRef, const char *&endRef) {
1613 while (startBuf < endBuf) {
1614 if (*startBuf == '<')
1615 startRef = startBuf; // mark the start.
1616 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001617 if (startRef && *startRef == '<') {
1618 endRef = startBuf; // mark the end.
1619 return true;
1620 }
1621 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001622 }
1623 startBuf++;
1624 }
1625 return false;
1626}
1627
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001628static void scanToNextArgument(const char *&argRef) {
1629 int angle = 0;
1630 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1631 if (*argRef == '<')
1632 angle++;
1633 else if (*argRef == '>')
1634 angle--;
1635 argRef++;
1636 }
1637 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1638}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001639
Steve Naroffb29b4272008-04-14 22:03:09 +00001640bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001641
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001642 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001643 return true;
1644
Steve Naroffd5255f52007-11-01 13:24:47 +00001645 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +00001646 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001647 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff9165ad32007-10-31 04:38:33 +00001648 return true; // we have "Class <Protocol> *".
1649 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001650 return false;
1651}
1652
Steve Naroff4f95b752008-07-29 18:15:38 +00001653void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1654 QualType Type = E->getType();
1655 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00001656 SourceLocation Loc, EndLoc;
1657
1658 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
1659 Loc = ECE->getLParenLoc();
1660 EndLoc = ECE->getRParenLoc();
1661 } else {
1662 Loc = E->getLocStart();
1663 EndLoc = E->getLocEnd();
1664 }
1665 // This will defend against trying to rewrite synthesized expressions.
1666 if (Loc.isInvalid() || EndLoc.isInvalid())
1667 return;
1668
Steve Naroff4f95b752008-07-29 18:15:38 +00001669 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00001670 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00001671 const char *startRef = 0, *endRef = 0;
1672 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1673 // Get the locations of the startRef, endRef.
1674 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1675 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1676 // Comment out the protocol references.
1677 InsertText(LessLoc, "/*", 2);
1678 InsertText(GreaterLoc, "*/", 2);
1679 }
1680 }
1681}
1682
Steve Naroffb29b4272008-04-14 22:03:09 +00001683void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001684 SourceLocation Loc;
1685 QualType Type;
1686 const FunctionTypeProto *proto = 0;
1687 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1688 Loc = VD->getLocation();
1689 Type = VD->getType();
1690 }
1691 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1692 Loc = FD->getLocation();
1693 // Check for ObjC 'id' and class types that have been adorned with protocol
1694 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1695 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1696 assert(funcType && "missing function type");
1697 proto = dyn_cast<FunctionTypeProto>(funcType);
1698 if (!proto)
1699 return;
1700 Type = proto->getResultType();
1701 }
1702 else
1703 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001704
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001705 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001706 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001707
1708 const char *endBuf = SM->getCharacterData(Loc);
1709 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00001710 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001711 startBuf--; // scan backward (from the decl location) for return type.
1712 const char *startRef = 0, *endRef = 0;
1713 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1714 // Get the locations of the startRef, endRef.
1715 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1716 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1717 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001718 InsertText(LessLoc, "/*", 2);
1719 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001720 }
1721 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001722 if (!proto)
1723 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001724 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001725 const char *startBuf = SM->getCharacterData(Loc);
1726 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001727 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1728 if (needToScanForQualifiers(proto->getArgType(i))) {
1729 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001730
Steve Naroffd5255f52007-11-01 13:24:47 +00001731 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001732 // scan forward (from the decl location) for argument types.
1733 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001734 const char *startRef = 0, *endRef = 0;
1735 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1736 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001737 SourceLocation LessLoc =
1738 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1739 SourceLocation GreaterLoc =
1740 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001741 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001742 InsertText(LessLoc, "/*", 2);
1743 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001744 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001745 startBuf = ++endBuf;
1746 }
1747 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00001748 // If the function name is derived from a macro expansion, then the
1749 // argument buffer will not follow the name. Need to speak with Chris.
1750 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001751 startBuf++; // scan forward (from the decl location) for argument types.
1752 startBuf++;
1753 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001754 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001755}
1756
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001757// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00001758void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001759 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1760 llvm::SmallVector<QualType, 16> ArgTys;
1761 ArgTys.push_back(Context->getPointerType(
1762 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001763 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001764 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001765 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001766 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001767 SourceLocation(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001768 SelGetUidIdent, getFuncType,
1769 FunctionDecl::Extern, false, 0);
1770}
1771
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001772// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
Steve Naroffb29b4272008-04-14 22:03:09 +00001773void RewriteObjC::SynthGetProtocolFunctionDecl() {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001774 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1775 llvm::SmallVector<QualType, 16> ArgTys;
1776 ArgTys.push_back(Context->getPointerType(
1777 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001778 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001779 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001780 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001781 GetProtocolFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001782 SourceLocation(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001783 SelGetProtoIdent, getFuncType,
1784 FunctionDecl::Extern, false, 0);
1785}
1786
Steve Naroffb29b4272008-04-14 22:03:09 +00001787void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001788 // declared in <objc/objc.h>
Chris Lattner8ec03f52008-11-24 03:54:41 +00001789 if (strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001790 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001791 return;
1792 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001793 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001794}
1795
Steve Naroffc0a123c2008-03-11 17:37:02 +00001796// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00001797void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00001798 if (SuperContructorFunctionDecl)
1799 return;
1800 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_super");
1801 llvm::SmallVector<QualType, 16> ArgTys;
1802 QualType argT = Context->getObjCIdType();
1803 assert(!argT.isNull() && "Can't find 'id' type");
1804 ArgTys.push_back(argT);
1805 ArgTys.push_back(argT);
1806 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1807 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001808 false, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001809 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001810 SourceLocation(),
Steve Naroffc0a123c2008-03-11 17:37:02 +00001811 msgSendIdent, msgSendType,
1812 FunctionDecl::Extern, false, 0);
1813}
1814
Steve Naroff09b266e2007-10-30 23:14:51 +00001815// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001816void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00001817 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1818 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001819 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001820 assert(!argT.isNull() && "Can't find 'id' type");
1821 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001822 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001823 assert(!argT.isNull() && "Can't find 'SEL' type");
1824 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001825 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001826 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001827 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001828 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001829 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001830 msgSendIdent, msgSendType,
1831 FunctionDecl::Extern, false, 0);
1832}
1833
Steve Naroff874e2322007-11-15 10:28:18 +00001834// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001835void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00001836 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1837 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001838 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001839 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00001840 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00001841 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1842 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1843 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001844 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00001845 assert(!argT.isNull() && "Can't find 'SEL' type");
1846 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001847 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00001848 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001849 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001850 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001851 SourceLocation(),
Steve Naroff874e2322007-11-15 10:28:18 +00001852 msgSendIdent, msgSendType,
1853 FunctionDecl::Extern, false, 0);
1854}
1855
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001856// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001857void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001858 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1859 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001860 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001861 assert(!argT.isNull() && "Can't find 'id' type");
1862 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001863 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001864 assert(!argT.isNull() && "Can't find 'SEL' type");
1865 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001866 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001867 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001868 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001869 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001870 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001871 msgSendIdent, msgSendType,
1872 FunctionDecl::Extern, false, 0);
1873}
1874
1875// SynthMsgSendSuperStretFunctionDecl -
1876// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001877void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001878 IdentifierInfo *msgSendIdent =
1879 &Context->Idents.get("objc_msgSendSuper_stret");
1880 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001881 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001882 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00001883 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001884 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1885 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1886 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001887 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001888 assert(!argT.isNull() && "Can't find 'SEL' type");
1889 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001890 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001891 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001892 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001893 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnera98e58d2008-03-15 21:24:04 +00001894 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001895 msgSendIdent, msgSendType,
1896 FunctionDecl::Extern, false, 0);
1897}
1898
Steve Naroff1284db82008-05-08 22:02:18 +00001899// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001900void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001901 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1902 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001903 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001904 assert(!argT.isNull() && "Can't find 'id' type");
1905 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001906 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001907 assert(!argT.isNull() && "Can't find 'SEL' type");
1908 ArgTys.push_back(argT);
Steve Naroff1284db82008-05-08 22:02:18 +00001909 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001910 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001911 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001912 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001913 SourceLocation(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001914 msgSendIdent, msgSendType,
1915 FunctionDecl::Extern, false, 0);
1916}
1917
Steve Naroff09b266e2007-10-30 23:14:51 +00001918// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00001919void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00001920 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1921 llvm::SmallVector<QualType, 16> ArgTys;
1922 ArgTys.push_back(Context->getPointerType(
1923 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001924 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001925 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001926 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001927 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001928 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001929 getClassIdent, getClassType,
1930 FunctionDecl::Extern, false, 0);
1931}
1932
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001933// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00001934void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001935 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1936 llvm::SmallVector<QualType, 16> ArgTys;
1937 ArgTys.push_back(Context->getPointerType(
1938 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001939 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001940 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001941 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001942 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001943 SourceLocation(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001944 getClassIdent, getClassType,
1945 FunctionDecl::Extern, false, 0);
1946}
1947
Steve Naroffb29b4272008-04-14 22:03:09 +00001948Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001949 QualType strType = getConstantStringStructType();
1950
1951 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00001952
1953 std::string tmpName = InFileName;
1954 unsigned i;
1955 for (i=0; i < tmpName.length(); i++) {
1956 char c = tmpName.at(i);
1957 // replace any non alphanumeric characters with '_'.
1958 if (!isalpha(c) && (c < '0' || c > '9'))
1959 tmpName[i] = '_';
1960 }
1961 S += tmpName;
1962 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001963 S += utostr(NumObjCStringLiterals++);
1964
Steve Naroffba92b2e2008-03-27 22:29:16 +00001965 Preamble += "static __NSConstantStringImpl " + S;
1966 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
1967 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001968 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00001969 std::string prettyBufS;
1970 llvm::raw_string_ostream prettyBuf(prettyBufS);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001971 Exp->getString()->printPretty(prettyBuf);
Steve Naroffba92b2e2008-03-27 22:29:16 +00001972 Preamble += prettyBuf.str();
1973 Preamble += ",";
Steve Naroff3652c2d2008-03-15 01:36:04 +00001974 // The minus 2 removes the begin/end double quotes.
Steve Naroffba92b2e2008-03-27 22:29:16 +00001975 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001976
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001977 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Steve Naroff248a7532008-04-15 22:42:06 +00001978 &Context->Idents.get(S.c_str()), strType,
1979 VarDecl::Static, NULL);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001980 DeclRefExpr *DRE = new DeclRefExpr(NewVD, strType, SourceLocation());
1981 Expr *Unop = new UnaryOperator(DRE, UnaryOperator::AddrOf,
1982 Context->getPointerType(DRE->getType()),
1983 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00001984 // cast to NSConstantString *
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001985 CastExpr *cast = new CStyleCastExpr(Exp->getType(), Unop,
Steve Naroffb2f9e512008-11-03 23:29:32 +00001986 Exp->getType(), SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001987 ReplaceStmt(Exp, cast);
Steve Naroff96984642007-11-08 14:30:50 +00001988 delete Exp;
1989 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00001990}
1991
Steve Naroffb29b4272008-04-14 22:03:09 +00001992ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001993 // check if we are sending a message to 'super'
Steve Naroff54055232008-10-27 17:20:55 +00001994 if (!CurMethodDef || !CurMethodDef->isInstance()) return 0;
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001995
Douglas Gregorcd9b46e2008-11-04 14:56:14 +00001996 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
1997 const PointerType *PT = Super->getType()->getAsPointerType();
Chris Lattner0d17f6f2008-06-21 18:04:54 +00001998 assert(PT);
1999 ObjCInterfaceType *IT = cast<ObjCInterfaceType>(PT->getPointeeType());
2000 return IT->getDecl();
2001 }
2002 return 0;
Steve Naroff874e2322007-11-15 10:28:18 +00002003}
2004
2005// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002006QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002007 if (!SuperStructDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002008 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002009 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002010 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002011 QualType FieldTypes[2];
2012
2013 // struct objc_object *receiver;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002014 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002015 // struct objc_class *super;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002016 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff874e2322007-11-15 10:28:18 +00002017 // Create fields
2018 FieldDecl *FieldDecls[2];
2019
2020 for (unsigned i = 0; i < 2; ++i)
Chris Lattnerb048c982008-04-06 04:47:34 +00002021 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00002022 FieldTypes[i]);
Steve Naroff874e2322007-11-15 10:28:18 +00002023
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002024 SuperStructDecl->defineBody(*Context, FieldDecls, 4);
Steve Naroff874e2322007-11-15 10:28:18 +00002025 }
2026 return Context->getTagDeclType(SuperStructDecl);
2027}
2028
Steve Naroffb29b4272008-04-14 22:03:09 +00002029QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002030 if (!ConstantStringDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002031 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002032 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002033 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002034 QualType FieldTypes[4];
2035
2036 // struct objc_object *receiver;
2037 FieldTypes[0] = Context->getObjCIdType();
2038 // int flags;
2039 FieldTypes[1] = Context->IntTy;
2040 // char *str;
2041 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2042 // long length;
2043 FieldTypes[3] = Context->LongTy;
2044 // Create fields
Steve Naroff9630ec52008-03-27 22:59:54 +00002045 FieldDecl *FieldDecls[4];
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002046
2047 for (unsigned i = 0; i < 4; ++i)
Chris Lattnerb048c982008-04-06 04:47:34 +00002048 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00002049 FieldTypes[i]);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002050
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002051 ConstantStringDecl->defineBody(*Context, FieldDecls, 4);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002052 }
2053 return Context->getTagDeclType(ConstantStringDecl);
2054}
2055
Steve Naroffb29b4272008-04-14 22:03:09 +00002056Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002057 if (!SelGetUidFunctionDecl)
2058 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002059 if (!MsgSendFunctionDecl)
2060 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002061 if (!MsgSendSuperFunctionDecl)
2062 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002063 if (!MsgSendStretFunctionDecl)
2064 SynthMsgSendStretFunctionDecl();
2065 if (!MsgSendSuperStretFunctionDecl)
2066 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002067 if (!MsgSendFpretFunctionDecl)
2068 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002069 if (!GetClassFunctionDecl)
2070 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002071 if (!GetMetaClassFunctionDecl)
2072 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002073
Steve Naroff874e2322007-11-15 10:28:18 +00002074 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002075 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2076 // May need to use objc_msgSend_stret() as well.
2077 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002078 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002079 QualType resultType = mDecl->getResultType();
Chris Lattner8b51fd72008-07-26 22:36:27 +00002080 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002081 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002082 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002083 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002084 }
Steve Naroff874e2322007-11-15 10:28:18 +00002085
Steve Naroff934f2762007-10-24 22:48:43 +00002086 // Synthesize a call to objc_msgSend().
2087 llvm::SmallVector<Expr*, 8> MsgExprs;
2088 IdentifierInfo *clsName = Exp->getClassName();
2089
2090 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2091 if (clsName) { // class message.
Steve Narofffc93d522008-07-24 19:44:33 +00002092 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2093 // the 'super' idiom within a class method.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002094 if (!strcmp(clsName->getName(), "super")) {
2095 MsgSendFlavor = MsgSendSuperFunctionDecl;
2096 if (MsgSendStretFlavor)
2097 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2098 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2099
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002100 ObjCInterfaceDecl *SuperDecl =
Steve Naroff54055232008-10-27 17:20:55 +00002101 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002102
2103 llvm::SmallVector<Expr*, 4> InitExprs;
2104
2105 // set the receiver to self, the first argument to all methods.
Chris Lattner41110242008-06-17 18:05:57 +00002106 InitExprs.push_back(new DeclRefExpr(
Steve Naroff54055232008-10-27 17:20:55 +00002107 CurMethodDef->getSelfDecl(),
Chris Lattner41110242008-06-17 18:05:57 +00002108 Context->getObjCIdType(),
2109 SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002110 llvm::SmallVector<Expr*, 8> ClsExprs;
2111 QualType argType = Context->getPointerType(Context->CharTy);
2112 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2113 SuperDecl->getIdentifier()->getLength(),
2114 false, argType, SourceLocation(),
2115 SourceLocation()));
2116 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2117 &ClsExprs[0],
2118 ClsExprs.size());
2119 // To turn off a warning, type-cast to 'id'
Douglas Gregor49badde2008-10-27 19:41:14 +00002120 InitExprs.push_back( // set 'super class', using objc_getClass().
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002121 new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002122 Cls, Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002123 SourceLocation(), SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002124 // struct objc_super
2125 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00002126 Expr *SuperRep;
Steve Naroffc0a123c2008-03-11 17:37:02 +00002127
Steve Naroff23f41272008-03-11 18:14:26 +00002128 if (LangOpts.Microsoft) {
2129 SynthSuperContructorFunctionDecl();
2130 // Simulate a contructor call...
2131 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2132 superType, SourceLocation());
2133 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2134 superType, SourceLocation());
2135 } else {
2136 // (struct objc_super) { <exprs from above> }
2137 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2138 &InitExprs[0], InitExprs.size(),
Chris Lattner418f6c72008-10-26 23:43:26 +00002139 SourceLocation(), false);
2140 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE,
2141 false);
Steve Naroff23f41272008-03-11 18:14:26 +00002142 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002143 // struct objc_super *
2144 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2145 Context->getPointerType(SuperRep->getType()),
2146 SourceLocation());
2147 MsgExprs.push_back(Unop);
2148 } else {
2149 llvm::SmallVector<Expr*, 8> ClsExprs;
2150 QualType argType = Context->getPointerType(Context->CharTy);
2151 ClsExprs.push_back(new StringLiteral(clsName->getName(),
2152 clsName->getLength(),
2153 false, argType, SourceLocation(),
2154 SourceLocation()));
2155 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2156 &ClsExprs[0],
2157 ClsExprs.size());
2158 MsgExprs.push_back(Cls);
2159 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002160 } else { // instance message.
2161 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00002162
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002163 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00002164 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002165 if (MsgSendStretFlavor)
2166 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00002167 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2168
2169 llvm::SmallVector<Expr*, 4> InitExprs;
2170
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002171 InitExprs.push_back(
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002172 new CStyleCastExpr(Context->getObjCIdType(),
Steve Naroff54055232008-10-27 17:20:55 +00002173 new DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Narofff616ebb2008-07-16 22:35:27 +00002174 Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002175 SourceLocation()),
2176 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002177 SourceLocation(), SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00002178
2179 llvm::SmallVector<Expr*, 8> ClsExprs;
2180 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002181 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2182 SuperDecl->getIdentifier()->getLength(),
Steve Naroff874e2322007-11-15 10:28:18 +00002183 false, argType, SourceLocation(),
2184 SourceLocation()));
2185 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002186 &ClsExprs[0],
2187 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00002188 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002189 InitExprs.push_back(
Douglas Gregor49badde2008-10-27 19:41:14 +00002190 // set 'super class', using objc_getClass().
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002191 new CStyleCastExpr(Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002192 Cls, Context->getObjCIdType(), SourceLocation(), SourceLocation()));
Steve Naroff874e2322007-11-15 10:28:18 +00002193 // struct objc_super
2194 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00002195 Expr *SuperRep;
2196
2197 if (LangOpts.Microsoft) {
2198 SynthSuperContructorFunctionDecl();
2199 // Simulate a contructor call...
2200 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2201 superType, SourceLocation());
2202 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2203 superType, SourceLocation());
2204 } else {
2205 // (struct objc_super) { <exprs from above> }
2206 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2207 &InitExprs[0], InitExprs.size(),
Chris Lattner418f6c72008-10-26 23:43:26 +00002208 SourceLocation(), false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002209 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
2210 }
Steve Naroff874e2322007-11-15 10:28:18 +00002211 // struct objc_super *
2212 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2213 Context->getPointerType(SuperRep->getType()),
2214 SourceLocation());
2215 MsgExprs.push_back(Unop);
2216 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002217 // Remove all type-casts because it may contain objc-style types; e.g.
2218 // Foo<Proto> *.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002219 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002220 recExpr = CE->getSubExpr();
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002221 recExpr = new CStyleCastExpr(Context->getObjCIdType(), recExpr,
Douglas Gregor49badde2008-10-27 19:41:14 +00002222 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002223 SourceLocation(), SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00002224 MsgExprs.push_back(recExpr);
2225 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002226 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00002227 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002228 llvm::SmallVector<Expr*, 8> SelExprs;
2229 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner077bf5e2008-11-24 03:33:13 +00002230 SelExprs.push_back(new StringLiteral(Exp->getSelector().getAsString().c_str(),
2231 Exp->getSelector().getAsString().size(),
Steve Naroff934f2762007-10-24 22:48:43 +00002232 false, argType, SourceLocation(),
2233 SourceLocation()));
2234 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2235 &SelExprs[0], SelExprs.size());
2236 MsgExprs.push_back(SelExp);
2237
2238 // Now push any user supplied arguments.
2239 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002240 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002241 // Make all implicit casts explicit...ICE comes in handy:-)
2242 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2243 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregor49badde2008-10-27 19:41:14 +00002244 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002245 ? Context->getObjCIdType()
Douglas Gregor49badde2008-10-27 19:41:14 +00002246 : ICE->getType();
Steve Naroffb2f9e512008-11-03 23:29:32 +00002247 userExpr = new CStyleCastExpr(type, userExpr, type, SourceLocation(), SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002248 }
2249 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002250 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002251 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002252 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002253 userExpr = CE->getSubExpr();
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002254 userExpr = new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002255 userExpr, Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002256 SourceLocation(), SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002257 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00002258 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002259 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00002260 // We've transferred the ownership to MsgExprs. Null out the argument in
2261 // the original expression, since we will delete it below.
2262 Exp->setArg(i, 0);
2263 }
Steve Naroffab972d32007-11-04 22:37:50 +00002264 // Generate the funky cast.
2265 CastExpr *cast;
2266 llvm::SmallVector<QualType, 8> ArgTypes;
2267 QualType returnType;
2268
2269 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002270 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2271 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2272 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002273 ArgTypes.push_back(Context->getObjCIdType());
2274 ArgTypes.push_back(Context->getObjCSelType());
2275 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002276 // Push any user argument types.
Chris Lattner58cce3b2008-03-16 01:07:14 +00002277 for (unsigned i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002278 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
2279 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002280 : mDecl->getParamDecl(i)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00002281 // Make sure we convert "t (^)(...)" to "t (*)(...)".
2282 if (isBlockPointerType(t)) {
2283 const BlockPointerType *BPT = t->getAsBlockPointerType();
2284 t = Context->getPointerType(BPT->getPointeeType());
2285 }
Steve Naroff352336b2007-11-05 14:36:37 +00002286 ArgTypes.push_back(t);
2287 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002288 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
2289 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00002290 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002291 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002292 }
2293 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002294 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00002295
2296 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002297 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
2298 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002299
2300 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2301 // If we don't do this cast, we get the following bizarre warning/note:
2302 // xx.m:13: warning: function called through a non-compatible type
2303 // xx.m:13: note: if this code is reached, the program will abort
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002304 cast = new CStyleCastExpr(Context->getPointerType(Context->VoidTy), DRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002305 Context->getPointerType(Context->VoidTy),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002306 SourceLocation(), SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00002307
Steve Naroffab972d32007-11-04 22:37:50 +00002308 // Now do the "normal" pointer to function cast.
2309 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002310 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00002311 // If we don't have a method decl, force a variadic cast.
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002312 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Naroffab972d32007-11-04 22:37:50 +00002313 castType = Context->getPointerType(castType);
Steve Naroffb2f9e512008-11-03 23:29:32 +00002314 cast = new CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002315
2316 // Don't forget the parens to enforce the proper binding.
2317 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2318
2319 const FunctionType *FT = msgSendType->getAsFunctionType();
2320 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2321 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002322 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002323 if (MsgSendStretFlavor) {
2324 // We have the method which returns a struct/union. Must also generate
2325 // call to objc_msgSend_stret and hang both varieties on a conditional
2326 // expression which dictate which one to envoke depending on size of
2327 // method's return type.
2328
2329 // Create a reference to the objc_msgSend_stret() declaration.
2330 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
2331 SourceLocation());
2332 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002333 cast = new CStyleCastExpr(Context->getPointerType(Context->VoidTy), STDRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002334 Context->getPointerType(Context->VoidTy),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002335 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002336 // Now do the "normal" pointer to function cast.
2337 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002338 &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002339 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002340 castType = Context->getPointerType(castType);
Steve Naroffb2f9e512008-11-03 23:29:32 +00002341 cast = new CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002342
2343 // Don't forget the parens to enforce the proper binding.
2344 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2345
2346 FT = msgSendType->getAsFunctionType();
2347 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2348 FT->getResultType(), SourceLocation());
2349
2350 // Build sizeof(returnType)
Sebastian Redl05189992008-11-11 17:56:53 +00002351 SizeOfAlignOfExpr *sizeofExpr = new SizeOfAlignOfExpr(true, true,
2352 returnType.getAsOpaquePtr(),
2353 Context->getSizeType(),
2354 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002355 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2356 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2357 // For X86 it is more complicated and some kind of target specific routine
2358 // is needed to decide what to do.
Chris Lattner98be4942008-03-05 18:54:05 +00002359 unsigned IntSize =
2360 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002361 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2362 Context->IntTy,
2363 SourceLocation());
2364 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2365 BinaryOperator::LE,
2366 Context->IntTy,
2367 SourceLocation());
2368 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2369 ConditionalOperator *CondExpr =
2370 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002371 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002372 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002373 return ReplacingStmt;
2374}
2375
Steve Naroffb29b4272008-04-14 22:03:09 +00002376Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002377 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff80c28552008-10-27 20:54:44 +00002378
Steve Naroff934f2762007-10-24 22:48:43 +00002379 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002380 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff934f2762007-10-24 22:48:43 +00002381
Chris Lattnere64b7772007-10-24 16:57:36 +00002382 delete Exp;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002383 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002384}
2385
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002386/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2387/// call to objc_getProtocol("proto-name").
Steve Naroffb29b4272008-04-14 22:03:09 +00002388Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002389 if (!GetProtocolFunctionDecl)
2390 SynthGetProtocolFunctionDecl();
2391 // Create a call to objc_getProtocol("ProtocolName").
2392 llvm::SmallVector<Expr*, 8> ProtoExprs;
2393 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner8ec03f52008-11-24 03:54:41 +00002394 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getNameAsCString(),
2395 strlen(Exp->getProtocol()->getNameAsCString()),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002396 false, argType, SourceLocation(),
2397 SourceLocation()));
2398 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2399 &ProtoExprs[0],
2400 ProtoExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002401 ReplaceStmt(Exp, ProtoExp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002402 delete Exp;
2403 return ProtoExp;
2404
2405}
2406
Steve Naroffbaf58c32008-05-31 14:15:04 +00002407bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
2408 const char *endBuf) {
2409 while (startBuf < endBuf) {
2410 if (*startBuf == '#') {
2411 // Skip whitespace.
2412 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2413 ;
2414 if (!strncmp(startBuf, "if", strlen("if")) ||
2415 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2416 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2417 !strncmp(startBuf, "define", strlen("define")) ||
2418 !strncmp(startBuf, "undef", strlen("undef")) ||
2419 !strncmp(startBuf, "else", strlen("else")) ||
2420 !strncmp(startBuf, "elif", strlen("elif")) ||
2421 !strncmp(startBuf, "endif", strlen("endif")) ||
2422 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2423 !strncmp(startBuf, "include", strlen("include")) ||
2424 !strncmp(startBuf, "import", strlen("import")) ||
2425 !strncmp(startBuf, "include_next", strlen("include_next")))
2426 return true;
2427 }
2428 startBuf++;
2429 }
2430 return false;
2431}
2432
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002433/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002434/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00002435void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002436 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002437 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Chris Lattner8ec03f52008-11-24 03:54:41 +00002438 assert(CDecl->getNameAsCString() &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002439 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002440 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002441 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002442 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002443 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002444 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00002445 SourceLocation LocStart = CDecl->getLocStart();
2446 SourceLocation LocEnd = CDecl->getLocEnd();
2447
2448 const char *startBuf = SM->getCharacterData(LocStart);
2449 const char *endBuf = SM->getCharacterData(LocEnd);
Steve Naroffbaf58c32008-05-31 14:15:04 +00002450
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002451 // If no ivars and no root or if its root, directly or indirectly,
2452 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002453 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2454 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002455 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattneraadaf782008-01-31 19:51:04 +00002456 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002457 return;
2458 }
2459
2460 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002461 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002462 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002463 Result += CDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002464 if (LangOpts.Microsoft)
2465 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00002466
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002467 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002468 const char *cursor = strchr(startBuf, '{');
2469 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002470 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00002471 // If the buffer contains preprocessor directives, we do more fine-grained
2472 // rewrites. This is intended to fix code that looks like (which occurs in
2473 // NSURL.h, for example):
2474 //
2475 // #ifdef XYZ
2476 // @interface Foo : NSObject
2477 // #else
2478 // @interface FooBar : NSObject
2479 // #endif
2480 // {
2481 // int i;
2482 // }
2483 // @end
2484 //
2485 // This clause is segregated to avoid breaking the common case.
2486 if (BufferContainsPPDirectives(startBuf, cursor)) {
2487 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
2488 CDecl->getClassLoc();
2489 const char *endHeader = SM->getCharacterData(L);
2490 endHeader += Lexer::MeasureTokenLength(L, *SM);
2491
Chris Lattner3db6cae2008-07-21 18:19:38 +00002492 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00002493 // advance to the end of the referenced protocols.
2494 while (endHeader < cursor && *endHeader != '>') endHeader++;
2495 endHeader++;
2496 }
2497 // rewrite the original header
2498 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2499 } else {
2500 // rewrite the original header *without* disturbing the '{'
2501 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
2502 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002503 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002504 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002505 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002506 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002507 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00002508 Result += "_IVARS;\n";
Steve Narofffea763e82007-11-14 19:25:57 +00002509
2510 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002511 SourceLocation OnePastCurly =
2512 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2513 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002514 }
2515 cursor++; // past '{'
2516
2517 // Now comment out any visibility specifiers.
2518 while (cursor < endBuf) {
2519 if (*cursor == '@') {
2520 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002521 // Skip whitespace.
2522 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2523 /*scan*/;
2524
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002525 // FIXME: presence of @public, etc. inside comment results in
2526 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002527 if (!strncmp(cursor, "public", strlen("public")) ||
2528 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00002529 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002530 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002531 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002532 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002533 // FIXME: If there are cases where '<' is used in ivar declaration part
2534 // of user code, then scan the ivar list and use needToScanForQualifiers
2535 // for type checking.
2536 else if (*cursor == '<') {
2537 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002538 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002539 cursor = strchr(cursor, '>');
2540 cursor++;
2541 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002542 InsertText(atLoc, " */", 3);
Steve Naroffced80a82008-10-30 12:09:33 +00002543 } else if (*cursor == '^') { // rewrite block specifier.
2544 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2545 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002546 }
Steve Narofffea763e82007-11-14 19:25:57 +00002547 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002548 }
Steve Narofffea763e82007-11-14 19:25:57 +00002549 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002550 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00002551 } else { // we don't have any instance variables - insert super struct.
2552 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2553 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002554 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002555 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002556 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00002557 Result += "_IVARS;\n};\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00002558 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002559 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002560 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002561 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00002562 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002563}
2564
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002565// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002566/// class methods.
Steve Naroffb29b4272008-04-14 22:03:09 +00002567void RewriteObjC::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002568 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002569 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002570 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002571 const char *ClassName,
2572 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002573 if (MethodBegin == MethodEnd) return;
2574
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002575 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002576 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002577 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002578 SEL _cmd;
2579 char *method_types;
2580 void *_imp;
2581 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002582 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002583 Result += "\nstruct _objc_method {\n";
2584 Result += "\tSEL _cmd;\n";
2585 Result += "\tchar *method_types;\n";
2586 Result += "\tvoid *_imp;\n";
2587 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002588
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002589 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002590 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002591
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002592 // Build _objc_method_list for class's methods if needed
Steve Naroff946a6932008-03-11 00:12:29 +00002593
2594 /* struct {
2595 struct _objc_method_list *next_method;
2596 int method_count;
2597 struct _objc_method method_list[];
2598 }
2599 */
2600 Result += "\nstatic struct {\n";
2601 Result += "\tstruct _objc_method_list *next_method;\n";
2602 Result += "\tint method_count;\n";
2603 Result += "\tstruct _objc_method method_list[";
2604 Result += utostr(MethodEnd-MethodBegin);
2605 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002606 Result += prefix;
2607 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2608 Result += "_METHODS_";
2609 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002610 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002611 Result += IsInstanceMethod ? "inst" : "cls";
2612 Result += "_meth\")))= ";
2613 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002614
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002615 Result += "\t,{{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002616 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002617 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002618 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002619 Result += "\", \"";
2620 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002621 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002622 Result += MethodInternalNames[*MethodBegin];
2623 Result += "}\n";
2624 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2625 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002626 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002627 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002628 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002629 Result += "\", \"";
2630 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002631 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002632 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002633 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002634 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002635 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002636}
2637
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002638/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00002639void RewriteObjC::
2640RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
2641 const char *prefix,
2642 const char *ClassName,
2643 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002644 static bool objc_protocol_methods = false;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002645 if (Protocols.empty()) return;
2646
2647 for (unsigned i = 0; i != Protocols.size(); i++) {
2648 ObjCProtocolDecl *PDecl = Protocols[i];
2649 // Output struct protocol_methods holder of method selector and type.
2650 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
2651 /* struct protocol_methods {
2652 SEL _cmd;
2653 char *method_types;
2654 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002655 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002656 Result += "\nstruct protocol_methods {\n";
2657 Result += "\tSEL _cmd;\n";
2658 Result += "\tchar *method_types;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002659 Result += "};\n";
Steve Narofffbfe8252008-05-06 18:26:51 +00002660
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002661 objc_protocol_methods = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002662 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002663 // Do not synthesize the protocol more than once.
2664 if (ObjCSynthesizedProtocols.count(PDecl))
2665 continue;
2666
2667 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2668 unsigned NumMethods = PDecl->getNumInstanceMethods();
2669 /* struct _objc_protocol_method_list {
2670 int protocol_method_count;
2671 struct protocol_methods protocols[];
2672 }
2673 */
2674 Result += "\nstatic struct {\n";
2675 Result += "\tint protocol_method_count;\n";
2676 Result += "\tstruct protocol_methods protocols[";
2677 Result += utostr(NumMethods);
2678 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002679 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002680 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
2681 "{\n\t" + utostr(NumMethods) + "\n";
2682
2683 // Output instance methods declared in this protocol.
2684 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
2685 E = PDecl->instmeth_end(); I != E; ++I) {
2686 if (I == PDecl->instmeth_begin())
2687 Result += "\t ,{{(SEL)\"";
2688 else
2689 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002690 Result += (*I)->getSelector().getAsString().c_str();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002691 std::string MethodTypeString;
2692 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2693 Result += "\", \"";
2694 Result += MethodTypeString;
2695 Result += "\"}\n";
2696 }
2697 Result += "\t }\n};\n";
2698 }
2699
2700 // Output class methods declared in this protocol.
2701 int NumMethods = PDecl->getNumClassMethods();
2702 if (NumMethods > 0) {
2703 /* struct _objc_protocol_method_list {
2704 int protocol_method_count;
2705 struct protocol_methods protocols[];
2706 }
2707 */
2708 Result += "\nstatic struct {\n";
2709 Result += "\tint protocol_method_count;\n";
2710 Result += "\tstruct protocol_methods protocols[";
2711 Result += utostr(NumMethods);
2712 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002713 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002714 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2715 "{\n\t";
2716 Result += utostr(NumMethods);
2717 Result += "\n";
2718
2719 // Output instance methods declared in this protocol.
2720 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
2721 E = PDecl->classmeth_end(); I != E; ++I) {
2722 if (I == PDecl->classmeth_begin())
2723 Result += "\t ,{{(SEL)\"";
2724 else
2725 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002726 Result += (*I)->getSelector().getAsString().c_str();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002727 std::string MethodTypeString;
2728 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2729 Result += "\", \"";
2730 Result += MethodTypeString;
2731 Result += "\"}\n";
2732 }
2733 Result += "\t }\n};\n";
2734 }
2735
2736 // Output:
2737 /* struct _objc_protocol {
2738 // Objective-C 1.0 extensions
2739 struct _objc_protocol_extension *isa;
2740 char *protocol_name;
2741 struct _objc_protocol **protocol_list;
2742 struct _objc_protocol_method_list *instance_methods;
2743 struct _objc_protocol_method_list *class_methods;
2744 };
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002745 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002746 static bool objc_protocol = false;
2747 if (!objc_protocol) {
2748 Result += "\nstruct _objc_protocol {\n";
2749 Result += "\tstruct _objc_protocol_extension *isa;\n";
2750 Result += "\tchar *protocol_name;\n";
2751 Result += "\tstruct _objc_protocol **protocol_list;\n";
2752 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2753 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2754 Result += "};\n";
2755
2756 objc_protocol = true;
2757 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002758
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002759 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002760 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002761 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
2762 "{\n\t0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002763 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002764 Result += "\", 0, ";
2765 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2766 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002767 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002768 Result += ", ";
2769 }
2770 else
2771 Result += "0, ";
2772 if (PDecl->getNumClassMethods() > 0) {
2773 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002774 Result += PDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002775 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002776 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002777 else
2778 Result += "0\n";
2779 Result += "};\n";
2780
2781 // Mark this protocol as having been generated.
2782 if (!ObjCSynthesizedProtocols.insert(PDecl))
2783 assert(false && "protocol already synthesized");
2784 }
2785 // Output the top lovel protocol meta-data for the class.
2786 /* struct _objc_protocol_list {
2787 struct _objc_protocol_list *next;
2788 int protocol_count;
2789 struct _objc_protocol *class_protocols[];
2790 }
2791 */
2792 Result += "\nstatic struct {\n";
2793 Result += "\tstruct _objc_protocol_list *next;\n";
2794 Result += "\tint protocol_count;\n";
2795 Result += "\tstruct _objc_protocol *class_protocols[";
2796 Result += utostr(Protocols.size());
2797 Result += "];\n} _OBJC_";
2798 Result += prefix;
2799 Result += "_PROTOCOLS_";
2800 Result += ClassName;
2801 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2802 "{\n\t0, ";
2803 Result += utostr(Protocols.size());
2804 Result += "\n";
2805
2806 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002807 Result += Protocols[0]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002808 Result += " \n";
2809
2810 for (unsigned i = 1; i != Protocols.size(); i++) {
2811 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002812 Result += Protocols[i]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002813 Result += "\n";
2814 }
2815 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002816}
2817
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002818/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002819/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00002820void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002821 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002822 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002823 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002824 ObjCCategoryDecl *CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002825 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2826 CDecl = CDecl->getNextClassCategory())
2827 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2828 break;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002829
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002830 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00002831 FullCategoryName += '_';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002832 FullCategoryName += IDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00002833
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002834 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002835 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002836 true, "CATEGORY_", FullCategoryName.c_str(),
2837 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002838
2839 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002840 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002841 false, "CATEGORY_", FullCategoryName.c_str(),
2842 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002843
2844 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002845 // Null CDecl is case of a category implementation with no category interface
2846 if (CDecl)
Chris Lattner780f3292008-07-21 21:32:27 +00002847 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Chris Lattnereb44eee2007-12-23 01:40:15 +00002848 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002849
2850 /* struct _objc_category {
2851 char *category_name;
2852 char *class_name;
2853 struct _objc_method_list *instance_methods;
2854 struct _objc_method_list *class_methods;
2855 struct _objc_protocol_list *protocols;
2856 // Objective-C 1.0 extensions
2857 uint32_t size; // sizeof (struct _objc_category)
2858 struct _objc_property_list *instance_properties; // category's own
2859 // @property decl.
2860 };
2861 */
2862
2863 static bool objc_category = false;
2864 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002865 Result += "\nstruct _objc_category {\n";
2866 Result += "\tchar *category_name;\n";
2867 Result += "\tchar *class_name;\n";
2868 Result += "\tstruct _objc_method_list *instance_methods;\n";
2869 Result += "\tstruct _objc_method_list *class_methods;\n";
2870 Result += "\tstruct _objc_protocol_list *protocols;\n";
2871 Result += "\tunsigned int size;\n";
2872 Result += "\tstruct _objc_property_list *instance_properties;\n";
2873 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002874 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002875 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002876 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2877 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002878 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002879 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002880 Result += "\"\n\t, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002881 Result += ClassDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002882 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002883
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002884 if (IDecl->getNumInstanceMethods() > 0) {
2885 Result += "\t, (struct _objc_method_list *)"
2886 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2887 Result += FullCategoryName;
2888 Result += "\n";
2889 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002890 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002891 Result += "\t, 0\n";
2892 if (IDecl->getNumClassMethods() > 0) {
2893 Result += "\t, (struct _objc_method_list *)"
2894 "&_OBJC_CATEGORY_CLASS_METHODS_";
2895 Result += FullCategoryName;
2896 Result += "\n";
2897 }
2898 else
2899 Result += "\t, 0\n";
2900
Chris Lattner780f3292008-07-21 21:32:27 +00002901 if (CDecl && !CDecl->getReferencedProtocols().empty()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002902 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2903 Result += FullCategoryName;
2904 Result += "\n";
2905 }
2906 else
2907 Result += "\t, 0\n";
2908 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002909}
2910
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002911/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2912/// ivar offset.
Steve Naroffb29b4272008-04-14 22:03:09 +00002913void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002914 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002915 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00002916 if (ivar->isBitField()) {
2917 // FIXME: The hack below doesn't work for bitfields. For now, we simply
2918 // place all bitfields at offset 0.
2919 Result += "0";
2920 } else {
2921 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002922 Result += IDecl->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00002923 if (LangOpts.Microsoft)
2924 Result += "_IMPL";
2925 Result += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002926 Result += ivar->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00002927 Result += ")";
2928 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002929}
2930
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002931//===----------------------------------------------------------------------===//
2932// Meta Data Emission
2933//===----------------------------------------------------------------------===//
2934
Steve Naroffb29b4272008-04-14 22:03:09 +00002935void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002936 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002937 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002938
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002939 // Explictly declared @interface's are already synthesized.
2940 if (CDecl->ImplicitInterfaceDecl()) {
2941 // FIXME: Implementation of a class with no @interface (legacy) doese not
2942 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002943 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002944 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002945
Chris Lattnerbe6df082007-12-12 07:56:42 +00002946 // Build _objc_ivar_list metadata for classes ivars if needed
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002947 unsigned NumIvars = !IDecl->ivar_empty()
2948 ? IDecl->ivar_size()
2949 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002950 if (NumIvars > 0) {
2951 static bool objc_ivar = false;
2952 if (!objc_ivar) {
2953 /* struct _objc_ivar {
2954 char *ivar_name;
2955 char *ivar_type;
2956 int ivar_offset;
2957 };
2958 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002959 Result += "\nstruct _objc_ivar {\n";
2960 Result += "\tchar *ivar_name;\n";
2961 Result += "\tchar *ivar_type;\n";
2962 Result += "\tint ivar_offset;\n";
2963 Result += "};\n";
2964
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002965 objc_ivar = true;
2966 }
2967
Steve Naroff946a6932008-03-11 00:12:29 +00002968 /* struct {
2969 int ivar_count;
2970 struct _objc_ivar ivar_list[nIvars];
2971 };
2972 */
2973 Result += "\nstatic struct {\n";
2974 Result += "\tint ivar_count;\n";
2975 Result += "\tstruct _objc_ivar ivar_list[";
2976 Result += utostr(NumIvars);
2977 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002978 Result += IDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00002979 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002980 "{\n\t";
2981 Result += utostr(NumIvars);
2982 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002983
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002984 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002985 if (!IDecl->ivar_empty()) {
Chris Lattnerbe6df082007-12-12 07:56:42 +00002986 IVI = IDecl->ivar_begin();
2987 IVE = IDecl->ivar_end();
2988 } else {
2989 IVI = CDecl->ivar_begin();
2990 IVE = CDecl->ivar_end();
2991 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002992 Result += "\t,{{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002993 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002994 Result += "\", \"";
2995 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002996 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002997 Result += StrEncoding;
2998 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002999 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003000 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003001 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003002 Result += "\t ,{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003003 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003004 Result += "\", \"";
3005 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003006 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003007 Result += StrEncoding;
3008 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003009 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003010 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003011 }
3012
3013 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003014 }
3015
3016 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003017 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003018 true, "", IDecl->getNameAsCString(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003019
3020 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003021 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003022 false, "", IDecl->getNameAsCString(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003023
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003024 // Protocols referenced in class declaration?
Chris Lattner780f3292008-07-21 21:32:27 +00003025 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003026 "CLASS", CDecl->getNameAsCString(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003027
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003028
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003029 // Declaration of class/meta-class metadata
3030 /* struct _objc_class {
3031 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003032 const char *super_class_name;
3033 char *name;
3034 long version;
3035 long info;
3036 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003037 struct _objc_ivar_list *ivars;
3038 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003039 struct objc_cache *cache;
3040 struct objc_protocol_list *protocols;
3041 const char *ivar_layout;
3042 struct _objc_class_ext *ext;
3043 };
3044 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003045 static bool objc_class = false;
3046 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003047 Result += "\nstruct _objc_class {\n";
3048 Result += "\tstruct _objc_class *isa;\n";
3049 Result += "\tconst char *super_class_name;\n";
3050 Result += "\tchar *name;\n";
3051 Result += "\tlong version;\n";
3052 Result += "\tlong info;\n";
3053 Result += "\tlong instance_size;\n";
3054 Result += "\tstruct _objc_ivar_list *ivars;\n";
3055 Result += "\tstruct _objc_method_list *methods;\n";
3056 Result += "\tstruct objc_cache *cache;\n";
3057 Result += "\tstruct _objc_protocol_list *protocols;\n";
3058 Result += "\tconst char *ivar_layout;\n";
3059 Result += "\tstruct _objc_class_ext *ext;\n";
3060 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003061 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003062 }
3063
3064 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003065 ObjCInterfaceDecl *RootClass = 0;
3066 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003067 while (SuperClass) {
3068 RootClass = SuperClass;
3069 SuperClass = SuperClass->getSuperClass();
3070 }
3071 SuperClass = CDecl->getSuperClass();
3072
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003073 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003074 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003075 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003076 "{\n\t(struct _objc_class *)\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003077 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003078 Result += "\"";
3079
3080 if (SuperClass) {
3081 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003082 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003083 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003084 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003085 Result += "\"";
3086 }
3087 else {
3088 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003089 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003090 Result += "\"";
3091 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003092 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003093 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003094 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffb26d7132007-12-05 21:49:40 +00003095 if (IDecl->getNumClassMethods() > 0) {
Steve Naroff23f41272008-03-11 18:14:26 +00003096 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003097 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003098 Result += "\n";
3099 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003100 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003101 Result += ", 0\n";
Chris Lattner3db6cae2008-07-21 18:19:38 +00003102 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003103 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003104 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003105 Result += ",0,0\n";
3106 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003107 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003108 Result += "\t,0,0,0,0\n";
3109 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003110
3111 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003112 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003113 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003114 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003115 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003116 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003117 if (SuperClass) {
3118 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003119 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003120 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003121 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003122 Result += "\"";
3123 }
3124 else {
3125 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003126 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003127 Result += "\"";
3128 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003129 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003130 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003131 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003132 Result += ",0";
3133 else {
3134 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003135 Result += ",sizeof(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003136 Result += CDecl->getNameAsString();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003137 if (LangOpts.Microsoft)
3138 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003139 Result += ")";
3140 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003141 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00003142 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003143 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003144 Result += "\n\t";
3145 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003146 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003147 Result += ",0";
3148 if (IDecl->getNumInstanceMethods() > 0) {
Steve Naroff946a6932008-03-11 00:12:29 +00003149 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003150 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003151 Result += ", 0\n\t";
3152 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003153 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003154 Result += ",0,0";
Chris Lattner3db6cae2008-07-21 18:19:38 +00003155 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003156 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003157 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003158 Result += ", 0,0\n";
3159 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003160 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003161 Result += ",0,0,0\n";
3162 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003163}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003164
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003165/// RewriteImplementations - This routine rewrites all method implementations
3166/// and emits meta-data.
3167
Steve Narofface66252008-11-13 20:07:04 +00003168void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003169 int ClsDefCount = ClassImplementation.size();
3170 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003171
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003172 // Rewrite implemented methods
3173 for (int i = 0; i < ClsDefCount; i++)
3174 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003175
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003176 for (int i = 0; i < CatDefCount; i++)
3177 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00003178}
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003179
Steve Narofface66252008-11-13 20:07:04 +00003180void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3181 int ClsDefCount = ClassImplementation.size();
3182 int CatDefCount = CategoryImplementation.size();
3183
Steve Naroff5df5b762008-05-07 21:23:49 +00003184 // This is needed for determining instance variable offsets.
Steve Naroffa11440b2008-08-05 18:47:23 +00003185 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003186 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003187 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003188 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003189
3190 // For each implemented category, write out all its meta data.
3191 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003192 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003193
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003194 // Write objc_symtab metadata
3195 /*
3196 struct _objc_symtab
3197 {
3198 long sel_ref_cnt;
3199 SEL *refs;
3200 short cls_def_cnt;
3201 short cat_def_cnt;
3202 void *defs[cls_def_cnt + cat_def_cnt];
3203 };
3204 */
3205
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003206 Result += "\nstruct _objc_symtab {\n";
3207 Result += "\tlong sel_ref_cnt;\n";
3208 Result += "\tSEL *refs;\n";
3209 Result += "\tshort cls_def_cnt;\n";
3210 Result += "\tshort cat_def_cnt;\n";
3211 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3212 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003213
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003214 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00003215 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003216 Result += "\t0, 0, " + utostr(ClsDefCount)
3217 + ", " + utostr(CatDefCount) + "\n";
3218 for (int i = 0; i < ClsDefCount; i++) {
3219 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003220 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003221 Result += "\n";
3222 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003223
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003224 for (int i = 0; i < CatDefCount; i++) {
3225 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003226 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003227 Result += "_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003228 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003229 Result += "\n";
3230 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003231
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003232 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003233
3234 // Write objc_module metadata
3235
3236 /*
3237 struct _objc_module {
3238 long version;
3239 long size;
3240 const char *name;
3241 struct _objc_symtab *symtab;
3242 }
3243 */
3244
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003245 Result += "\nstruct _objc_module {\n";
3246 Result += "\tlong version;\n";
3247 Result += "\tlong size;\n";
3248 Result += "\tconst char *name;\n";
3249 Result += "\tstruct _objc_symtab *symtab;\n";
3250 Result += "};\n\n";
3251 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00003252 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003253 Result += "\t" + utostr(OBJC_ABI_VERSION) +
3254 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003255 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003256
3257 if (LangOpts.Microsoft) {
3258 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00003259 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003260 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3261 Result += "&_OBJC_MODULES;\n";
3262 Result += "#pragma data_seg(pop)\n\n";
3263 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003264}
Chris Lattner311ff022007-10-16 22:36:42 +00003265
Steve Naroff54055232008-10-27 17:20:55 +00003266std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3267 const char *funcName,
3268 std::string Tag) {
3269 const FunctionType *AFT = CE->getFunctionType();
3270 QualType RT = AFT->getResultType();
3271 std::string StructRef = "struct " + Tag;
3272 std::string S = "static " + RT.getAsString() + " __" +
3273 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003274
Steve Naroff54055232008-10-27 17:20:55 +00003275 BlockDecl *BD = CE->getBlockDecl();
3276
3277 if (isa<FunctionTypeNoProto>(AFT)) {
3278 S += "()";
3279 } else if (BD->param_empty()) {
3280 S += "(" + StructRef + " *__cself)";
3281 } else {
3282 const FunctionTypeProto *FT = cast<FunctionTypeProto>(AFT);
3283 assert(FT && "SynthesizeBlockFunc: No function proto");
3284 S += '(';
3285 // first add the implicit argument.
3286 S += StructRef + " *__cself, ";
3287 std::string ParamStr;
3288 for (BlockDecl::param_iterator AI = BD->param_begin(),
3289 E = BD->param_end(); AI != E; ++AI) {
3290 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003291 ParamStr = (*AI)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003292 (*AI)->getType().getAsStringInternal(ParamStr);
3293 S += ParamStr;
3294 }
3295 if (FT->isVariadic()) {
3296 if (!BD->param_empty()) S += ", ";
3297 S += "...";
3298 }
3299 S += ')';
3300 }
3301 S += " {\n";
3302
3303 // Create local declarations to avoid rewriting all closure decl ref exprs.
3304 // First, emit a declaration for all "by ref" decls.
3305 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3306 E = BlockByRefDecls.end(); I != E; ++I) {
3307 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003308 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003309 Context->getPointerType((*I)->getType()).getAsStringInternal(Name);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003310 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Steve Naroff54055232008-10-27 17:20:55 +00003311 }
3312 // Next, emit a declaration for all "by copy" declarations.
3313 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3314 E = BlockByCopyDecls.end(); I != E; ++I) {
3315 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003316 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003317 // Handle nested closure invocation. For example:
3318 //
3319 // void (^myImportedClosure)(void);
3320 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3321 //
3322 // void (^anotherClosure)(void);
3323 // anotherClosure = ^(void) {
3324 // myImportedClosure(); // import and invoke the closure
3325 // };
3326 //
3327 if (isBlockPointerType((*I)->getType()))
3328 S += "struct __block_impl *";
3329 else
3330 (*I)->getType().getAsStringInternal(Name);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003331 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff54055232008-10-27 17:20:55 +00003332 }
3333 std::string RewrittenStr = RewrittenBlockExprs[CE];
3334 const char *cstr = RewrittenStr.c_str();
3335 while (*cstr++ != '{') ;
3336 S += cstr;
3337 S += "\n";
3338 return S;
3339}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003340
Steve Naroff54055232008-10-27 17:20:55 +00003341std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3342 const char *funcName,
3343 std::string Tag) {
3344 std::string StructRef = "struct " + Tag;
3345 std::string S = "static void __";
3346
3347 S += funcName;
3348 S += "_block_copy_" + utostr(i);
3349 S += "(" + StructRef;
3350 S += "*dst, " + StructRef;
3351 S += "*src) {";
3352 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3353 E = ImportedBlockDecls.end(); I != E; ++I) {
3354 S += "_Block_copy_assign(&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003355 S += (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003356 S += ", src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003357 S += (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003358 S += ");}";
3359 }
3360 S += "\nstatic void __";
3361 S += funcName;
3362 S += "_block_dispose_" + utostr(i);
3363 S += "(" + StructRef;
3364 S += "*src) {";
3365 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3366 E = ImportedBlockDecls.end(); I != E; ++I) {
3367 S += "_Block_destroy(src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003368 S += (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003369 S += ");";
3370 }
3371 S += "}\n";
3372 return S;
3373}
3374
3375std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3376 bool hasCopyDisposeHelpers) {
Steve Naroffced80a82008-10-30 12:09:33 +00003377 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00003378 std::string Constructor = " " + Tag;
3379
3380 S += " {\n struct __block_impl impl;\n";
3381
3382 if (hasCopyDisposeHelpers)
3383 S += " void *copy;\n void *dispose;\n";
3384
3385 Constructor += "(void *fp";
3386
3387 if (hasCopyDisposeHelpers)
3388 Constructor += ", void *copyHelp, void *disposeHelp";
3389
3390 if (BlockDeclRefs.size()) {
3391 // Output all "by copy" declarations.
3392 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3393 E = BlockByCopyDecls.end(); I != E; ++I) {
3394 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003395 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003396 std::string ArgName = "_" + FieldName;
3397 // Handle nested closure invocation. For example:
3398 //
3399 // void (^myImportedBlock)(void);
3400 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3401 //
3402 // void (^anotherBlock)(void);
3403 // anotherBlock = ^(void) {
3404 // myImportedBlock(); // import and invoke the closure
3405 // };
3406 //
3407 if (isBlockPointerType((*I)->getType())) {
3408 S += "struct __block_impl *";
3409 Constructor += ", void *" + ArgName;
3410 } else {
3411 (*I)->getType().getAsStringInternal(FieldName);
3412 (*I)->getType().getAsStringInternal(ArgName);
3413 Constructor += ", " + ArgName;
3414 }
3415 S += FieldName + ";\n";
3416 }
3417 // Output all "by ref" declarations.
3418 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3419 E = BlockByRefDecls.end(); I != E; ++I) {
3420 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003421 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003422 std::string ArgName = "_" + FieldName;
3423 // Handle nested closure invocation. For example:
3424 //
3425 // void (^myImportedBlock)(void);
3426 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3427 //
3428 // void (^anotherBlock)(void);
3429 // anotherBlock = ^(void) {
3430 // myImportedBlock(); // import and invoke the closure
3431 // };
3432 //
3433 if (isBlockPointerType((*I)->getType())) {
3434 S += "struct __block_impl *";
3435 Constructor += ", void *" + ArgName;
3436 } else {
3437 Context->getPointerType((*I)->getType()).getAsStringInternal(FieldName);
3438 Context->getPointerType((*I)->getType()).getAsStringInternal(ArgName);
3439 Constructor += ", " + ArgName;
3440 }
3441 S += FieldName + "; // by ref\n";
3442 }
3443 // Finish writing the constructor.
3444 // FIXME: handle NSConcreteGlobalBlock.
3445 Constructor += ", int flags=0) {\n";
3446 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3447 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3448
3449 if (hasCopyDisposeHelpers)
3450 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3451
3452 // Initialize all "by copy" arguments.
3453 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3454 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003455 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003456 Constructor += " ";
3457 if (isBlockPointerType((*I)->getType()))
3458 Constructor += Name + " = (struct __block_impl *)_";
3459 else
3460 Constructor += Name + " = _";
3461 Constructor += Name + ";\n";
3462 }
3463 // Initialize all "by ref" arguments.
3464 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3465 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003466 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003467 Constructor += " ";
3468 if (isBlockPointerType((*I)->getType()))
3469 Constructor += Name + " = (struct __block_impl *)_";
3470 else
3471 Constructor += Name + " = _";
3472 Constructor += Name + ";\n";
3473 }
3474 } else {
3475 // Finish writing the constructor.
3476 // FIXME: handle NSConcreteGlobalBlock.
3477 Constructor += ", int flags=0) {\n";
3478 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3479 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3480 if (hasCopyDisposeHelpers)
3481 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3482 }
3483 Constructor += " ";
3484 Constructor += "}\n";
3485 S += Constructor;
3486 S += "};\n";
3487 return S;
3488}
3489
3490void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3491 const char *FunName) {
3492 // Insert closures that were part of the function.
3493 for (unsigned i = 0; i < Blocks.size(); i++) {
3494
3495 CollectBlockDeclRefInfo(Blocks[i]);
3496
3497 std::string Tag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
3498
3499 std::string CI = SynthesizeBlockImpl(Blocks[i], Tag,
3500 ImportedBlockDecls.size() > 0);
3501
3502 InsertText(FunLocStart, CI.c_str(), CI.size());
3503
3504 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, Tag);
3505
3506 InsertText(FunLocStart, CF.c_str(), CF.size());
3507
3508 if (ImportedBlockDecls.size()) {
3509 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, Tag);
3510 InsertText(FunLocStart, HF.c_str(), HF.size());
3511 }
3512
3513 BlockDeclRefs.clear();
3514 BlockByRefDecls.clear();
3515 BlockByCopyDecls.clear();
3516 BlockCallExprs.clear();
3517 ImportedBlockDecls.clear();
3518 }
3519 Blocks.clear();
3520 RewrittenBlockExprs.clear();
3521}
3522
3523void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3524 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner8ec03f52008-11-24 03:54:41 +00003525 const char *FuncName = FD->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003526
3527 SynthesizeBlockLiterals(FunLocStart, FuncName);
3528}
3529
3530void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00003531 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3532 //SourceLocation FunLocStart = MD->getLocStart();
3533 // FIXME: This hack works around a bug in Rewrite.InsertText().
3534 SourceLocation FunLocStart = MD->getLocStart().getFileLocWithOffset(-1);
Chris Lattner077bf5e2008-11-24 03:33:13 +00003535 std::string FuncName = MD->getSelector().getAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003536 // Convert colons to underscores.
3537 std::string::size_type loc = 0;
3538 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3539 FuncName.replace(loc, 1, "_");
3540
3541 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
3542}
3543
3544void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
3545 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3546 CI != E; ++CI)
3547 if (*CI) {
3548 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3549 GetBlockDeclRefExprs(CBE->getBody());
3550 else
3551 GetBlockDeclRefExprs(*CI);
3552 }
3553 // Handle specific things.
3554 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
3555 // FIXME: Handle enums.
3556 if (!isa<FunctionDecl>(CDRE->getDecl()))
3557 BlockDeclRefs.push_back(CDRE);
3558 return;
3559}
3560
3561void RewriteObjC::GetBlockCallExprs(Stmt *S) {
3562 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3563 CI != E; ++CI)
3564 if (*CI) {
3565 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3566 GetBlockCallExprs(CBE->getBody());
3567 else
3568 GetBlockCallExprs(*CI);
3569 }
3570
3571 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
3572 if (CE->getCallee()->getType()->isBlockPointerType()) {
3573 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
3574 }
3575 }
3576 return;
3577}
3578
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003579Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00003580 // Navigate to relevant type information.
3581 const char *closureName = 0;
3582 const BlockPointerType *CPT = 0;
3583
3584 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003585 closureName = DRE->getDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003586 CPT = DRE->getType()->getAsBlockPointerType();
3587 } else if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003588 closureName = CDRE->getDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003589 CPT = CDRE->getType()->getAsBlockPointerType();
3590 } else if (MemberExpr *MExpr = dyn_cast<MemberExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003591 closureName = MExpr->getMemberDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003592 CPT = MExpr->getType()->getAsBlockPointerType();
3593 } else {
3594 assert(1 && "RewriteBlockClass: Bad type");
3595 }
3596 assert(CPT && "RewriteBlockClass: Bad type");
3597 const FunctionType *FT = CPT->getPointeeType()->getAsFunctionType();
3598 assert(FT && "RewriteBlockClass: Bad type");
3599 const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(FT);
3600 // FTP will be null for closures that don't take arguments.
3601
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003602 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
3603 SourceLocation(),
3604 &Context->Idents.get("__block_impl"));
3605 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00003606
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003607 // Generate a funky cast.
3608 llvm::SmallVector<QualType, 8> ArgTypes;
3609
3610 // Push the block argument type.
3611 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00003612 if (FTP) {
3613 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003614 E = FTP->arg_type_end(); I && (I != E); ++I) {
3615 QualType t = *I;
3616 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3617 if (isBlockPointerType(t)) {
3618 const BlockPointerType *BPT = t->getAsBlockPointerType();
3619 t = Context->getPointerType(BPT->getPointeeType());
3620 }
3621 ArgTypes.push_back(t);
3622 }
Steve Naroff54055232008-10-27 17:20:55 +00003623 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003624 // Now do the pointer to function cast.
3625 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
3626 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
3627
3628 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Steve Naroff54055232008-10-27 17:20:55 +00003629
Steve Naroffb2f9e512008-11-03 23:29:32 +00003630 CastExpr *BlkCast = new CStyleCastExpr(PtrBlock, Exp->getCallee(), PtrBlock, SourceLocation(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003631 // Don't forget the parens to enforce the proper binding.
3632 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), BlkCast);
3633 //PE->dump();
Steve Naroff54055232008-10-27 17:20:55 +00003634
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003635 FieldDecl *FD = FieldDecl::Create(*Context, SourceLocation(),
3636 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy);
3637 MemberExpr *ME = new MemberExpr(PE, true, FD, SourceLocation(), FD->getType());
3638
Steve Naroffb2f9e512008-11-03 23:29:32 +00003639 CastExpr *FunkCast = new CStyleCastExpr(PtrToFuncCastType, ME, PtrToFuncCastType, SourceLocation(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003640 PE = new ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
3641
3642 llvm::SmallVector<Expr*, 8> BlkExprs;
3643 // Add the implicit argument.
3644 BlkExprs.push_back(BlkCast);
3645 // Add the user arguments.
Steve Naroff54055232008-10-27 17:20:55 +00003646 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3647 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003648 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00003649 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003650 CallExpr *CE = new CallExpr(PE, &BlkExprs[0], BlkExprs.size(), Exp->getType(), SourceLocation());
3651 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00003652}
3653
3654void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003655 Stmt *BlockCall = SynthesizeBlockCall(Exp);
3656 ReplaceStmt(Exp, BlockCall);
Steve Naroff54055232008-10-27 17:20:55 +00003657}
3658
3659void RewriteObjC::RewriteBlockDeclRefExpr(BlockDeclRefExpr *BDRE) {
3660 // FIXME: Add more elaborate code generation required by the ABI.
3661 InsertText(BDRE->getLocStart(), "*", 1);
3662}
3663
Steve Naroffb2f9e512008-11-03 23:29:32 +00003664void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3665 SourceLocation LocStart = CE->getLParenLoc();
3666 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00003667
3668 // Need to avoid trying to rewrite synthesized casts.
3669 if (LocStart.isInvalid())
3670 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00003671 // Need to avoid trying to rewrite casts contained in macros.
3672 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3673 return;
Steve Narofffa15fd92008-10-28 20:29:00 +00003674
Steve Naroff54055232008-10-27 17:20:55 +00003675 const char *startBuf = SM->getCharacterData(LocStart);
3676 const char *endBuf = SM->getCharacterData(LocEnd);
3677
3678 // advance the location to startArgList.
3679 const char *argPtr = startBuf;
3680
3681 while (*argPtr++ && (argPtr < endBuf)) {
3682 switch (*argPtr) {
3683 case '^':
3684 // Replace the '^' with '*'.
3685 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
3686 ReplaceText(LocStart, 1, "*", 1);
3687 break;
3688 }
3689 }
3690 return;
3691}
3692
3693void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
3694 SourceLocation DeclLoc = FD->getLocation();
3695 unsigned parenCount = 0;
3696
3697 // We have 1 or more arguments that have closure pointers.
3698 const char *startBuf = SM->getCharacterData(DeclLoc);
3699 const char *startArgList = strchr(startBuf, '(');
3700
3701 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
3702
3703 parenCount++;
3704 // advance the location to startArgList.
3705 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
3706 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
3707
3708 const char *argPtr = startArgList;
3709
3710 while (*argPtr++ && parenCount) {
3711 switch (*argPtr) {
3712 case '^':
3713 // Replace the '^' with '*'.
3714 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
3715 ReplaceText(DeclLoc, 1, "*", 1);
3716 break;
3717 case '(':
3718 parenCount++;
3719 break;
3720 case ')':
3721 parenCount--;
3722 break;
3723 }
3724 }
3725 return;
3726}
3727
3728bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
3729 const FunctionTypeProto *FTP;
3730 const PointerType *PT = QT->getAsPointerType();
3731 if (PT) {
3732 FTP = PT->getPointeeType()->getAsFunctionTypeProto();
3733 } else {
3734 const BlockPointerType *BPT = QT->getAsBlockPointerType();
3735 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
3736 FTP = BPT->getPointeeType()->getAsFunctionTypeProto();
3737 }
3738 if (FTP) {
3739 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
3740 E = FTP->arg_type_end(); I != E; ++I)
3741 if (isBlockPointerType(*I))
3742 return true;
3743 }
3744 return false;
3745}
3746
3747void RewriteObjC::GetExtentOfArgList(const char *Name,
3748 const char *&LParen, const char *&RParen) {
3749 const char *argPtr = strchr(Name, '(');
3750 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
3751
3752 LParen = argPtr; // output the start.
3753 argPtr++; // skip past the left paren.
3754 unsigned parenCount = 1;
3755
3756 while (*argPtr && parenCount) {
3757 switch (*argPtr) {
3758 case '(': parenCount++; break;
3759 case ')': parenCount--; break;
3760 default: break;
3761 }
3762 if (parenCount) argPtr++;
3763 }
3764 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
3765 RParen = argPtr; // output the end
3766}
3767
3768void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
3769 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3770 RewriteBlockPointerFunctionArgs(FD);
3771 return;
3772 }
3773 // Handle Variables and Typedefs.
3774 SourceLocation DeclLoc = ND->getLocation();
3775 QualType DeclT;
3776 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3777 DeclT = VD->getType();
3778 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
3779 DeclT = TDD->getUnderlyingType();
3780 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
3781 DeclT = FD->getType();
3782 else
3783 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
3784
3785 const char *startBuf = SM->getCharacterData(DeclLoc);
3786 const char *endBuf = startBuf;
3787 // scan backward (from the decl location) for the end of the previous decl.
3788 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
3789 startBuf--;
3790
3791 // *startBuf != '^' if we are dealing with a pointer to function that
3792 // may take block argument types (which will be handled below).
3793 if (*startBuf == '^') {
3794 // Replace the '^' with '*', computing a negative offset.
3795 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
3796 ReplaceText(DeclLoc, 1, "*", 1);
3797 }
3798 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
3799 // Replace the '^' with '*' for arguments.
3800 DeclLoc = ND->getLocation();
3801 startBuf = SM->getCharacterData(DeclLoc);
3802 const char *argListBegin, *argListEnd;
3803 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
3804 while (argListBegin < argListEnd) {
3805 if (*argListBegin == '^') {
3806 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
3807 ReplaceText(CaretLoc, 1, "*", 1);
3808 }
3809 argListBegin++;
3810 }
3811 }
3812 return;
3813}
3814
3815void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
3816 // Add initializers for any closure decl refs.
3817 GetBlockDeclRefExprs(Exp->getBody());
3818 if (BlockDeclRefs.size()) {
3819 // Unique all "by copy" declarations.
3820 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3821 if (!BlockDeclRefs[i]->isByRef())
3822 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
3823 // Unique all "by ref" declarations.
3824 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3825 if (BlockDeclRefs[i]->isByRef()) {
3826 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
3827 }
3828 // Find any imported blocks...they will need special attention.
3829 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3830 if (isBlockPointerType(BlockDeclRefs[i]->getType())) {
Steve Naroff00072682008-11-13 17:40:07 +00003831 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff54055232008-10-27 17:20:55 +00003832 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
3833 }
3834 }
3835}
3836
Steve Narofffa15fd92008-10-28 20:29:00 +00003837FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
3838 IdentifierInfo *ID = &Context->Idents.get(name);
3839 QualType FType = Context->getFunctionTypeNoProto(Context->VoidPtrTy);
3840 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
3841 ID, FType, FunctionDecl::Extern, false, 0);
3842}
3843
Steve Naroff8e2f57a2008-10-29 18:15:37 +00003844Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Narofffa15fd92008-10-28 20:29:00 +00003845 Blocks.push_back(Exp);
3846
3847 CollectBlockDeclRefInfo(Exp);
3848 std::string FuncName;
3849
3850 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00003851 FuncName = CurFunctionDef->getNameAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00003852 else if (CurMethodDef) {
Chris Lattner077bf5e2008-11-24 03:33:13 +00003853 FuncName = CurMethodDef->getSelector().getAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00003854 // Convert colons to underscores.
3855 std::string::size_type loc = 0;
3856 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3857 FuncName.replace(loc, 1, "_");
Steve Naroff8e2f57a2008-10-29 18:15:37 +00003858 } else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003859 FuncName = std::string(GlobalVarDecl->getNameAsString());
Steve Narofffa15fd92008-10-28 20:29:00 +00003860
3861 std::string BlockNumber = utostr(Blocks.size()-1);
3862
3863 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
3864 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
3865
3866 // Get a pointer to the function type so we can cast appropriately.
3867 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
3868
3869 FunctionDecl *FD;
3870 Expr *NewRep;
3871
3872 // Simulate a contructor call...
3873 FD = SynthBlockInitFunctionDecl(Tag.c_str());
3874 DeclRefExpr *DRE = new DeclRefExpr(FD, FType, SourceLocation());
3875
3876 llvm::SmallVector<Expr*, 4> InitExprs;
3877
Steve Narofffdc03722008-10-29 21:23:59 +00003878 // Initialize the block function.
Steve Narofffa15fd92008-10-28 20:29:00 +00003879 FD = SynthBlockInitFunctionDecl(Func.c_str());
3880 DeclRefExpr *Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3881 CastExpr *castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00003882 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00003883 InitExprs.push_back(castExpr);
Steve Narofffa15fd92008-10-28 20:29:00 +00003884
3885 if (ImportedBlockDecls.size()) {
3886 std::string Buf = "__" + FuncName + "_block_copy_" + BlockNumber;
Steve Narofffdc03722008-10-29 21:23:59 +00003887 FD = SynthBlockInitFunctionDecl(Buf.c_str());
3888 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3889 castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00003890 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffdc03722008-10-29 21:23:59 +00003891 InitExprs.push_back(castExpr);
3892
Steve Narofffa15fd92008-10-28 20:29:00 +00003893 Buf = "__" + FuncName + "_block_dispose_" + BlockNumber;
Steve Narofffdc03722008-10-29 21:23:59 +00003894 FD = SynthBlockInitFunctionDecl(Buf.c_str());
3895 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3896 castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00003897 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffdc03722008-10-29 21:23:59 +00003898 InitExprs.push_back(castExpr);
Steve Narofffa15fd92008-10-28 20:29:00 +00003899 }
3900 // Add initializers for any closure decl refs.
3901 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00003902 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00003903 // Output all "by copy" declarations.
3904 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3905 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00003906 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00003907 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner8ec03f52008-11-24 03:54:41 +00003908 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00003909 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00003910 } else if (isBlockPointerType((*I)->getType())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003911 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00003912 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3913 Exp = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00003914 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00003915 } else {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003916 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00003917 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00003918 }
Steve Narofffdc03722008-10-29 21:23:59 +00003919 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00003920 }
3921 // Output all "by ref" declarations.
3922 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3923 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003924 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00003925 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3926 Exp = new UnaryOperator(Exp, UnaryOperator::AddrOf,
3927 Context->getPointerType(Exp->getType()),
3928 SourceLocation());
Steve Naroff707b0fe2008-11-14 21:36:12 +00003929 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00003930 }
3931 }
Steve Narofffa15fd92008-10-28 20:29:00 +00003932 NewRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
3933 FType, SourceLocation());
3934 NewRep = new UnaryOperator(NewRep, UnaryOperator::AddrOf,
3935 Context->getPointerType(NewRep->getType()),
3936 SourceLocation());
Steve Naroffb2f9e512008-11-03 23:29:32 +00003937 NewRep = new CStyleCastExpr(FType, NewRep, FType, SourceLocation(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00003938 BlockDeclRefs.clear();
3939 BlockByRefDecls.clear();
3940 BlockByCopyDecls.clear();
3941 ImportedBlockDecls.clear();
3942 return NewRep;
3943}
3944
3945//===----------------------------------------------------------------------===//
3946// Function Body / Expression rewriting
3947//===----------------------------------------------------------------------===//
3948
3949Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
3950 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
3951 isa<DoStmt>(S) || isa<ForStmt>(S))
3952 Stmts.push_back(S);
3953 else if (isa<ObjCForCollectionStmt>(S)) {
3954 Stmts.push_back(S);
3955 ObjCBcLabelNo.push_back(++BcLabelCount);
3956 }
3957
3958 SourceRange OrigStmtRange = S->getSourceRange();
3959
3960 // Perform a bottom up rewrite of all children.
3961 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3962 CI != E; ++CI)
3963 if (*CI) {
3964 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
3965 if (newStmt)
3966 *CI = newStmt;
3967 }
3968
3969 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
3970 // Rewrite the block body in place.
3971 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
3972
3973 // Now we snarf the rewritten text and stash it away for later use.
Steve Naroff8e2f57a2008-10-29 18:15:37 +00003974 std::string Str = Rewrite.getRewritenText(BE->getSourceRange());
3975 RewrittenBlockExprs[BE] = Str;
Steve Narofffa15fd92008-10-28 20:29:00 +00003976
3977 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
3978 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00003979 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00003980 return blockTranscribed;
3981 }
3982 // Handle specific things.
3983 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
3984 return RewriteAtEncode(AtEncode);
3985
3986 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
3987 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
3988
3989 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
3990 return RewriteAtSelector(AtSelector);
3991
3992 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
3993 return RewriteObjCStringLiteral(AtString);
3994
3995 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
3996 // Before we rewrite it, put the original message expression in a comment.
3997 SourceLocation startLoc = MessExpr->getLocStart();
3998 SourceLocation endLoc = MessExpr->getLocEnd();
3999
4000 const char *startBuf = SM->getCharacterData(startLoc);
4001 const char *endBuf = SM->getCharacterData(endLoc);
4002
4003 std::string messString;
4004 messString += "// ";
4005 messString.append(startBuf, endBuf-startBuf+1);
4006 messString += "\n";
4007
4008 // FIXME: Missing definition of
4009 // InsertText(clang::SourceLocation, char const*, unsigned int).
4010 // InsertText(startLoc, messString.c_str(), messString.size());
4011 // Tried this, but it didn't work either...
4012 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
4013 return RewriteMessageExpr(MessExpr);
4014 }
4015
4016 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4017 return RewriteObjCTryStmt(StmtTry);
4018
4019 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4020 return RewriteObjCSynchronizedStmt(StmtTry);
4021
4022 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4023 return RewriteObjCThrowStmt(StmtThrow);
4024
4025 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4026 return RewriteObjCProtocolExpr(ProtocolExp);
4027
4028 if (ObjCForCollectionStmt *StmtForCollection =
4029 dyn_cast<ObjCForCollectionStmt>(S))
4030 return RewriteObjCForCollectionStmt(StmtForCollection,
4031 OrigStmtRange.getEnd());
4032 if (BreakStmt *StmtBreakStmt =
4033 dyn_cast<BreakStmt>(S))
4034 return RewriteBreakStmt(StmtBreakStmt);
4035 if (ContinueStmt *StmtContinueStmt =
4036 dyn_cast<ContinueStmt>(S))
4037 return RewriteContinueStmt(StmtContinueStmt);
4038
4039 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
4040 // and cast exprs.
4041 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4042 // FIXME: What we're doing here is modifying the type-specifier that
4043 // precedes the first Decl. In the future the DeclGroup should have
4044 // a separate type-specifier that we can rewrite.
4045 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
4046
4047 // Blocks rewrite rules.
4048 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4049 DI != DE; ++DI) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004050 ScopedDecl *SD = *DI;
4051 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
4052 if (isBlockPointerType(ND->getType()))
4053 RewriteBlockPointerDecl(ND);
4054 else if (ND->getType()->isFunctionPointerType())
4055 CheckFunctionPointerDecl(ND->getType(), ND);
4056 }
4057 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
4058 if (isBlockPointerType(TD->getUnderlyingType()))
4059 RewriteBlockPointerDecl(TD);
4060 else if (TD->getUnderlyingType()->isFunctionPointerType())
4061 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4062 }
4063 }
4064 }
4065
4066 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4067 RewriteObjCQualifiedInterfaceTypes(CE);
4068
4069 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4070 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4071 assert(!Stmts.empty() && "Statement stack is empty");
4072 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4073 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
4074 && "Statement stack mismatch");
4075 Stmts.pop_back();
4076 }
4077 // Handle blocks rewriting.
4078 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4079 if (BDRE->isByRef())
4080 RewriteBlockDeclRefExpr(BDRE);
4081 }
4082 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004083 if (CE->getCallee()->getType()->isBlockPointerType()) {
4084 Stmt *BlockCall = SynthesizeBlockCall(CE);
4085 ReplaceStmt(S, BlockCall);
4086 return BlockCall;
4087 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004088 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00004089 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004090 RewriteCastExpr(CE);
4091 }
4092#if 0
4093 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
4094 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
4095 // Get the new text.
4096 std::string SStr;
4097 llvm::raw_string_ostream Buf(SStr);
4098 Replacement->printPretty(Buf);
4099 const std::string &Str = Buf.str();
4100
4101 printf("CAST = %s\n", &Str[0]);
4102 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4103 delete S;
4104 return Replacement;
4105 }
4106#endif
4107 // Return this stmt unmodified.
4108 return S;
4109}
4110
4111/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4112/// main file of the input.
4113void RewriteObjC::HandleDeclInMainFile(Decl *D) {
4114 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4115 // Since function prototypes don't have ParmDecl's, we check the function
4116 // prototype. This enables us to rewrite function declarations and
4117 // definitions using the same code.
4118 RewriteBlocksInFunctionTypeProto(FD->getType(), FD);
4119
4120 if (Stmt *Body = FD->getBody()) {
4121 CurFunctionDef = FD;
4122 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
4123 // This synthesizes and inserts the block "impl" struct, invoke function,
4124 // and any copy/dispose helper functions.
4125 InsertBlockLiteralsWithinFunction(FD);
4126 CurFunctionDef = 0;
4127 }
4128 return;
4129 }
4130 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4131 if (Stmt *Body = MD->getBody()) {
4132 //Body->dump();
4133 CurMethodDef = MD;
4134 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
4135 InsertBlockLiteralsWithinMethod(MD);
4136 CurMethodDef = 0;
4137 }
4138 }
4139 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
4140 ClassImplementation.push_back(CI);
4141 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
4142 CategoryImplementation.push_back(CI);
4143 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
4144 RewriteForwardClassDecl(CD);
4145 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4146 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004147 if (isBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004148 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004149 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004150 CheckFunctionPointerDecl(VD->getType(), VD);
4151 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00004152 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004153 RewriteCastExpr(CE);
4154 }
4155 }
4156 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004157 if (VD->getInit()) {
4158 GlobalVarDecl = VD;
4159 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Douglas Gregor2e1cd422008-11-17 14:58:09 +00004160 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00004161 VD->getNameAsCString());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004162 GlobalVarDecl = 0;
4163
4164 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00004165 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004166 RewriteCastExpr(CE);
4167 }
4168 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004169 return;
4170 }
4171 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
4172 if (isBlockPointerType(TD->getUnderlyingType()))
4173 RewriteBlockPointerDecl(TD);
4174 else if (TD->getUnderlyingType()->isFunctionPointerType())
4175 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4176 return;
4177 }
4178 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
4179 if (RD->isDefinition()) {
4180 for (RecordDecl::field_const_iterator i = RD->field_begin(),
4181 e = RD->field_end(); i != e; ++i) {
4182 FieldDecl *FD = *i;
4183 if (isBlockPointerType(FD->getType()))
4184 RewriteBlockPointerDecl(FD);
4185 }
4186 }
4187 return;
4188 }
4189 // Nothing yet.
4190}
4191
4192void RewriteObjC::HandleTranslationUnit(TranslationUnit& TU) {
4193 // Get the top-level buffer that this corresponds to.
4194
4195 // Rewrite tabs if we care.
4196 //RewriteTabs();
4197
4198 if (Diags.hasErrorOccurred())
4199 return;
4200
4201 // Create the output file.
4202
4203 llvm::OwningPtr<llvm::raw_ostream> OwnedStream;
4204 llvm::raw_ostream *OutFile;
4205 if (OutFileName == "-") {
4206 OutFile = &llvm::outs();
4207 } else if (!OutFileName.empty()) {
4208 std::string Err;
Daniel Dunbar26fb2722008-11-13 05:09:21 +00004209 OutFile = new llvm::raw_fd_ostream(OutFileName.c_str(), false, Err);
Steve Narofffa15fd92008-10-28 20:29:00 +00004210 OwnedStream.reset(OutFile);
4211 } else if (InFileName == "-") {
4212 OutFile = &llvm::outs();
4213 } else {
4214 llvm::sys::Path Path(InFileName);
4215 Path.eraseSuffix();
4216 Path.appendSuffix("cpp");
4217 std::string Err;
Daniel Dunbar26fb2722008-11-13 05:09:21 +00004218 OutFile = new llvm::raw_fd_ostream(Path.toString().c_str(), false, Err);
Steve Narofffa15fd92008-10-28 20:29:00 +00004219 OwnedStream.reset(OutFile);
4220 }
4221
4222 RewriteInclude();
4223
4224 InsertText(SourceLocation::getFileLoc(MainFileID, 0),
4225 Preamble.c_str(), Preamble.size(), false);
4226
Steve Naroff0aab7962008-11-14 14:10:01 +00004227 if (ClassImplementation.size() || CategoryImplementation.size())
4228 RewriteImplementations();
Steve Narofffa15fd92008-10-28 20:29:00 +00004229
4230 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
4231 // we are done.
4232 if (const RewriteBuffer *RewriteBuf =
4233 Rewrite.getRewriteBufferFor(MainFileID)) {
4234 //printf("Changed:\n");
4235 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4236 } else {
4237 fprintf(stderr, "No changes\n");
4238 }
Steve Narofface66252008-11-13 20:07:04 +00004239
Steve Naroff0aab7962008-11-14 14:10:01 +00004240 if (ClassImplementation.size() || CategoryImplementation.size()) {
4241 // Rewrite Objective-c meta data*
4242 std::string ResultStr;
4243 SynthesizeMetaDataIntoBuffer(ResultStr);
4244 // Emit metadata.
4245 *OutFile << ResultStr;
4246 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004247 OutFile->flush();
4248}
4249