blob: b5dd1796e34dd644c4975e49ea808037dc11165b [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;
108
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000109 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +0000110 public:
Ted Kremeneke3a61982008-05-31 20:11:04 +0000111 virtual void Initialize(ASTContext &context);
112
113 virtual void InitializeTU(TranslationUnit &TU) {
114 TU.SetOwnsDecls(false);
115 Initialize(TU.getContext());
116 }
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000117
Chris Lattner8a12c272007-10-11 18:38:32 +0000118
Chris Lattnerf04da132007-10-24 17:06:59 +0000119 // Top Level Driver code.
120 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000121 void HandleDeclInMainFile(Decl *D);
Steve Naroffb29b4272008-04-14 22:03:09 +0000122 RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000123 Diagnostic &D, const LangOptions &LOpts);
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000124
125 ~RewriteObjC() {}
126
127 virtual void HandleTranslationUnit(TranslationUnit& TU);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000128
129 void ReplaceStmt(Stmt *Old, Stmt *New) {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000130 // If replacement succeeded or warning disabled return with no warning.
131 if (!Rewrite.ReplaceStmt(Old, New) || SilenceRewriteMacroWarning)
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000132 return;
133
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000134 SourceRange Range = Old->getSourceRange();
135 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag,
136 0, 0, &Range, 1);
137 }
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);
172 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000173 void RewriteImplementationDecl(NamedDecl *Dcl);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000174 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
175 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
176 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
177 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
178 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Chris Lattner55d13b42008-03-16 21:23:50 +0000179 void RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +0000180 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000181 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroff4f95b752008-07-29 18:15:38 +0000182 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffd5255f52007-11-01 13:24:47 +0000183 bool needToScanForQualifiers(QualType T);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000184 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000185 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000186 QualType getConstantStringStructType();
Steve Naroffbaf58c32008-05-31 14:15:04 +0000187 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Chris Lattner311ff022007-10-16 22:36:42 +0000188
Chris Lattnerf04da132007-10-24 17:06:59 +0000189 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000190 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000191 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000192 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart);
Steve Naroffb42f8412007-11-05 14:50:49 +0000193 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000194 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000195 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000196 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000197 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000198 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000199 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
200 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
201 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000202 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
203 SourceLocation OrigEnd);
Steve Naroff934f2762007-10-24 22:48:43 +0000204 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
205 Expr **args, unsigned nargs);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000206 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000207 Stmt *RewriteBreakStmt(BreakStmt *S);
208 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000209 void SynthCountByEnumWithState(std::string &buf);
210
Steve Naroff09b266e2007-10-30 23:14:51 +0000211 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000212 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000213 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000214 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000215 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000216 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000217 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000218 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000219 void SynthGetProtocolFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000220 void SynthSuperContructorFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000221
Chris Lattnerf04da132007-10-24 17:06:59 +0000222 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000223 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000224 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000225
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000226 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
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 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
230 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000231 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000232 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000233 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000234 const char *ClassName,
235 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000236
Chris Lattner780f3292008-07-21 21:32:27 +0000237 void RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl>
238 &Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000239 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000240 const char *ClassName,
241 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000242 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000243 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000244 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
245 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000246 std::string &Result);
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000247 void RewriteImplementations(std::string &Result);
Steve Naroff54055232008-10-27 17:20:55 +0000248
249 // Block rewriting.
250 void RewriteBlocksInFunctionTypeProto(QualType funcType, NamedDecl *D);
251 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
252
253 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
254 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
255
256 // Block specific rewrite rules.
257 std::string SynthesizeBlockInitExpr(BlockExpr *Exp, VarDecl *VD=0);
258
259 void RewriteBlockCall(CallExpr *Exp);
260 void RewriteBlockPointerDecl(NamedDecl *VD);
261 void RewriteBlockDeclRefExpr(BlockDeclRefExpr *VD);
262 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
263
264 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
265 const char *funcName, std::string Tag);
266 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
267 const char *funcName, std::string Tag);
268 std::string SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
269 bool hasCopyDisposeHelpers);
270 std::string SynthesizeBlockCall(CallExpr *Exp);
271 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
272 const char *FunName);
273
274 void CollectBlockDeclRefInfo(BlockExpr *Exp);
275 void GetBlockCallExprs(Stmt *S);
276 void GetBlockDeclRefExprs(Stmt *S);
277
278 // We avoid calling Type::isBlockPointerType(), since it operates on the
279 // canonical type. We only care if the top-level type is a closure pointer.
280 bool isBlockPointerType(QualType T) { return isa<BlockPointerType>(T); }
281
282 // FIXME: This predicate seems like it would be useful to add to ASTContext.
283 bool isObjCType(QualType T) {
284 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
285 return false;
286
287 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
288
289 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
290 OCT == Context->getCanonicalType(Context->getObjCClassType()))
291 return true;
292
293 if (const PointerType *PT = OCT->getAsPointerType()) {
294 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
295 isa<ObjCQualifiedIdType>(PT->getPointeeType()))
296 return true;
297 }
298 return false;
299 }
300 bool PointerTypeTakesAnyBlockArguments(QualType QT);
301 void GetExtentOfArgList(const char *Name, const char *&LParen, const char *&RParen);
302 void RewriteCastExpr(CastExpr *CE);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000303 };
304}
305
Steve Naroff54055232008-10-27 17:20:55 +0000306void RewriteObjC::RewriteBlocksInFunctionTypeProto(QualType funcType,
307 NamedDecl *D) {
308 if (FunctionTypeProto *fproto = dyn_cast<FunctionTypeProto>(funcType)) {
309 for (FunctionTypeProto::arg_type_iterator I = fproto->arg_type_begin(),
310 E = fproto->arg_type_end(); I && (I != E); ++I)
311 if (isBlockPointerType(*I)) {
312 // All the args are checked/rewritten. Don't call twice!
313 RewriteBlockPointerDecl(D);
314 break;
315 }
316 }
317}
318
319void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
320 const PointerType *PT = funcType->getAsPointerType();
321 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
322 RewriteBlocksInFunctionTypeProto(PT->getPointeeType(), ND);
323}
324
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000325static bool IsHeaderFile(const std::string &Filename) {
326 std::string::size_type DotPos = Filename.rfind('.');
327
328 if (DotPos == std::string::npos) {
329 // no file extension
330 return false;
331 }
332
333 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
334 // C header: .h
335 // C++ header: .hh or .H;
336 return Ext == "h" || Ext == "hh" || Ext == "H";
337}
338
Steve Naroffb29b4272008-04-14 22:03:09 +0000339RewriteObjC::RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000340 Diagnostic &D, const LangOptions &LOpts)
341 : Diags(D), LangOpts(LOpts) {
342 IsHeader = IsHeaderFile(inFile);
343 InFileName = inFile;
344 OutFileName = outFile;
345 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
346 "rewriting sub-expression within a macro (may not be correct)");
347}
348
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000349ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
Chris Lattnerc68ab772008-03-22 00:08:40 +0000350 const std::string& OutFile,
Steve Naroff4f943c22008-03-10 20:43:59 +0000351 Diagnostic &Diags,
352 const LangOptions &LOpts) {
Steve Naroffb29b4272008-04-14 22:03:09 +0000353 return new RewriteObjC(InFile, OutFile, Diags, LOpts);
Chris Lattnere365c502007-11-30 22:25:36 +0000354}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000355
Steve Naroffb29b4272008-04-14 22:03:09 +0000356void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000357 Context = &context;
358 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000359 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000360 MsgSendFunctionDecl = 0;
361 MsgSendSuperFunctionDecl = 0;
362 MsgSendStretFunctionDecl = 0;
363 MsgSendSuperStretFunctionDecl = 0;
364 MsgSendFpretFunctionDecl = 0;
365 GetClassFunctionDecl = 0;
366 GetMetaClassFunctionDecl = 0;
367 SelGetUidFunctionDecl = 0;
368 CFStringFunctionDecl = 0;
369 GetProtocolFunctionDecl = 0;
370 ConstantStringClassReference = 0;
371 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000372 CurMethodDef = 0;
373 CurFunctionDef = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000374 SuperStructDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000375 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000376 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000377 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000378 NumObjCStringLiterals = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000379
380 // Get the ID and start/end of the main file.
381 MainFileID = SM->getMainFileID();
382 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
383 MainFileStart = MainBuf->getBufferStart();
384 MainFileEnd = MainBuf->getBufferEnd();
Steve Naroffba92b2e2008-03-27 22:29:16 +0000385
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000386 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000387
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000388 // declaring objc_selector outside the parameter list removes a silly
389 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000390 if (IsHeader)
391 Preamble = "#pragma once\n";
392 Preamble += "struct objc_selector; struct objc_class;\n";
393 Preamble += "#ifndef OBJC_SUPER\n";
394 Preamble += "struct objc_super { struct objc_object *object; ";
395 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000396 if (LangOpts.Microsoft) {
397 // Add a constructor for creating temporary objects.
Steve Naroffba92b2e2008-03-27 22:29:16 +0000398 Preamble += "objc_super(struct objc_object *o, struct objc_object *s) : ";
399 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000400 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000401 Preamble += "};\n";
402 Preamble += "#define OBJC_SUPER\n";
403 Preamble += "#endif\n";
404 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
405 Preamble += "typedef struct objc_object Protocol;\n";
406 Preamble += "#define _REWRITER_typedef_Protocol\n";
407 Preamble += "#endif\n";
Steve Naroff3c64d9e2008-03-12 13:19:12 +0000408 if (LangOpts.Microsoft)
Steve Naroff69c827f2008-05-06 22:45:19 +0000409 Preamble += "#define __OBJC_RW_EXTERN extern \"C\" __declspec(dllimport)\n";
410 else
411 Preamble += "#define __OBJC_RW_EXTERN extern\n";
412 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000413 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000414 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000415 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000416 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000417 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000418 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000419 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff1284db82008-05-08 22:02:18 +0000420 Preamble += "__OBJC_RW_EXTERN double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000421 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff0757612008-05-08 17:52:16 +0000422 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000423 Preamble += "(const char *);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000424 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000425 Preamble += "(const char *);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000426 Preamble += "__OBJC_RW_EXTERN void objc_exception_throw(struct objc_object *);\n";
427 Preamble += "__OBJC_RW_EXTERN void objc_exception_try_enter(void *);\n";
428 Preamble += "__OBJC_RW_EXTERN void objc_exception_try_exit(void *);\n";
429 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_exception_extract(void *);\n";
430 Preamble += "__OBJC_RW_EXTERN int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000431 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000432 // @synchronized hooks.
433 Preamble += "__OBJC_RW_EXTERN void objc_sync_enter(struct objc_object *);\n";
434 Preamble += "__OBJC_RW_EXTERN void objc_sync_exit(struct objc_object *);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000435 Preamble += "__OBJC_RW_EXTERN Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000436 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
437 Preamble += "struct __objcFastEnumerationState {\n\t";
438 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000439 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000440 Preamble += "unsigned long *mutationsPtr;\n\t";
441 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff73ebd6d2008-06-02 20:23:21 +0000442 Preamble += "__OBJC_RW_EXTERN void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000443 Preamble += "#define __FASTENUMERATIONSTATE\n";
444 Preamble += "#endif\n";
445 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
446 Preamble += "struct __NSConstantStringImpl {\n";
447 Preamble += " int *isa;\n";
448 Preamble += " int flags;\n";
449 Preamble += " char *str;\n";
450 Preamble += " long length;\n";
451 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000452 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
453 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
454 Preamble += "#else\n";
Steve Naroff73b17cd2008-05-15 21:12:10 +0000455 Preamble += "__OBJC_RW_EXTERN int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000456 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000457 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
458 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000459 // Blocks preamble.
460 Preamble += "#ifndef BLOCK_IMPL\n";
461 Preamble += "#define BLOCK_IMPL\n";
462 Preamble += "struct __block_impl {\n";
463 Preamble += " void *isa;\n";
464 Preamble += " int Flags;\n";
465 Preamble += " int Size;\n";
466 Preamble += " void *FuncPtr;\n";
467 Preamble += "};\n";
468 Preamble += "enum {\n";
469 Preamble += " BLOCK_HAS_COPY_DISPOSE = (1<<25),\n";
470 Preamble += " BLOCK_IS_GLOBAL = (1<<28)\n";
471 Preamble += "};\n";
Steve Naroff54055232008-10-27 17:20:55 +0000472 Preamble += "// Runtime copy/destroy helper functions\n";
473 Preamble += "__OBJC_RW_EXTERN void _Block_copy_assign(void *, void *);\n";
474 Preamble += "__OBJC_RW_EXTERN void _Block_byref_assign_copy(void *, void *);\n";
475 Preamble += "__OBJC_RW_EXTERN void _Block_destroy(void *);\n";
476 Preamble += "__OBJC_RW_EXTERN void _Block_byref_release(void *);\n";
477 Preamble += "__OBJC_RW_EXTERN void *_NSConcreteGlobalBlock;\n";
478 Preamble += "__OBJC_RW_EXTERN void *_NSConcreteStackBlock;\n";
479 Preamble += "#endif\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000480 if (LangOpts.Microsoft) {
481 Preamble += "#undef __OBJC_RW_EXTERN\n";
482 Preamble += "#define __attribute__(X)\n";
483 }
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000484}
485
486
Chris Lattnerf04da132007-10-24 17:06:59 +0000487//===----------------------------------------------------------------------===//
488// Top Level Driver Code
489//===----------------------------------------------------------------------===//
490
Steve Naroffb29b4272008-04-14 22:03:09 +0000491void RewriteObjC::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000492 // Two cases: either the decl could be in the main file, or it could be in a
493 // #included file. If the former, rewrite it now. If the later, check to see
494 // if we rewrote the #include/#import.
495 SourceLocation Loc = D->getLocation();
496 Loc = SM->getLogicalLoc(Loc);
497
498 // If this is for a builtin, ignore it.
499 if (Loc.isInvalid()) return;
500
Steve Naroffebf2b562007-10-23 23:50:29 +0000501 // Look for built-in declarations that we need to refer during the rewrite.
502 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000503 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000504 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000505 // declared in <Foundation/NSString.h>
506 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
507 ConstantStringClassReference = FVD;
508 return;
509 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000510 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000511 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000512 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000513 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000514 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000515 RewriteProtocolDecl(PD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000516 } else if (ObjCForwardProtocolDecl *FP =
517 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000518 RewriteForwardProtocolDecl(FP);
Steve Naroffebf2b562007-10-23 23:50:29 +0000519 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000520 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000521 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000522 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000523}
524
Chris Lattnerf04da132007-10-24 17:06:59 +0000525/// HandleDeclInMainFile - This is called for each top-level decl defined in the
526/// main file of the input.
Steve Naroffb29b4272008-04-14 22:03:09 +0000527void RewriteObjC::HandleDeclInMainFile(Decl *D) {
Steve Naroff54055232008-10-27 17:20:55 +0000528 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
529 // Since function prototypes don't have ParmDecl's, we check the function
530 // prototype. This enables us to rewrite function declarations and
531 // definitions using the same code.
532 RewriteBlocksInFunctionTypeProto(FD->getType(), FD);
533
534 if (Stmt *Body = FD->getBody()) {
535 CurFunctionDef = FD;
Steve Narofff3473a72007-11-09 15:20:18 +0000536 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff54055232008-10-27 17:20:55 +0000537 // This synthesizes and inserts the block "impl" struct, invoke function,
538 // and any copy/dispose helper functions.
539 InsertBlockLiteralsWithinFunction(FD);
540 CurFunctionDef = 0;
541 }
542 return;
543 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000544 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Steve Naroff874e2322007-11-15 10:28:18 +0000545 if (Stmt *Body = MD->getBody()) {
546 //Body->dump();
Steve Naroff54055232008-10-27 17:20:55 +0000547 CurMethodDef = MD;
Steve Naroff71c0a952007-11-13 23:01:27 +0000548 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff54055232008-10-27 17:20:55 +0000549 InsertBlockLiteralsWithinMethod(MD);
550 CurMethodDef = 0;
Steve Naroff874e2322007-11-15 10:28:18 +0000551 }
Steve Naroff71c0a952007-11-13 23:01:27 +0000552 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000553 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000554 ClassImplementation.push_back(CI);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000555 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000556 CategoryImplementation.push_back(CI);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000557 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000558 RewriteForwardClassDecl(CD);
Steve Narofff3473a72007-11-09 15:20:18 +0000559 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000560 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Narofff3473a72007-11-09 15:20:18 +0000561 if (VD->getInit())
562 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
563 }
Steve Naroff54055232008-10-27 17:20:55 +0000564 // Rewrite rules for blocks.
565 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
566 if (isBlockPointerType(VD->getType())) {
567 RewriteBlockPointerDecl(VD);
568 if (VD->getInit()) {
569 if (BlockExpr *CBE = dyn_cast<BlockExpr>(VD->getInit())) {
570 RewriteFunctionBodyOrGlobalInitializer(CBE->getBody());
571
572 // We've just rewritten the block body in place.
573 // Now we snarf the rewritten text and stash it away for later use.
574 std::string S = Rewrite.getRewritenText(CBE->getSourceRange());
575 RewrittenBlockExprs[CBE] = S;
576 std::string Init = SynthesizeBlockInitExpr(CBE, VD);
577 // Do the rewrite, using S.size() which contains the rewritten size.
578 ReplaceText(CBE->getLocStart(), S.size(), Init.c_str(), Init.size());
579 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
580 } else if (CastExpr *CE = dyn_cast<CastExpr>(VD->getInit())) {
581 RewriteCastExpr(CE);
582 }
583 }
584 } else if (VD->getType()->isFunctionPointerType()) {
585 CheckFunctionPointerDecl(VD->getType(), VD);
586 if (VD->getInit()) {
587 if (CastExpr *CE = dyn_cast<CastExpr>(VD->getInit())) {
588 RewriteCastExpr(CE);
589 }
590 }
591 }
592 return;
593 }
594 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
595 if (isBlockPointerType(TD->getUnderlyingType()))
596 RewriteBlockPointerDecl(TD);
597 else if (TD->getUnderlyingType()->isFunctionPointerType())
598 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
599 return;
600 }
601 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
602 if (RD->isDefinition()) {
603 for (RecordDecl::field_const_iterator i = RD->field_begin(),
604 e = RD->field_end(); i != e; ++i) {
605 FieldDecl *FD = *i;
606 if (isBlockPointerType(FD->getType()))
607 RewriteBlockPointerDecl(FD);
608 }
609 }
610 return;
611 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000612 // Nothing yet.
613}
614
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000615void RewriteObjC::HandleTranslationUnit(TranslationUnit& TU) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000616 // Get the top-level buffer that this corresponds to.
Chris Lattner74a0c772007-11-08 04:27:23 +0000617
618 // Rewrite tabs if we care.
619 //RewriteTabs();
Chris Lattnerf04da132007-10-24 17:06:59 +0000620
Steve Naroffa7b402d2008-03-28 22:26:09 +0000621 if (Diags.hasErrorOccurred())
622 return;
623
624 // Create the output file.
625
Ted Kremeneka95d3752008-09-13 05:16:45 +0000626 llvm::OwningPtr<llvm::raw_ostream> OwnedStream;
627 llvm::raw_ostream *OutFile;
Steve Naroffa7b402d2008-03-28 22:26:09 +0000628 if (OutFileName == "-") {
Ted Kremeneka95d3752008-09-13 05:16:45 +0000629 OutFile = &llvm::outs();
Steve Naroffa7b402d2008-03-28 22:26:09 +0000630 } else if (!OutFileName.empty()) {
Ted Kremeneka95d3752008-09-13 05:16:45 +0000631 std::string Err;
632 OutFile = new llvm::raw_fd_ostream(OutFileName.c_str(), Err);
633 OwnedStream.reset(OutFile);
Steve Naroffa7b402d2008-03-28 22:26:09 +0000634 } else if (InFileName == "-") {
Ted Kremeneka95d3752008-09-13 05:16:45 +0000635 OutFile = &llvm::outs();
Steve Naroffa7b402d2008-03-28 22:26:09 +0000636 } else {
637 llvm::sys::Path Path(InFileName);
638 Path.eraseSuffix();
639 Path.appendSuffix("cpp");
Ted Kremeneka95d3752008-09-13 05:16:45 +0000640 std::string Err;
641 OutFile = new llvm::raw_fd_ostream(Path.toString().c_str(), Err);
642 OwnedStream.reset(OutFile);
Steve Naroffa7b402d2008-03-28 22:26:09 +0000643 }
644
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000645 RewriteInclude();
646
Steve Naroffba92b2e2008-03-27 22:29:16 +0000647 InsertText(SourceLocation::getFileLoc(MainFileID, 0),
648 Preamble.c_str(), Preamble.size(), false);
649
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000650 // Rewrite Objective-c meta data*
651 std::string ResultStr;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000652 RewriteImplementations(ResultStr);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000653
Chris Lattnerf04da132007-10-24 17:06:59 +0000654 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
655 // we are done.
656 if (const RewriteBuffer *RewriteBuf =
657 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000658 //printf("Changed:\n");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000659 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
Chris Lattnerf04da132007-10-24 17:06:59 +0000660 } else {
Chris Lattnerc68ab772008-03-22 00:08:40 +0000661 fprintf(stderr, "No changes\n");
Chris Lattnerf04da132007-10-24 17:06:59 +0000662 }
Fariborz Jahanian4402d812007-11-07 18:40:28 +0000663 // Emit metadata.
Steve Naroffa7b402d2008-03-28 22:26:09 +0000664 *OutFile << ResultStr;
Ted Kremeneka95d3752008-09-13 05:16:45 +0000665 OutFile->flush();
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000666}
667
Chris Lattnerf04da132007-10-24 17:06:59 +0000668//===----------------------------------------------------------------------===//
669// Syntactic (non-AST) Rewriting Code
670//===----------------------------------------------------------------------===//
671
Steve Naroffb29b4272008-04-14 22:03:09 +0000672void RewriteObjC::RewriteInclude() {
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000673 SourceLocation LocStart = SourceLocation::getFileLoc(MainFileID, 0);
674 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
675 const char *MainBufStart = MainBuf.first;
676 const char *MainBufEnd = MainBuf.second;
677 size_t ImportLen = strlen("import");
678 size_t IncludeLen = strlen("include");
679
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000680 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000681 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
682 if (*BufPtr == '#') {
683 if (++BufPtr == MainBufEnd)
684 return;
685 while (*BufPtr == ' ' || *BufPtr == '\t')
686 if (++BufPtr == MainBufEnd)
687 return;
688 if (!strncmp(BufPtr, "import", ImportLen)) {
689 // replace import with include
690 SourceLocation ImportLoc =
691 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattneraadaf782008-01-31 19:51:04 +0000692 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000693 BufPtr += ImportLen;
694 }
695 }
696 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000697}
698
Steve Naroffb29b4272008-04-14 22:03:09 +0000699void RewriteObjC::RewriteTabs() {
Chris Lattnerf04da132007-10-24 17:06:59 +0000700 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
701 const char *MainBufStart = MainBuf.first;
702 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000703
Chris Lattnerf04da132007-10-24 17:06:59 +0000704 // Loop over the whole file, looking for tabs.
705 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
706 if (*BufPtr != '\t')
707 continue;
708
709 // Okay, we found a tab. This tab will turn into at least one character,
710 // but it depends on which 'virtual column' it is in. Compute that now.
711 unsigned VCol = 0;
712 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
713 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
714 ++VCol;
715
716 // Okay, now that we know the virtual column, we know how many spaces to
717 // insert. We assume 8-character tab-stops.
718 unsigned Spaces = 8-(VCol & 7);
719
720 // Get the location of the tab.
721 SourceLocation TabLoc =
722 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
723
724 // Rewrite the single tab character into a sequence of spaces.
Chris Lattneraadaf782008-01-31 19:51:04 +0000725 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerf04da132007-10-24 17:06:59 +0000726 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000727}
728
729
Steve Naroffb29b4272008-04-14 22:03:09 +0000730void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000731 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000732 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerf04da132007-10-24 17:06:59 +0000733
734 // Get the start location and compute the semi location.
735 SourceLocation startLoc = ClassDecl->getLocation();
736 const char *startBuf = SM->getCharacterData(startLoc);
737 const char *semiPtr = strchr(startBuf, ';');
738
739 // Translate to typedef's that forward reference structs with the same name
740 // as the class. As a convenience, we include the original declaration
741 // as a comment.
742 std::string typedefString;
743 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000744 typedefString.append(startBuf, semiPtr-startBuf+1);
745 typedefString += "\n";
746 for (int i = 0; i < numDecls; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000747 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000748 typedefString += "#ifndef _REWRITER_typedef_";
749 typedefString += ForwardDecl->getName();
750 typedefString += "\n";
751 typedefString += "#define _REWRITER_typedef_";
752 typedefString += ForwardDecl->getName();
753 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000754 typedefString += "typedef struct objc_object ";
Steve Naroff934f2762007-10-24 22:48:43 +0000755 typedefString += ForwardDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000756 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000757 }
758
759 // Replace the @class with typedefs corresponding to the classes.
Chris Lattneraadaf782008-01-31 19:51:04 +0000760 ReplaceText(startLoc, semiPtr-startBuf+1,
761 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000762}
763
Steve Naroffb29b4272008-04-14 22:03:09 +0000764void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000765 SourceLocation LocStart = Method->getLocStart();
766 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000767
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000768 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
Steve Naroff94ac21e2008-10-21 13:37:27 +0000769 InsertText(LocStart, "#if 0\n", 6);
770 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000771 } else {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000772 InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000773 }
774}
775
Steve Naroffb29b4272008-04-14 22:03:09 +0000776void RewriteObjC::RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000777{
Chris Lattner55d13b42008-03-16 21:23:50 +0000778 for (unsigned i = 0; i < nProperties; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000779 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000780 SourceLocation Loc = Property->getLocation();
781
Chris Lattneraadaf782008-01-31 19:51:04 +0000782 ReplaceText(Loc, 0, "// ", 3);
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000783
784 // FIXME: handle properties that are declared across multiple lines.
785 }
786}
787
Steve Naroffb29b4272008-04-14 22:03:09 +0000788void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000789 SourceLocation LocStart = CatDecl->getLocStart();
790
791 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000792 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000793
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000794 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000795 E = CatDecl->instmeth_end(); I != E; ++I)
796 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000797 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000798 E = CatDecl->classmeth_end(); I != E; ++I)
799 RewriteMethodDeclaration(*I);
800
Steve Naroff423cb562007-10-30 13:30:57 +0000801 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000802 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000803}
804
Steve Naroffb29b4272008-04-14 22:03:09 +0000805void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000806 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000807
Steve Naroff752d6ef2007-10-30 16:42:30 +0000808 SourceLocation LocStart = PDecl->getLocStart();
809
810 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000811 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000812
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000813 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000814 E = PDecl->instmeth_end(); I != E; ++I)
815 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000816 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000817 E = PDecl->classmeth_end(); I != E; ++I)
818 RewriteMethodDeclaration(*I);
819
Steve Naroff752d6ef2007-10-30 16:42:30 +0000820 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000821 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattneraadaf782008-01-31 19:51:04 +0000822 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000823
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000824 // Must comment out @optional/@required
825 const char *startBuf = SM->getCharacterData(LocStart);
826 const char *endBuf = SM->getCharacterData(LocEnd);
827 for (const char *p = startBuf; p < endBuf; p++) {
828 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
829 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000830 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000831 ReplaceText(OptionalLoc, strlen("@optional"),
832 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000833
834 }
835 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
836 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000837 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000838 ReplaceText(OptionalLoc, strlen("@required"),
839 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000840
841 }
842 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000843}
844
Steve Naroffb29b4272008-04-14 22:03:09 +0000845void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000846 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000847 if (LocStart.isInvalid())
848 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000849 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000850 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000851}
852
Steve Naroffb29b4272008-04-14 22:03:09 +0000853void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000854 std::string &ResultStr) {
Steve Naroff76e429d2008-07-16 14:40:40 +0000855 const FunctionType *FPRetType = 0;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000856 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000857 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000858 ResultStr += "id";
Steve Naroff76e429d2008-07-16 14:40:40 +0000859 else if (OMD->getResultType()->isFunctionPointerType()) {
860 // needs special handling, since pointer-to-functions have special
861 // syntax (where a decaration models use).
862 QualType retType = OMD->getResultType();
863 if (const PointerType* PT = retType->getAsPointerType()) {
864 QualType PointeeTy = PT->getPointeeType();
865 if ((FPRetType = PointeeTy->getAsFunctionType())) {
866 ResultStr += FPRetType->getResultType().getAsString();
867 ResultStr += "(*";
868 }
869 }
870 } else
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000871 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000872 ResultStr += " ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000873
874 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000875 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000876
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000877 if (OMD->isInstance())
878 NameStr += "_I_";
879 else
880 NameStr += "_C_";
881
882 NameStr += OMD->getClassInterface()->getName();
883 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000884
885 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000886 if (ObjCCategoryImplDecl *CID =
887 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000888 NameStr += CID->getName();
889 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000890 }
Steve Naroff563b8282008-04-04 22:23:44 +0000891 // Append selector names, replacing ':' with '_'
892 if (OMD->getSelector().getName().find(':') == std::string::npos)
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000893 NameStr += OMD->getSelector().getName();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000894 else {
895 std::string selString = OMD->getSelector().getName();
896 int len = selString.size();
897 for (int i = 0; i < len; i++)
898 if (selString[i] == ':')
899 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000900 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000901 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000902 // Remember this name for metadata emission
903 MethodInternalNames[OMD] = NameStr;
904 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000905
906 // Rewrite arguments
907 ResultStr += "(";
908
909 // invisible arguments
910 if (OMD->isInstance()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000911 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000912 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +0000913 if (!LangOpts.Microsoft) {
914 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
915 ResultStr += "struct ";
916 }
917 // When rewriting for Microsoft, explicitly omit the structure name.
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000918 ResultStr += OMD->getClassInterface()->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000919 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000920 }
921 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000922 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000923
924 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000925 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000926 ResultStr += " _cmd";
927
928 // Method arguments.
Chris Lattner58cce3b2008-03-16 01:07:14 +0000929 for (unsigned i = 0; i < OMD->getNumParams(); i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000930 ParmVarDecl *PDecl = OMD->getParamDecl(i);
931 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +0000932 if (PDecl->getType()->isObjCQualifiedIdType()) {
933 ResultStr += "id ";
934 ResultStr += PDecl->getName();
935 } else {
936 std::string Name = PDecl->getName();
937 PDecl->getType().getAsStringInternal(Name);
938 ResultStr += Name;
939 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000940 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +0000941 if (OMD->isVariadic())
942 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000943 ResultStr += ") ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000944
Steve Naroff76e429d2008-07-16 14:40:40 +0000945 if (FPRetType) {
946 ResultStr += ")"; // close the precedence "scope" for "*".
947
948 // Now, emit the argument types (if any).
949 if (const FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(FPRetType)) {
950 ResultStr += "(";
951 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
952 if (i) ResultStr += ", ";
953 std::string ParamStr = FT->getArgType(i).getAsString();
954 ResultStr += ParamStr;
955 }
956 if (FT->isVariadic()) {
957 if (FT->getNumArgs()) ResultStr += ", ";
958 ResultStr += "...";
959 }
960 ResultStr += ")";
961 } else {
962 ResultStr += "()";
963 }
964 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000965}
Steve Naroffb29b4272008-04-14 22:03:09 +0000966void RewriteObjC::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000967 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
968 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000969
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000970 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000971 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000972 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000973 InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000974
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000975 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000976 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
977 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000978 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000979 ObjCMethodDecl *OMD = *I;
980 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000981 SourceLocation LocStart = OMD->getLocStart();
982 SourceLocation LocEnd = OMD->getBody()->getLocStart();
983
984 const char *startBuf = SM->getCharacterData(LocStart);
985 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000986 ReplaceText(LocStart, endBuf-startBuf,
987 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000988 }
989
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000990 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000991 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
992 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000993 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000994 ObjCMethodDecl *OMD = *I;
995 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000996 SourceLocation LocStart = OMD->getLocStart();
997 SourceLocation LocEnd = OMD->getBody()->getLocStart();
998
999 const char *startBuf = SM->getCharacterData(LocStart);
1000 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +00001001 ReplaceText(LocStart, endBuf-startBuf,
1002 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001003 }
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001004 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001005 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001006 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001007 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001008}
1009
Steve Naroffb29b4272008-04-14 22:03:09 +00001010void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001011 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001012 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001013 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001014 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff32174822007-11-09 12:50:28 +00001015 ResultStr += ClassDecl->getName();
1016 ResultStr += "\n";
1017 ResultStr += "#define _REWRITER_typedef_";
1018 ResultStr += ClassDecl->getName();
1019 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001020 ResultStr += "typedef struct objc_object ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001021 ResultStr += ClassDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +00001022 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001023 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001024 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001025 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001026 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Narofff908a872007-10-30 02:23:23 +00001027
Fariborz Jahanian957cf652007-11-07 00:09:37 +00001028 RewriteProperties(ClassDecl->getNumPropertyDecl(),
1029 ClassDecl->getPropertyDecl());
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001030 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001031 E = ClassDecl->instmeth_end(); I != E; ++I)
1032 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001033 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001034 E = ClassDecl->classmeth_end(); I != E; ++I)
1035 RewriteMethodDeclaration(*I);
1036
Steve Naroff2feac5e2007-10-30 03:43:13 +00001037 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +00001038 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +00001039}
1040
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001041Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
1042 SourceLocation OrigStart) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001043 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff54055232008-10-27 17:20:55 +00001044 if (CurMethodDef) {
Steve Naroff05b8c782008-03-12 00:25:36 +00001045 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +00001046 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
1047 // lookup which class implements the instance variable.
1048 ObjCInterfaceDecl *clsDeclared = 0;
1049 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
1050 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1051
1052 // Synthesize an explicit cast to gain access to the ivar.
1053 std::string RecName = clsDeclared->getIdentifier()->getName();
1054 RecName += "_IMPL";
1055 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001056 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001057 SourceLocation(), II);
Steve Narofff0757612008-05-08 17:52:16 +00001058 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1059 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001060 CastExpr *castExpr = new CStyleCastExpr(castT, IV->getBase(), castT,
Douglas Gregor49badde2008-10-27 19:41:14 +00001061 SourceLocation());
Steve Narofff0757612008-05-08 17:52:16 +00001062 // Don't forget the parens to enforce the proper binding.
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001063 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
1064 IV->getBase()->getLocEnd(),
1065 castExpr);
Steve Narofff0757612008-05-08 17:52:16 +00001066 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +00001067 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001068 MemberExpr *ME = new MemberExpr(PE, true, D, IV->getLocation(),
1069 D->getType());
Steve Narofff0757612008-05-08 17:52:16 +00001070 ReplaceStmt(IV, ME);
1071 delete IV;
1072 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001073 }
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001074
1075 ReplaceStmt(IV->getBase(), PE);
1076 // Cannot delete IV->getBase(), since PE points to it.
1077 // Replace the old base with the cast. This is important when doing
1078 // embedded rewrites. For example, [newInv->_container addObject:0].
1079 IV->setBase(PE);
1080 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001081 }
Steve Naroff84472a82008-04-18 21:55:08 +00001082 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001083 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
1084
1085 // Explicit ivar refs need to have a cast inserted.
1086 // FIXME: consider sharing some of this code with the code above.
1087 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +00001088 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001089 // lookup which class implements the instance variable.
1090 ObjCInterfaceDecl *clsDeclared = 0;
Steve Narofff0757612008-05-08 17:52:16 +00001091 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001092 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1093
1094 // Synthesize an explicit cast to gain access to the ivar.
1095 std::string RecName = clsDeclared->getIdentifier()->getName();
1096 RecName += "_IMPL";
1097 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001098 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001099 SourceLocation(), II);
Steve Naroff9f525972008-05-06 23:20:07 +00001100 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1101 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001102 CastExpr *castExpr = new CStyleCastExpr(castT, IV->getBase(), castT,
Douglas Gregor49badde2008-10-27 19:41:14 +00001103 SourceLocation());
Steve Naroff9f525972008-05-06 23:20:07 +00001104 // Don't forget the parens to enforce the proper binding.
Chris Lattner8d366162008-05-28 16:38:23 +00001105 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
1106 IV->getBase()->getLocEnd(), castExpr);
Steve Naroff9f525972008-05-06 23:20:07 +00001107 ReplaceStmt(IV->getBase(), PE);
1108 // Cannot delete IV->getBase(), since PE points to it.
1109 // Replace the old base with the cast. This is important when doing
1110 // embedded rewrites. For example, [newInv->_container addObject:0].
1111 IV->setBase(PE);
1112 return IV;
1113 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001114 }
Steve Naroff84472a82008-04-18 21:55:08 +00001115 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +00001116}
1117
Chris Lattnerf04da132007-10-24 17:06:59 +00001118//===----------------------------------------------------------------------===//
1119// Function Body / Expression rewriting
1120//===----------------------------------------------------------------------===//
1121
Steve Naroffb29b4272008-04-14 22:03:09 +00001122Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001123 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
1124 isa<DoStmt>(S) || isa<ForStmt>(S))
1125 Stmts.push_back(S);
1126 else if (isa<ObjCForCollectionStmt>(S)) {
1127 Stmts.push_back(S);
1128 ObjCBcLabelNo.push_back(++BcLabelCount);
1129 }
1130
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001131 SourceRange OrigStmtRange = S->getSourceRange();
Chris Lattner338d1e22008-01-31 05:10:40 +00001132
1133 // Start by rewriting all children.
Chris Lattner311ff022007-10-16 22:36:42 +00001134 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1135 CI != E; ++CI)
Steve Naroff75730982007-11-07 04:08:17 +00001136 if (*CI) {
Steve Naroffa48396e2008-10-27 18:50:14 +00001137 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
1138 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(CBE->getBody());
1139 if (newStmt)
1140 *CI = newStmt;
1141
1142 // We've just rewritten the block body in place.
1143 // Now we snarf the rewritten text and stash it away for later use.
1144 std::string S = Rewrite.getRewritenText(CBE->getSourceRange());
1145 RewrittenBlockExprs[CBE] = S;
1146 std::string Init = SynthesizeBlockInitExpr(CBE);
1147 // Do the rewrite, using S.size() which contains the rewritten size.
1148 ReplaceText(CBE->getLocStart(), S.size(), Init.c_str(), Init.size());
1149 } else {
1150 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
1151 if (newStmt)
1152 *CI = newStmt;
1153 }
Steve Naroff75730982007-11-07 04:08:17 +00001154 }
Steve Naroffebf2b562007-10-23 23:50:29 +00001155
1156 // Handle specific things.
1157 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
1158 return RewriteAtEncode(AtEncode);
Steve Naroff7e3411b2007-11-15 02:58:25 +00001159
1160 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001161 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
Steve Naroffb42f8412007-11-05 14:50:49 +00001162
1163 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
1164 return RewriteAtSelector(AtSelector);
Steve Narofff69cc5d2008-01-30 19:17:43 +00001165
Steve Naroffbeaf2992007-11-03 11:27:19 +00001166 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
1167 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +00001168
Steve Naroff934f2762007-10-24 22:48:43 +00001169 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
1170 // Before we rewrite it, put the original message expression in a comment.
1171 SourceLocation startLoc = MessExpr->getLocStart();
1172 SourceLocation endLoc = MessExpr->getLocEnd();
1173
1174 const char *startBuf = SM->getCharacterData(startLoc);
1175 const char *endBuf = SM->getCharacterData(endLoc);
1176
1177 std::string messString;
1178 messString += "// ";
1179 messString.append(startBuf, endBuf-startBuf+1);
1180 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +00001181
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001182 // FIXME: Missing definition of
1183 // InsertText(clang::SourceLocation, char const*, unsigned int).
1184 // InsertText(startLoc, messString.c_str(), messString.size());
Steve Naroff934f2762007-10-24 22:48:43 +00001185 // Tried this, but it didn't work either...
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001186 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +00001187 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00001188 }
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001189
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001190 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
1191 return RewriteObjCTryStmt(StmtTry);
Steve Naroff2bd03922007-11-07 15:32:26 +00001192
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001193 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
1194 return RewriteObjCSynchronizedStmt(StmtTry);
1195
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001196 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
1197 return RewriteObjCThrowStmt(StmtThrow);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001198
1199 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
1200 return RewriteObjCProtocolExpr(ProtocolExp);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001201
1202 if (ObjCForCollectionStmt *StmtForCollection =
1203 dyn_cast<ObjCForCollectionStmt>(S))
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001204 return RewriteObjCForCollectionStmt(StmtForCollection,
1205 OrigStmtRange.getEnd());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001206 if (BreakStmt *StmtBreakStmt =
1207 dyn_cast<BreakStmt>(S))
1208 return RewriteBreakStmt(StmtBreakStmt);
1209 if (ContinueStmt *StmtContinueStmt =
1210 dyn_cast<ContinueStmt>(S))
1211 return RewriteContinueStmt(StmtContinueStmt);
Steve Naroff4f95b752008-07-29 18:15:38 +00001212
Ted Kremenekab9bae72008-10-06 22:45:07 +00001213 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
1214 // and cast exprs.
1215 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
1216 // FIXME: What we're doing here is modifying the type-specifier that
1217 // precedes the first Decl. In the future the DeclGroup should have
1218 // a separate type-specifier that we can rewrite.
1219 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Steve Naroff54055232008-10-27 17:20:55 +00001220
1221 // Blocks rewrite rules.
1222 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
1223 DI != DE; ++DI) {
1224
1225 ScopedDecl *SD = *DI;
1226 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
1227 if (isBlockPointerType(ND->getType()))
1228 RewriteBlockPointerDecl(ND);
1229 else if (ND->getType()->isFunctionPointerType())
1230 CheckFunctionPointerDecl(ND->getType(), ND);
1231 }
1232 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
1233 if (isBlockPointerType(TD->getUnderlyingType()))
1234 RewriteBlockPointerDecl(TD);
1235 else if (TD->getUnderlyingType()->isFunctionPointerType())
1236 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
1237 }
1238 }
Ted Kremenekab9bae72008-10-06 22:45:07 +00001239 }
1240
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001241 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
Steve Naroff4f95b752008-07-29 18:15:38 +00001242 RewriteObjCQualifiedInterfaceTypes(CE);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001243
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001244 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
1245 isa<DoStmt>(S) || isa<ForStmt>(S)) {
1246 assert(!Stmts.empty() && "Statement stack is empty");
1247 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
1248 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
1249 && "Statement stack mismatch");
1250 Stmts.pop_back();
1251 }
Steve Naroff54055232008-10-27 17:20:55 +00001252 // Handle blocks rewriting.
1253 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
1254 if (BDRE->isByRef())
1255 RewriteBlockDeclRefExpr(BDRE);
1256 }
1257 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
1258 if (CE->getCallee()->getType()->isBlockPointerType())
1259 RewriteBlockCall(CE);
1260 }
1261 if (CastExpr *CE = dyn_cast<CastExpr>(S)) {
Steve Naroff80c28552008-10-27 20:54:44 +00001262 if (CE->getLocStart().isValid())
1263 RewriteCastExpr(CE);
Steve Naroff54055232008-10-27 17:20:55 +00001264 }
Steve Naroff874e2322007-11-15 10:28:18 +00001265#if 0
1266 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
1267 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
1268 // Get the new text.
Ted Kremeneka95d3752008-09-13 05:16:45 +00001269 std::string SStr;
1270 llvm::raw_string_ostream Buf(SStr);
Steve Naroff874e2322007-11-15 10:28:18 +00001271 Replacement->printPretty(Buf);
1272 const std::string &Str = Buf.str();
1273
1274 printf("CAST = %s\n", &Str[0]);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001275 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
Steve Naroff874e2322007-11-15 10:28:18 +00001276 delete S;
1277 return Replacement;
1278 }
1279#endif
Chris Lattnere64b7772007-10-24 16:57:36 +00001280 // Return this stmt unmodified.
1281 return S;
Chris Lattner311ff022007-10-16 22:36:42 +00001282}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001283
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001284/// SynthCountByEnumWithState - To print:
1285/// ((unsigned int (*)
1286/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1287/// (void *)objc_msgSend)((id)l_collection,
1288/// sel_registerName(
1289/// "countByEnumeratingWithState:objects:count:"),
1290/// &enumState,
1291/// (id *)items, (unsigned int)16)
1292///
Steve Naroffb29b4272008-04-14 22:03:09 +00001293void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001294 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1295 "id *, unsigned int))(void *)objc_msgSend)";
1296 buf += "\n\t\t";
1297 buf += "((id)l_collection,\n\t\t";
1298 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1299 buf += "\n\t\t";
1300 buf += "&enumState, "
1301 "(id *)items, (unsigned int)16)";
1302}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001303
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001304/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1305/// statement to exit to its outer synthesized loop.
1306///
Steve Naroffb29b4272008-04-14 22:03:09 +00001307Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001308 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1309 return S;
1310 // replace break with goto __break_label
1311 std::string buf;
1312
1313 SourceLocation startLoc = S->getLocStart();
1314 buf = "goto __break_label_";
1315 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001316 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001317
1318 return 0;
1319}
1320
1321/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1322/// statement to continue with its inner synthesized loop.
1323///
Steve Naroffb29b4272008-04-14 22:03:09 +00001324Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001325 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1326 return S;
1327 // replace continue with goto __continue_label
1328 std::string buf;
1329
1330 SourceLocation startLoc = S->getLocStart();
1331 buf = "goto __continue_label_";
1332 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001333 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001334
1335 return 0;
1336}
1337
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001338/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001339/// It rewrites:
1340/// for ( type elem in collection) { stmts; }
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001341
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001342/// Into:
1343/// {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001344/// type elem;
1345/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001346/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001347/// id l_collection = (id)collection;
1348/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1349/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001350/// if (limit) {
1351/// unsigned long startMutations = *enumState.mutationsPtr;
1352/// do {
1353/// unsigned long counter = 0;
1354/// do {
1355/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001356/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001357/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001358/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001359/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001360/// } while (counter < limit);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001361/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1362/// objects:items count:16]);
1363/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001364/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001365/// }
1366/// else
1367/// elem = nil;
1368/// }
1369///
Steve Naroffb29b4272008-04-14 22:03:09 +00001370Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001371 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001372 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1373 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1374 "ObjCForCollectionStmt Statement stack mismatch");
1375 assert(!ObjCBcLabelNo.empty() &&
1376 "ObjCForCollectionStmt - Label No stack empty");
1377
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001378 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001379 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001380 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001381 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001382 std::string buf;
1383 buf = "\n{\n\t";
1384 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1385 // type elem;
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001386 ScopedDecl* D = DS->getSolitaryDecl();
1387 QualType ElementType = cast<ValueDecl>(D)->getType();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001388 elementTypeAsString = ElementType.getAsString();
1389 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001390 buf += " ";
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001391 elementName = D->getName();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001392 buf += elementName;
1393 buf += ";\n\t";
1394 }
Chris Lattner06767512008-04-08 05:52:18 +00001395 else {
1396 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001397 elementName = DR->getDecl()->getName();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001398 elementTypeAsString
1399 = cast<ValueDecl>(DR->getDecl())->getType().getAsString();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001400 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001401
1402 // struct __objcFastEnumerationState enumState = { 0 };
1403 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1404 // id items[16];
1405 buf += "id items[16];\n\t";
1406 // id l_collection = (id)
1407 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001408 // Find start location of 'collection' the hard way!
1409 const char *startCollectionBuf = startBuf;
1410 startCollectionBuf += 3; // skip 'for'
1411 startCollectionBuf = strchr(startCollectionBuf, '(');
1412 startCollectionBuf++; // skip '('
1413 // find 'in' and skip it.
1414 while (*startCollectionBuf != ' ' ||
1415 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1416 (*(startCollectionBuf+3) != ' ' &&
1417 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1418 startCollectionBuf++;
1419 startCollectionBuf += 3;
1420
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001421 // Replace: "for (type element in" with string constructed thus far.
Chris Lattneraadaf782008-01-31 19:51:04 +00001422 ReplaceText(startLoc, startCollectionBuf - startBuf,
1423 buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001424 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001425 SourceLocation rightParenLoc = S->getRParenLoc();
1426 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1427 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001428 buf = ";\n\t";
1429
1430 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1431 // objects:items count:16];
1432 // which is synthesized into:
1433 // unsigned int limit =
1434 // ((unsigned int (*)
1435 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1436 // (void *)objc_msgSend)((id)l_collection,
1437 // sel_registerName(
1438 // "countByEnumeratingWithState:objects:count:"),
1439 // (struct __objcFastEnumerationState *)&state,
1440 // (id *)items, (unsigned int)16);
1441 buf += "unsigned long limit =\n\t\t";
1442 SynthCountByEnumWithState(buf);
1443 buf += ";\n\t";
1444 /// if (limit) {
1445 /// unsigned long startMutations = *enumState.mutationsPtr;
1446 /// do {
1447 /// unsigned long counter = 0;
1448 /// do {
1449 /// if (startMutations != *enumState.mutationsPtr)
1450 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001451 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001452 buf += "if (limit) {\n\t";
1453 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1454 buf += "do {\n\t\t";
1455 buf += "unsigned long counter = 0;\n\t\t";
1456 buf += "do {\n\t\t\t";
1457 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1458 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1459 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001460 buf += " = (";
1461 buf += elementTypeAsString;
1462 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001463 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattneraadaf782008-01-31 19:51:04 +00001464 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001465
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001466 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001467 /// } while (counter < limit);
1468 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1469 /// objects:items count:16]);
1470 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001471 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001472 /// }
1473 /// else
1474 /// elem = nil;
1475 /// }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001476 ///
1477 buf = ";\n\t";
1478 buf += "__continue_label_";
1479 buf += utostr(ObjCBcLabelNo.back());
1480 buf += ": ;";
1481 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001482 buf += "} while (counter < limit);\n\t";
1483 buf += "} while (limit = ";
1484 SynthCountByEnumWithState(buf);
1485 buf += ");\n\t";
1486 buf += elementName;
1487 buf += " = nil;\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001488 buf += "__break_label_";
1489 buf += utostr(ObjCBcLabelNo.back());
1490 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001491 buf += "}\n\t";
1492 buf += "else\n\t\t";
1493 buf += elementName;
1494 buf += " = nil;\n";
1495 buf += "}\n";
Steve Naroff600e4e82008-07-21 18:26:02 +00001496
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001497 // Insert all these *after* the statement body.
Steve Naroff600e4e82008-07-21 18:26:02 +00001498 if (isa<CompoundStmt>(S->getBody())) {
1499 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1500 InsertText(endBodyLoc, buf.c_str(), buf.size());
1501 } else {
1502 /* Need to treat single statements specially. For example:
1503 *
1504 * for (A *a in b) if (stuff()) break;
1505 * for (A *a in b) xxxyy;
1506 *
1507 * The following code simply scans ahead to the semi to find the actual end.
1508 */
1509 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1510 const char *semiBuf = strchr(stmtBuf, ';');
1511 assert(semiBuf && "Can't find ';'");
1512 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1513 InsertText(endBodyLoc, buf.c_str(), buf.size());
1514 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001515 Stmts.pop_back();
1516 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001517 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001518}
1519
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001520/// RewriteObjCSynchronizedStmt -
1521/// This routine rewrites @synchronized(expr) stmt;
1522/// into:
1523/// objc_sync_enter(expr);
1524/// @try stmt @finally { objc_sync_exit(expr); }
1525///
Steve Naroffb29b4272008-04-14 22:03:09 +00001526Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001527 // Get the start location and compute the semi location.
1528 SourceLocation startLoc = S->getLocStart();
1529 const char *startBuf = SM->getCharacterData(startLoc);
1530
1531 assert((*startBuf == '@') && "bogus @synchronized location");
1532
1533 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001534 buf = "objc_sync_enter((id)";
1535 const char *lparenBuf = startBuf;
1536 while (*lparenBuf != '(') lparenBuf++;
1537 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Steve Naroffc7089f12008-08-19 13:04:19 +00001538 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1539 // the sync expression is typically a message expression that's already
1540 // been rewritten! (which implies the SourceLocation's are invalid).
1541 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001542 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001543 while (*endBuf != ')') endBuf--;
1544 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001545 buf = ");\n";
1546 // declare a new scope with two variables, _stack and _rethrow.
1547 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1548 buf += "int buf[18/*32-bit i386*/];\n";
1549 buf += "char *pointers[4];} _stack;\n";
1550 buf += "id volatile _rethrow = 0;\n";
1551 buf += "objc_exception_try_enter(&_stack);\n";
1552 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00001553 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001554 startLoc = S->getSynchBody()->getLocEnd();
1555 startBuf = SM->getCharacterData(startLoc);
1556
Steve Naroffc7089f12008-08-19 13:04:19 +00001557 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001558 SourceLocation lastCurlyLoc = startLoc;
1559 buf = "}\nelse {\n";
1560 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1561 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb2a39452008-07-16 19:47:39 +00001562 buf += " objc_sync_exit(";
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001563 Expr *syncExpr = new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00001564 S->getSynchExpr(),
1565 Context->getObjCIdType(),
1566 SourceLocation());
Ted Kremeneka95d3752008-09-13 05:16:45 +00001567 std::string syncExprBufS;
1568 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Steve Naroff3498cc92008-08-21 13:03:03 +00001569 syncExpr->printPretty(syncExprBuf);
Steve Naroffb2a39452008-07-16 19:47:39 +00001570 buf += syncExprBuf.str();
1571 buf += ");\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001572 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1573 buf += "}\n";
1574 buf += "}";
1575
Chris Lattneraadaf782008-01-31 19:51:04 +00001576 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001577 return 0;
1578}
1579
Steve Naroffb29b4272008-04-14 22:03:09 +00001580Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001581 // Get the start location and compute the semi location.
1582 SourceLocation startLoc = S->getLocStart();
1583 const char *startBuf = SM->getCharacterData(startLoc);
1584
1585 assert((*startBuf == '@') && "bogus @try location");
1586
1587 std::string buf;
1588 // declare a new scope with two variables, _stack and _rethrow.
1589 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1590 buf += "int buf[18/*32-bit i386*/];\n";
1591 buf += "char *pointers[4];} _stack;\n";
1592 buf += "id volatile _rethrow = 0;\n";
1593 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001594 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001595
Chris Lattneraadaf782008-01-31 19:51:04 +00001596 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001597
1598 startLoc = S->getTryBody()->getLocEnd();
1599 startBuf = SM->getCharacterData(startLoc);
1600
1601 assert((*startBuf == '}') && "bogus @try block");
Steve Naroffc9ba1722008-07-16 15:31:30 +00001602
Steve Naroff75730982007-11-07 04:08:17 +00001603 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffc9ba1722008-07-16 15:31:30 +00001604 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1605 if (catchList) {
1606 startLoc = startLoc.getFileLocWithOffset(1);
1607 buf = " /* @catch begin */ else {\n";
1608 buf += " id _caught = objc_exception_extract(&_stack);\n";
1609 buf += " objc_exception_try_enter (&_stack);\n";
1610 buf += " if (_setjmp(_stack.buf))\n";
1611 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1612 buf += " else { /* @catch continue */";
1613
1614 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001615 } else { /* no catch list */
1616 buf = "}\nelse {\n";
1617 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1618 buf += "}";
1619 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffc9ba1722008-07-16 15:31:30 +00001620 }
Steve Naroff75730982007-11-07 04:08:17 +00001621 bool sawIdTypedCatch = false;
1622 Stmt *lastCatchBody = 0;
Steve Naroff75730982007-11-07 04:08:17 +00001623 while (catchList) {
1624 Stmt *catchStmt = catchList->getCatchParamStmt();
1625
1626 if (catchList == S->getCatchStmts())
1627 buf = "if ("; // we are generating code for the first catch clause
1628 else
1629 buf = "else if (";
1630 startLoc = catchList->getLocStart();
1631 startBuf = SM->getCharacterData(startLoc);
1632
1633 assert((*startBuf == '@') && "bogus @catch location");
1634
1635 const char *lParenLoc = strchr(startBuf, '(');
1636
Steve Naroffbe4b3332008-02-01 22:08:12 +00001637 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001638 // Now rewrite the body...
1639 lastCatchBody = catchList->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001640 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1641 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner06767512008-04-08 05:52:18 +00001642 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1643 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001644 assert((*bodyBuf == '{') && "bogus @catch body location");
1645
1646 buf += "1) { id _tmp = _caught;";
1647 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1648 buf.c_str(), buf.size());
1649 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Ted Kremenek50a25e22008-10-06 22:39:38 +00001650 QualType t = dyn_cast<ValueDecl>(declStmt->getSolitaryDecl())->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001651 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001652 buf += "1) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001653 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001654 sawIdTypedCatch = true;
1655 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001656 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroff75730982007-11-07 04:08:17 +00001657
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001658 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001659 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001660 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroff75730982007-11-07 04:08:17 +00001661 buf += cls->getDecl()->getName();
Steve Naroff21867b12007-11-07 18:43:40 +00001662 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001663 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001664 }
1665 }
1666 // Now rewrite the body...
1667 lastCatchBody = catchList->getCatchBody();
1668 SourceLocation rParenLoc = catchList->getRParenLoc();
1669 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1670 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1671 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1672 assert((*rParenBuf == ')') && "bogus @catch paren location");
1673 assert((*bodyBuf == '{') && "bogus @catch body location");
1674
1675 buf = " = _caught;";
1676 // Here we replace ") {" with "= _caught;" (which initializes and
1677 // declares the @catch parameter).
Chris Lattneraadaf782008-01-31 19:51:04 +00001678 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001679 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001680 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001681 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001682 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001683 catchList = catchList->getNextCatchStmt();
1684 }
1685 // Complete the catch list...
1686 if (lastCatchBody) {
1687 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001688 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1689 "bogus @catch body location");
Steve Naroff75730982007-11-07 04:08:17 +00001690
Steve Naroff378f47a2008-09-11 15:29:03 +00001691 // Insert the last (implicit) else clause *before* the right curly brace.
1692 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1693 buf = "} /* last catch end */\n";
1694 buf += "else {\n";
1695 buf += " _rethrow = _caught;\n";
1696 buf += " objc_exception_try_exit(&_stack);\n";
1697 buf += "} } /* @catch end */\n";
1698 if (!S->getFinallyStmt())
1699 buf += "}\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001700 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001701
1702 // Set lastCurlyLoc
1703 lastCurlyLoc = lastCatchBody->getLocEnd();
1704 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001705 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001706 startLoc = finalStmt->getLocStart();
1707 startBuf = SM->getCharacterData(startLoc);
1708 assert((*startBuf == '@') && "bogus @finally start");
1709
1710 buf = "/* @finally */";
Chris Lattneraadaf782008-01-31 19:51:04 +00001711 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001712
1713 Stmt *body = finalStmt->getFinallyBody();
1714 SourceLocation startLoc = body->getLocStart();
1715 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001716 assert(*SM->getCharacterData(startLoc) == '{' &&
1717 "bogus @finally body location");
1718 assert(*SM->getCharacterData(endLoc) == '}' &&
1719 "bogus @finally body location");
Steve Naroff75730982007-11-07 04:08:17 +00001720
1721 startLoc = startLoc.getFileLocWithOffset(1);
1722 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001723 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001724 endLoc = endLoc.getFileLocWithOffset(-1);
1725 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001726 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001727
1728 // Set lastCurlyLoc
1729 lastCurlyLoc = body->getLocEnd();
Steve Naroff378f47a2008-09-11 15:29:03 +00001730 } else { /* no finally clause - make sure we synthesize an implicit one */
1731 buf = "{ /* implicit finally clause */\n";
1732 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1733 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1734 buf += "}";
1735 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001736 }
1737 // Now emit the final closing curly brace...
1738 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1739 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001740 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001741 return 0;
1742}
1743
Steve Naroffb29b4272008-04-14 22:03:09 +00001744Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001745 return 0;
1746}
1747
Steve Naroffb29b4272008-04-14 22:03:09 +00001748Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001749 return 0;
1750}
1751
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001752// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff2bd03922007-11-07 15:32:26 +00001753// the throw expression is typically a message expression that's already
1754// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001755Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001756 // Get the start location and compute the semi location.
1757 SourceLocation startLoc = S->getLocStart();
1758 const char *startBuf = SM->getCharacterData(startLoc);
1759
1760 assert((*startBuf == '@') && "bogus @throw location");
1761
1762 std::string buf;
1763 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001764 if (S->getThrowExpr())
1765 buf = "objc_exception_throw(";
1766 else // add an implicit argument
1767 buf = "objc_exception_throw(_caught";
Steve Naroff4ba0acb2008-07-25 15:41:30 +00001768
1769 // handle "@ throw" correctly.
1770 const char *wBuf = strchr(startBuf, 'w');
1771 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1772 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
1773
Steve Naroff2bd03922007-11-07 15:32:26 +00001774 const char *semiBuf = strchr(startBuf, ';');
1775 assert((*semiBuf == ';') && "@throw: can't find ';'");
1776 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1777 buf = ");";
Chris Lattneraadaf782008-01-31 19:51:04 +00001778 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001779 return 0;
1780}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001781
Steve Naroffb29b4272008-04-14 22:03:09 +00001782Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001783 // Create a new string expression.
1784 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001785 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001786 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001787 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1788 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +00001789 SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001790 ReplaceStmt(Exp, Replacement);
Chris Lattnere365c502007-11-30 22:25:36 +00001791
Chris Lattner07506182007-11-30 22:53:43 +00001792 // Replace this subexpr in the parent.
Chris Lattnere64b7772007-10-24 16:57:36 +00001793 delete Exp;
1794 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001795}
1796
Steve Naroffb29b4272008-04-14 22:03:09 +00001797Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroffb42f8412007-11-05 14:50:49 +00001798 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1799 // Create a call to sel_registerName("selName").
1800 llvm::SmallVector<Expr*, 8> SelExprs;
1801 QualType argType = Context->getPointerType(Context->CharTy);
1802 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1803 Exp->getSelector().getName().size(),
1804 false, argType, SourceLocation(),
1805 SourceLocation()));
1806 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1807 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001808 ReplaceStmt(Exp, SelExp);
Steve Naroffb42f8412007-11-05 14:50:49 +00001809 delete Exp;
1810 return SelExp;
1811}
1812
Steve Naroffb29b4272008-04-14 22:03:09 +00001813CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff934f2762007-10-24 22:48:43 +00001814 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001815 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001816 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +00001817
1818 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +00001819 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +00001820
1821 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001822 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +00001823 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
1824
1825 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +00001826
Steve Naroff934f2762007-10-24 22:48:43 +00001827 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1828}
1829
Steve Naroffd5255f52007-11-01 13:24:47 +00001830static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1831 const char *&startRef, const char *&endRef) {
1832 while (startBuf < endBuf) {
1833 if (*startBuf == '<')
1834 startRef = startBuf; // mark the start.
1835 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001836 if (startRef && *startRef == '<') {
1837 endRef = startBuf; // mark the end.
1838 return true;
1839 }
1840 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001841 }
1842 startBuf++;
1843 }
1844 return false;
1845}
1846
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001847static void scanToNextArgument(const char *&argRef) {
1848 int angle = 0;
1849 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1850 if (*argRef == '<')
1851 angle++;
1852 else if (*argRef == '>')
1853 angle--;
1854 argRef++;
1855 }
1856 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1857}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001858
Steve Naroffb29b4272008-04-14 22:03:09 +00001859bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001860
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001861 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001862 return true;
1863
Steve Naroffd5255f52007-11-01 13:24:47 +00001864 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +00001865 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001866 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff9165ad32007-10-31 04:38:33 +00001867 return true; // we have "Class <Protocol> *".
1868 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001869 return false;
1870}
1871
Steve Naroff4f95b752008-07-29 18:15:38 +00001872void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1873 QualType Type = E->getType();
1874 if (needToScanForQualifiers(Type)) {
1875 SourceLocation Loc = E->getLocStart();
1876 const char *startBuf = SM->getCharacterData(Loc);
1877 const char *endBuf = SM->getCharacterData(E->getLocEnd());
1878 const char *startRef = 0, *endRef = 0;
1879 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1880 // Get the locations of the startRef, endRef.
1881 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1882 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1883 // Comment out the protocol references.
1884 InsertText(LessLoc, "/*", 2);
1885 InsertText(GreaterLoc, "*/", 2);
1886 }
1887 }
1888}
1889
Steve Naroffb29b4272008-04-14 22:03:09 +00001890void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001891 SourceLocation Loc;
1892 QualType Type;
1893 const FunctionTypeProto *proto = 0;
1894 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1895 Loc = VD->getLocation();
1896 Type = VD->getType();
1897 }
1898 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1899 Loc = FD->getLocation();
1900 // Check for ObjC 'id' and class types that have been adorned with protocol
1901 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1902 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1903 assert(funcType && "missing function type");
1904 proto = dyn_cast<FunctionTypeProto>(funcType);
1905 if (!proto)
1906 return;
1907 Type = proto->getResultType();
1908 }
1909 else
1910 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001911
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001912 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001913 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001914
1915 const char *endBuf = SM->getCharacterData(Loc);
1916 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00001917 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001918 startBuf--; // scan backward (from the decl location) for return type.
1919 const char *startRef = 0, *endRef = 0;
1920 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1921 // Get the locations of the startRef, endRef.
1922 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1923 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1924 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001925 InsertText(LessLoc, "/*", 2);
1926 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001927 }
1928 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001929 if (!proto)
1930 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001931 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001932 const char *startBuf = SM->getCharacterData(Loc);
1933 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001934 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1935 if (needToScanForQualifiers(proto->getArgType(i))) {
1936 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001937
Steve Naroffd5255f52007-11-01 13:24:47 +00001938 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001939 // scan forward (from the decl location) for argument types.
1940 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001941 const char *startRef = 0, *endRef = 0;
1942 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1943 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001944 SourceLocation LessLoc =
1945 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1946 SourceLocation GreaterLoc =
1947 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001948 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001949 InsertText(LessLoc, "/*", 2);
1950 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001951 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001952 startBuf = ++endBuf;
1953 }
1954 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00001955 // If the function name is derived from a macro expansion, then the
1956 // argument buffer will not follow the name. Need to speak with Chris.
1957 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001958 startBuf++; // scan forward (from the decl location) for argument types.
1959 startBuf++;
1960 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001961 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001962}
1963
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001964// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00001965void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001966 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1967 llvm::SmallVector<QualType, 16> ArgTys;
1968 ArgTys.push_back(Context->getPointerType(
1969 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001970 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001971 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001972 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001973 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001974 SourceLocation(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001975 SelGetUidIdent, getFuncType,
1976 FunctionDecl::Extern, false, 0);
1977}
1978
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001979// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
Steve Naroffb29b4272008-04-14 22:03:09 +00001980void RewriteObjC::SynthGetProtocolFunctionDecl() {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001981 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1982 llvm::SmallVector<QualType, 16> ArgTys;
1983 ArgTys.push_back(Context->getPointerType(
1984 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001985 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001986 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001987 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001988 GetProtocolFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001989 SourceLocation(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001990 SelGetProtoIdent, getFuncType,
1991 FunctionDecl::Extern, false, 0);
1992}
1993
Steve Naroffb29b4272008-04-14 22:03:09 +00001994void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001995 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +00001996 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001997 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001998 return;
1999 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002000 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00002001}
2002
Steve Naroffc0a123c2008-03-11 17:37:02 +00002003// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00002004void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002005 if (SuperContructorFunctionDecl)
2006 return;
2007 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_super");
2008 llvm::SmallVector<QualType, 16> ArgTys;
2009 QualType argT = Context->getObjCIdType();
2010 assert(!argT.isNull() && "Can't find 'id' type");
2011 ArgTys.push_back(argT);
2012 ArgTys.push_back(argT);
2013 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2014 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002015 false, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002016 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002017 SourceLocation(),
Steve Naroffc0a123c2008-03-11 17:37:02 +00002018 msgSendIdent, msgSendType,
2019 FunctionDecl::Extern, false, 0);
2020}
2021
Steve Naroff09b266e2007-10-30 23:14:51 +00002022// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002023void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002024 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2025 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002026 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002027 assert(!argT.isNull() && "Can't find 'id' type");
2028 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002029 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002030 assert(!argT.isNull() && "Can't find 'SEL' type");
2031 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002032 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002033 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002034 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002035 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002036 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002037 msgSendIdent, msgSendType,
2038 FunctionDecl::Extern, false, 0);
2039}
2040
Steve Naroff874e2322007-11-15 10:28:18 +00002041// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002042void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00002043 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2044 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002045 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002046 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002047 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002048 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2049 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2050 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002051 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002052 assert(!argT.isNull() && "Can't find 'SEL' type");
2053 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002054 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00002055 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002056 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002057 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002058 SourceLocation(),
Steve Naroff874e2322007-11-15 10:28:18 +00002059 msgSendIdent, msgSendType,
2060 FunctionDecl::Extern, false, 0);
2061}
2062
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002063// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002064void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002065 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2066 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002067 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002068 assert(!argT.isNull() && "Can't find 'id' type");
2069 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002070 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002071 assert(!argT.isNull() && "Can't find 'SEL' type");
2072 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002073 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002074 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002075 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002076 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002077 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002078 msgSendIdent, msgSendType,
2079 FunctionDecl::Extern, false, 0);
2080}
2081
2082// SynthMsgSendSuperStretFunctionDecl -
2083// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002084void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002085 IdentifierInfo *msgSendIdent =
2086 &Context->Idents.get("objc_msgSendSuper_stret");
2087 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002088 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002089 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002090 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002091 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2092 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2093 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002094 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002095 assert(!argT.isNull() && "Can't find 'SEL' type");
2096 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002097 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002098 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002099 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002100 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnera98e58d2008-03-15 21:24:04 +00002101 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002102 msgSendIdent, msgSendType,
2103 FunctionDecl::Extern, false, 0);
2104}
2105
Steve Naroff1284db82008-05-08 22:02:18 +00002106// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002107void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002108 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2109 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002110 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002111 assert(!argT.isNull() && "Can't find 'id' type");
2112 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002113 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002114 assert(!argT.isNull() && "Can't find 'SEL' type");
2115 ArgTys.push_back(argT);
Steve Naroff1284db82008-05-08 22:02:18 +00002116 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002117 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002118 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002119 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002120 SourceLocation(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002121 msgSendIdent, msgSendType,
2122 FunctionDecl::Extern, false, 0);
2123}
2124
Steve Naroff09b266e2007-10-30 23:14:51 +00002125// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002126void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002127 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2128 llvm::SmallVector<QualType, 16> ArgTys;
2129 ArgTys.push_back(Context->getPointerType(
2130 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002131 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002132 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002133 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002134 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002135 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002136 getClassIdent, getClassType,
2137 FunctionDecl::Extern, false, 0);
2138}
2139
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002140// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002141void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002142 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2143 llvm::SmallVector<QualType, 16> ArgTys;
2144 ArgTys.push_back(Context->getPointerType(
2145 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002146 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002147 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002148 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002149 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002150 SourceLocation(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002151 getClassIdent, getClassType,
2152 FunctionDecl::Extern, false, 0);
2153}
2154
Steve Naroffb29b4272008-04-14 22:03:09 +00002155Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002156 QualType strType = getConstantStringStructType();
2157
2158 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002159
2160 std::string tmpName = InFileName;
2161 unsigned i;
2162 for (i=0; i < tmpName.length(); i++) {
2163 char c = tmpName.at(i);
2164 // replace any non alphanumeric characters with '_'.
2165 if (!isalpha(c) && (c < '0' || c > '9'))
2166 tmpName[i] = '_';
2167 }
2168 S += tmpName;
2169 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002170 S += utostr(NumObjCStringLiterals++);
2171
Steve Naroffba92b2e2008-03-27 22:29:16 +00002172 Preamble += "static __NSConstantStringImpl " + S;
2173 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2174 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002175 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002176 std::string prettyBufS;
2177 llvm::raw_string_ostream prettyBuf(prettyBufS);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002178 Exp->getString()->printPretty(prettyBuf);
Steve Naroffba92b2e2008-03-27 22:29:16 +00002179 Preamble += prettyBuf.str();
2180 Preamble += ",";
Steve Naroff3652c2d2008-03-15 01:36:04 +00002181 // The minus 2 removes the begin/end double quotes.
Steve Naroffba92b2e2008-03-27 22:29:16 +00002182 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002183
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002184 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Steve Naroff248a7532008-04-15 22:42:06 +00002185 &Context->Idents.get(S.c_str()), strType,
2186 VarDecl::Static, NULL);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002187 DeclRefExpr *DRE = new DeclRefExpr(NewVD, strType, SourceLocation());
2188 Expr *Unop = new UnaryOperator(DRE, UnaryOperator::AddrOf,
2189 Context->getPointerType(DRE->getType()),
2190 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002191 // cast to NSConstantString *
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002192 CastExpr *cast = new CStyleCastExpr(Exp->getType(), Unop,
Douglas Gregor49badde2008-10-27 19:41:14 +00002193 Exp->getType(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002194 ReplaceStmt(Exp, cast);
Steve Naroff96984642007-11-08 14:30:50 +00002195 delete Exp;
2196 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002197}
2198
Steve Naroffb29b4272008-04-14 22:03:09 +00002199ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002200 // check if we are sending a message to 'super'
Steve Naroff54055232008-10-27 17:20:55 +00002201 if (!CurMethodDef || !CurMethodDef->isInstance()) return 0;
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002202
Chris Lattnerd9f69102008-08-10 01:53:14 +00002203 if (PredefinedExpr *PDE = dyn_cast<PredefinedExpr>(recExpr))
2204 if (PDE->getIdentType() == PredefinedExpr::ObjCSuper) {
Chris Lattner0d17f6f2008-06-21 18:04:54 +00002205 const PointerType *PT = PDE->getType()->getAsPointerType();
2206 assert(PT);
2207 ObjCInterfaceType *IT = cast<ObjCInterfaceType>(PT->getPointeeType());
2208 return IT->getDecl();
2209 }
2210 return 0;
Steve Naroff874e2322007-11-15 10:28:18 +00002211}
2212
2213// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002214QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002215 if (!SuperStructDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002216 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002217 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002218 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002219 QualType FieldTypes[2];
2220
2221 // struct objc_object *receiver;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002222 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002223 // struct objc_class *super;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002224 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff874e2322007-11-15 10:28:18 +00002225 // Create fields
2226 FieldDecl *FieldDecls[2];
2227
2228 for (unsigned i = 0; i < 2; ++i)
Chris Lattnerb048c982008-04-06 04:47:34 +00002229 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00002230 FieldTypes[i]);
Steve Naroff874e2322007-11-15 10:28:18 +00002231
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002232 SuperStructDecl->defineBody(*Context, FieldDecls, 4);
Steve Naroff874e2322007-11-15 10:28:18 +00002233 }
2234 return Context->getTagDeclType(SuperStructDecl);
2235}
2236
Steve Naroffb29b4272008-04-14 22:03:09 +00002237QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002238 if (!ConstantStringDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002239 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002240 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002241 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002242 QualType FieldTypes[4];
2243
2244 // struct objc_object *receiver;
2245 FieldTypes[0] = Context->getObjCIdType();
2246 // int flags;
2247 FieldTypes[1] = Context->IntTy;
2248 // char *str;
2249 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2250 // long length;
2251 FieldTypes[3] = Context->LongTy;
2252 // Create fields
Steve Naroff9630ec52008-03-27 22:59:54 +00002253 FieldDecl *FieldDecls[4];
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002254
2255 for (unsigned i = 0; i < 4; ++i)
Chris Lattnerb048c982008-04-06 04:47:34 +00002256 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00002257 FieldTypes[i]);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002258
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002259 ConstantStringDecl->defineBody(*Context, FieldDecls, 4);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002260 }
2261 return Context->getTagDeclType(ConstantStringDecl);
2262}
2263
Steve Naroffb29b4272008-04-14 22:03:09 +00002264Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002265 if (!SelGetUidFunctionDecl)
2266 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002267 if (!MsgSendFunctionDecl)
2268 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002269 if (!MsgSendSuperFunctionDecl)
2270 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002271 if (!MsgSendStretFunctionDecl)
2272 SynthMsgSendStretFunctionDecl();
2273 if (!MsgSendSuperStretFunctionDecl)
2274 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002275 if (!MsgSendFpretFunctionDecl)
2276 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002277 if (!GetClassFunctionDecl)
2278 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002279 if (!GetMetaClassFunctionDecl)
2280 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002281
Steve Naroff874e2322007-11-15 10:28:18 +00002282 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002283 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2284 // May need to use objc_msgSend_stret() as well.
2285 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002286 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002287 QualType resultType = mDecl->getResultType();
Chris Lattner8b51fd72008-07-26 22:36:27 +00002288 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002289 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002290 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002291 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002292 }
Steve Naroff874e2322007-11-15 10:28:18 +00002293
Steve Naroff934f2762007-10-24 22:48:43 +00002294 // Synthesize a call to objc_msgSend().
2295 llvm::SmallVector<Expr*, 8> MsgExprs;
2296 IdentifierInfo *clsName = Exp->getClassName();
2297
2298 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2299 if (clsName) { // class message.
Steve Narofffc93d522008-07-24 19:44:33 +00002300 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2301 // the 'super' idiom within a class method.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002302 if (!strcmp(clsName->getName(), "super")) {
2303 MsgSendFlavor = MsgSendSuperFunctionDecl;
2304 if (MsgSendStretFlavor)
2305 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2306 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2307
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002308 ObjCInterfaceDecl *SuperDecl =
Steve Naroff54055232008-10-27 17:20:55 +00002309 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002310
2311 llvm::SmallVector<Expr*, 4> InitExprs;
2312
2313 // set the receiver to self, the first argument to all methods.
Chris Lattner41110242008-06-17 18:05:57 +00002314 InitExprs.push_back(new DeclRefExpr(
Steve Naroff54055232008-10-27 17:20:55 +00002315 CurMethodDef->getSelfDecl(),
Chris Lattner41110242008-06-17 18:05:57 +00002316 Context->getObjCIdType(),
2317 SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002318 llvm::SmallVector<Expr*, 8> ClsExprs;
2319 QualType argType = Context->getPointerType(Context->CharTy);
2320 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2321 SuperDecl->getIdentifier()->getLength(),
2322 false, argType, SourceLocation(),
2323 SourceLocation()));
2324 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2325 &ClsExprs[0],
2326 ClsExprs.size());
2327 // To turn off a warning, type-cast to 'id'
Douglas Gregor49badde2008-10-27 19:41:14 +00002328 InitExprs.push_back( // set 'super class', using objc_getClass().
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002329 new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002330 Cls, Context->getObjCIdType(),
2331 SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002332 // struct objc_super
2333 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00002334 Expr *SuperRep;
Steve Naroffc0a123c2008-03-11 17:37:02 +00002335
Steve Naroff23f41272008-03-11 18:14:26 +00002336 if (LangOpts.Microsoft) {
2337 SynthSuperContructorFunctionDecl();
2338 // Simulate a contructor call...
2339 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2340 superType, SourceLocation());
2341 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2342 superType, SourceLocation());
2343 } else {
2344 // (struct objc_super) { <exprs from above> }
2345 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2346 &InitExprs[0], InitExprs.size(),
Chris Lattner418f6c72008-10-26 23:43:26 +00002347 SourceLocation(), false);
2348 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE,
2349 false);
Steve Naroff23f41272008-03-11 18:14:26 +00002350 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002351 // struct objc_super *
2352 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2353 Context->getPointerType(SuperRep->getType()),
2354 SourceLocation());
2355 MsgExprs.push_back(Unop);
2356 } else {
2357 llvm::SmallVector<Expr*, 8> ClsExprs;
2358 QualType argType = Context->getPointerType(Context->CharTy);
2359 ClsExprs.push_back(new StringLiteral(clsName->getName(),
2360 clsName->getLength(),
2361 false, argType, SourceLocation(),
2362 SourceLocation()));
2363 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2364 &ClsExprs[0],
2365 ClsExprs.size());
2366 MsgExprs.push_back(Cls);
2367 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002368 } else { // instance message.
2369 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00002370
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002371 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00002372 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002373 if (MsgSendStretFlavor)
2374 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00002375 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2376
2377 llvm::SmallVector<Expr*, 4> InitExprs;
2378
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002379 InitExprs.push_back(
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002380 new CStyleCastExpr(Context->getObjCIdType(),
Steve Naroff54055232008-10-27 17:20:55 +00002381 new DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Narofff616ebb2008-07-16 22:35:27 +00002382 Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002383 SourceLocation()),
2384 Context->getObjCIdType(),
Steve Narofff616ebb2008-07-16 22:35:27 +00002385 SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00002386
2387 llvm::SmallVector<Expr*, 8> ClsExprs;
2388 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002389 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2390 SuperDecl->getIdentifier()->getLength(),
Steve Naroff874e2322007-11-15 10:28:18 +00002391 false, argType, SourceLocation(),
2392 SourceLocation()));
2393 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002394 &ClsExprs[0],
2395 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00002396 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002397 InitExprs.push_back(
Douglas Gregor49badde2008-10-27 19:41:14 +00002398 // set 'super class', using objc_getClass().
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002399 new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002400 Cls, Context->getObjCIdType(), SourceLocation()));
Steve Naroff874e2322007-11-15 10:28:18 +00002401 // struct objc_super
2402 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00002403 Expr *SuperRep;
2404
2405 if (LangOpts.Microsoft) {
2406 SynthSuperContructorFunctionDecl();
2407 // Simulate a contructor call...
2408 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2409 superType, SourceLocation());
2410 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2411 superType, SourceLocation());
2412 } else {
2413 // (struct objc_super) { <exprs from above> }
2414 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2415 &InitExprs[0], InitExprs.size(),
Chris Lattner418f6c72008-10-26 23:43:26 +00002416 SourceLocation(), false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002417 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
2418 }
Steve Naroff874e2322007-11-15 10:28:18 +00002419 // struct objc_super *
2420 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2421 Context->getPointerType(SuperRep->getType()),
2422 SourceLocation());
2423 MsgExprs.push_back(Unop);
2424 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002425 // Remove all type-casts because it may contain objc-style types; e.g.
2426 // Foo<Proto> *.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002427 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002428 recExpr = CE->getSubExpr();
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002429 recExpr = new CStyleCastExpr(Context->getObjCIdType(), recExpr,
Douglas Gregor49badde2008-10-27 19:41:14 +00002430 Context->getObjCIdType(),
2431 SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00002432 MsgExprs.push_back(recExpr);
2433 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002434 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00002435 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002436 llvm::SmallVector<Expr*, 8> SelExprs;
2437 QualType argType = Context->getPointerType(Context->CharTy);
2438 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
2439 Exp->getSelector().getName().size(),
2440 false, argType, SourceLocation(),
2441 SourceLocation()));
2442 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2443 &SelExprs[0], SelExprs.size());
2444 MsgExprs.push_back(SelExp);
2445
2446 // Now push any user supplied arguments.
2447 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002448 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002449 // Make all implicit casts explicit...ICE comes in handy:-)
2450 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2451 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregor49badde2008-10-27 19:41:14 +00002452 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002453 ? Context->getObjCIdType()
Douglas Gregor49badde2008-10-27 19:41:14 +00002454 : ICE->getType();
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002455 userExpr = new CStyleCastExpr(type, userExpr, type, SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002456 }
2457 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002458 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002459 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002460 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002461 userExpr = CE->getSubExpr();
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002462 userExpr = new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002463 userExpr, Context->getObjCIdType(),
2464 SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002465 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00002466 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002467 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00002468 // We've transferred the ownership to MsgExprs. Null out the argument in
2469 // the original expression, since we will delete it below.
2470 Exp->setArg(i, 0);
2471 }
Steve Naroffab972d32007-11-04 22:37:50 +00002472 // Generate the funky cast.
2473 CastExpr *cast;
2474 llvm::SmallVector<QualType, 8> ArgTypes;
2475 QualType returnType;
2476
2477 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002478 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2479 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2480 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002481 ArgTypes.push_back(Context->getObjCIdType());
2482 ArgTypes.push_back(Context->getObjCSelType());
2483 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002484 // Push any user argument types.
Chris Lattner58cce3b2008-03-16 01:07:14 +00002485 for (unsigned i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002486 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
2487 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002488 : mDecl->getParamDecl(i)->getType();
Steve Naroff352336b2007-11-05 14:36:37 +00002489 ArgTypes.push_back(t);
2490 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002491 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
2492 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00002493 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002494 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002495 }
2496 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002497 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00002498
2499 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002500 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
2501 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002502
2503 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2504 // If we don't do this cast, we get the following bizarre warning/note:
2505 // xx.m:13: warning: function called through a non-compatible type
2506 // xx.m:13: note: if this code is reached, the program will abort
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002507 cast = new CStyleCastExpr(Context->getPointerType(Context->VoidTy), DRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002508 Context->getPointerType(Context->VoidTy),
2509 SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00002510
Steve Naroffab972d32007-11-04 22:37:50 +00002511 // Now do the "normal" pointer to function cast.
2512 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002513 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00002514 // If we don't have a method decl, force a variadic cast.
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002515 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Naroffab972d32007-11-04 22:37:50 +00002516 castType = Context->getPointerType(castType);
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002517 cast = new CStyleCastExpr(castType, cast, castType, SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002518
2519 // Don't forget the parens to enforce the proper binding.
2520 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2521
2522 const FunctionType *FT = msgSendType->getAsFunctionType();
2523 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2524 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002525 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002526 if (MsgSendStretFlavor) {
2527 // We have the method which returns a struct/union. Must also generate
2528 // call to objc_msgSend_stret and hang both varieties on a conditional
2529 // expression which dictate which one to envoke depending on size of
2530 // method's return type.
2531
2532 // Create a reference to the objc_msgSend_stret() declaration.
2533 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
2534 SourceLocation());
2535 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002536 cast = new CStyleCastExpr(Context->getPointerType(Context->VoidTy), STDRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002537 Context->getPointerType(Context->VoidTy),
2538 SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002539 // Now do the "normal" pointer to function cast.
2540 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002541 &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002542 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002543 castType = Context->getPointerType(castType);
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002544 cast = new CStyleCastExpr(castType, cast, castType, SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002545
2546 // Don't forget the parens to enforce the proper binding.
2547 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2548
2549 FT = msgSendType->getAsFunctionType();
2550 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2551 FT->getResultType(), SourceLocation());
2552
2553 // Build sizeof(returnType)
2554 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
2555 returnType, Context->getSizeType(),
2556 SourceLocation(), SourceLocation());
2557 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2558 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2559 // For X86 it is more complicated and some kind of target specific routine
2560 // is needed to decide what to do.
Chris Lattner98be4942008-03-05 18:54:05 +00002561 unsigned IntSize =
2562 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002563 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2564 Context->IntTy,
2565 SourceLocation());
2566 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2567 BinaryOperator::LE,
2568 Context->IntTy,
2569 SourceLocation());
2570 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2571 ConditionalOperator *CondExpr =
2572 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002573 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002574 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002575 return ReplacingStmt;
2576}
2577
Steve Naroffb29b4272008-04-14 22:03:09 +00002578Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002579 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff80c28552008-10-27 20:54:44 +00002580
Steve Naroff934f2762007-10-24 22:48:43 +00002581 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002582 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff934f2762007-10-24 22:48:43 +00002583
Chris Lattnere64b7772007-10-24 16:57:36 +00002584 delete Exp;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002585 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002586}
2587
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002588/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2589/// call to objc_getProtocol("proto-name").
Steve Naroffb29b4272008-04-14 22:03:09 +00002590Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002591 if (!GetProtocolFunctionDecl)
2592 SynthGetProtocolFunctionDecl();
2593 // Create a call to objc_getProtocol("ProtocolName").
2594 llvm::SmallVector<Expr*, 8> ProtoExprs;
2595 QualType argType = Context->getPointerType(Context->CharTy);
2596 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
2597 strlen(Exp->getProtocol()->getName()),
2598 false, argType, SourceLocation(),
2599 SourceLocation()));
2600 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2601 &ProtoExprs[0],
2602 ProtoExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002603 ReplaceStmt(Exp, ProtoExp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002604 delete Exp;
2605 return ProtoExp;
2606
2607}
2608
Steve Naroffbaf58c32008-05-31 14:15:04 +00002609bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
2610 const char *endBuf) {
2611 while (startBuf < endBuf) {
2612 if (*startBuf == '#') {
2613 // Skip whitespace.
2614 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2615 ;
2616 if (!strncmp(startBuf, "if", strlen("if")) ||
2617 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2618 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2619 !strncmp(startBuf, "define", strlen("define")) ||
2620 !strncmp(startBuf, "undef", strlen("undef")) ||
2621 !strncmp(startBuf, "else", strlen("else")) ||
2622 !strncmp(startBuf, "elif", strlen("elif")) ||
2623 !strncmp(startBuf, "endif", strlen("endif")) ||
2624 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2625 !strncmp(startBuf, "include", strlen("include")) ||
2626 !strncmp(startBuf, "import", strlen("import")) ||
2627 !strncmp(startBuf, "include_next", strlen("include_next")))
2628 return true;
2629 }
2630 startBuf++;
2631 }
2632 return false;
2633}
2634
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002635/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002636/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00002637void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002638 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002639 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
2640 assert(CDecl->getName() && "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002641 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002642 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002643 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002644 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002645 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00002646 SourceLocation LocStart = CDecl->getLocStart();
2647 SourceLocation LocEnd = CDecl->getLocEnd();
2648
2649 const char *startBuf = SM->getCharacterData(LocStart);
2650 const char *endBuf = SM->getCharacterData(LocEnd);
Steve Naroffbaf58c32008-05-31 14:15:04 +00002651
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002652 // If no ivars and no root or if its root, directly or indirectly,
2653 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002654 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2655 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002656 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattneraadaf782008-01-31 19:51:04 +00002657 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002658 return;
2659 }
2660
2661 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002662 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002663 Result += "\nstruct ";
2664 Result += CDecl->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002665 if (LangOpts.Microsoft)
2666 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00002667
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002668 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002669 const char *cursor = strchr(startBuf, '{');
2670 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002671 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00002672 // If the buffer contains preprocessor directives, we do more fine-grained
2673 // rewrites. This is intended to fix code that looks like (which occurs in
2674 // NSURL.h, for example):
2675 //
2676 // #ifdef XYZ
2677 // @interface Foo : NSObject
2678 // #else
2679 // @interface FooBar : NSObject
2680 // #endif
2681 // {
2682 // int i;
2683 // }
2684 // @end
2685 //
2686 // This clause is segregated to avoid breaking the common case.
2687 if (BufferContainsPPDirectives(startBuf, cursor)) {
2688 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
2689 CDecl->getClassLoc();
2690 const char *endHeader = SM->getCharacterData(L);
2691 endHeader += Lexer::MeasureTokenLength(L, *SM);
2692
Chris Lattner3db6cae2008-07-21 18:19:38 +00002693 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00002694 // advance to the end of the referenced protocols.
2695 while (endHeader < cursor && *endHeader != '>') endHeader++;
2696 endHeader++;
2697 }
2698 // rewrite the original header
2699 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2700 } else {
2701 // rewrite the original header *without* disturbing the '{'
2702 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
2703 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002704 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002705 Result = "\n struct ";
2706 Result += RCDecl->getName();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002707 Result += "_IMPL ";
2708 Result += RCDecl->getName();
Steve Naroff819173c2008-03-12 21:22:52 +00002709 Result += "_IVARS;\n";
Steve Narofffea763e82007-11-14 19:25:57 +00002710
2711 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002712 SourceLocation OnePastCurly =
2713 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2714 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002715 }
2716 cursor++; // past '{'
2717
2718 // Now comment out any visibility specifiers.
2719 while (cursor < endBuf) {
2720 if (*cursor == '@') {
2721 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002722 // Skip whitespace.
2723 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2724 /*scan*/;
2725
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002726 // FIXME: presence of @public, etc. inside comment results in
2727 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002728 if (!strncmp(cursor, "public", strlen("public")) ||
2729 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00002730 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002731 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002732 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002733 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002734 // FIXME: If there are cases where '<' is used in ivar declaration part
2735 // of user code, then scan the ivar list and use needToScanForQualifiers
2736 // for type checking.
2737 else if (*cursor == '<') {
2738 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002739 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002740 cursor = strchr(cursor, '>');
2741 cursor++;
2742 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002743 InsertText(atLoc, " */", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002744 }
Steve Narofffea763e82007-11-14 19:25:57 +00002745 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002746 }
Steve Narofffea763e82007-11-14 19:25:57 +00002747 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002748 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00002749 } else { // we don't have any instance variables - insert super struct.
2750 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2751 Result += " {\n struct ";
2752 Result += RCDecl->getName();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002753 Result += "_IMPL ";
2754 Result += RCDecl->getName();
Steve Naroff819173c2008-03-12 21:22:52 +00002755 Result += "_IVARS;\n};\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00002756 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002757 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002758 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002759 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00002760 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002761}
2762
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002763// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002764/// class methods.
Steve Naroffb29b4272008-04-14 22:03:09 +00002765void RewriteObjC::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002766 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002767 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002768 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002769 const char *ClassName,
2770 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002771 if (MethodBegin == MethodEnd) return;
2772
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002773 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002774 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002775 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002776 SEL _cmd;
2777 char *method_types;
2778 void *_imp;
2779 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002780 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002781 Result += "\nstruct _objc_method {\n";
2782 Result += "\tSEL _cmd;\n";
2783 Result += "\tchar *method_types;\n";
2784 Result += "\tvoid *_imp;\n";
2785 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002786
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002787 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002788 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002789
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002790 // Build _objc_method_list for class's methods if needed
Steve Naroff946a6932008-03-11 00:12:29 +00002791
2792 /* struct {
2793 struct _objc_method_list *next_method;
2794 int method_count;
2795 struct _objc_method method_list[];
2796 }
2797 */
2798 Result += "\nstatic struct {\n";
2799 Result += "\tstruct _objc_method_list *next_method;\n";
2800 Result += "\tint method_count;\n";
2801 Result += "\tstruct _objc_method method_list[";
2802 Result += utostr(MethodEnd-MethodBegin);
2803 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002804 Result += prefix;
2805 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2806 Result += "_METHODS_";
2807 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002808 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002809 Result += IsInstanceMethod ? "inst" : "cls";
2810 Result += "_meth\")))= ";
2811 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002812
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002813 Result += "\t,{{(SEL)\"";
2814 Result += (*MethodBegin)->getSelector().getName().c_str();
2815 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002816 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002817 Result += "\", \"";
2818 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002819 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002820 Result += MethodInternalNames[*MethodBegin];
2821 Result += "}\n";
2822 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2823 Result += "\t ,{(SEL)\"";
2824 Result += (*MethodBegin)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002825 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002826 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002827 Result += "\", \"";
2828 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002829 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002830 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002831 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002832 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002833 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002834}
2835
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002836/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00002837void RewriteObjC::
2838RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
2839 const char *prefix,
2840 const char *ClassName,
2841 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002842 static bool objc_protocol_methods = false;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002843 if (Protocols.empty()) return;
2844
2845 for (unsigned i = 0; i != Protocols.size(); i++) {
2846 ObjCProtocolDecl *PDecl = Protocols[i];
2847 // Output struct protocol_methods holder of method selector and type.
2848 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
2849 /* struct protocol_methods {
2850 SEL _cmd;
2851 char *method_types;
2852 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002853 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002854 Result += "\nstruct protocol_methods {\n";
2855 Result += "\tSEL _cmd;\n";
2856 Result += "\tchar *method_types;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002857 Result += "};\n";
Steve Narofffbfe8252008-05-06 18:26:51 +00002858
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002859 objc_protocol_methods = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002860 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002861 // Do not synthesize the protocol more than once.
2862 if (ObjCSynthesizedProtocols.count(PDecl))
2863 continue;
2864
2865 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2866 unsigned NumMethods = PDecl->getNumInstanceMethods();
2867 /* struct _objc_protocol_method_list {
2868 int protocol_method_count;
2869 struct protocol_methods protocols[];
2870 }
2871 */
2872 Result += "\nstatic struct {\n";
2873 Result += "\tint protocol_method_count;\n";
2874 Result += "\tstruct protocol_methods protocols[";
2875 Result += utostr(NumMethods);
2876 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
2877 Result += PDecl->getName();
2878 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
2879 "{\n\t" + utostr(NumMethods) + "\n";
2880
2881 // Output instance methods declared in this protocol.
2882 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
2883 E = PDecl->instmeth_end(); I != E; ++I) {
2884 if (I == PDecl->instmeth_begin())
2885 Result += "\t ,{{(SEL)\"";
2886 else
2887 Result += "\t ,{(SEL)\"";
2888 Result += (*I)->getSelector().getName().c_str();
2889 std::string MethodTypeString;
2890 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2891 Result += "\", \"";
2892 Result += MethodTypeString;
2893 Result += "\"}\n";
2894 }
2895 Result += "\t }\n};\n";
2896 }
2897
2898 // Output class methods declared in this protocol.
2899 int NumMethods = PDecl->getNumClassMethods();
2900 if (NumMethods > 0) {
2901 /* struct _objc_protocol_method_list {
2902 int protocol_method_count;
2903 struct protocol_methods protocols[];
2904 }
2905 */
2906 Result += "\nstatic struct {\n";
2907 Result += "\tint protocol_method_count;\n";
2908 Result += "\tstruct protocol_methods protocols[";
2909 Result += utostr(NumMethods);
2910 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
2911 Result += PDecl->getName();
2912 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2913 "{\n\t";
2914 Result += utostr(NumMethods);
2915 Result += "\n";
2916
2917 // Output instance methods declared in this protocol.
2918 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
2919 E = PDecl->classmeth_end(); I != E; ++I) {
2920 if (I == PDecl->classmeth_begin())
2921 Result += "\t ,{{(SEL)\"";
2922 else
2923 Result += "\t ,{(SEL)\"";
2924 Result += (*I)->getSelector().getName().c_str();
2925 std::string MethodTypeString;
2926 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2927 Result += "\", \"";
2928 Result += MethodTypeString;
2929 Result += "\"}\n";
2930 }
2931 Result += "\t }\n};\n";
2932 }
2933
2934 // Output:
2935 /* struct _objc_protocol {
2936 // Objective-C 1.0 extensions
2937 struct _objc_protocol_extension *isa;
2938 char *protocol_name;
2939 struct _objc_protocol **protocol_list;
2940 struct _objc_protocol_method_list *instance_methods;
2941 struct _objc_protocol_method_list *class_methods;
2942 };
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002943 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002944 static bool objc_protocol = false;
2945 if (!objc_protocol) {
2946 Result += "\nstruct _objc_protocol {\n";
2947 Result += "\tstruct _objc_protocol_extension *isa;\n";
2948 Result += "\tchar *protocol_name;\n";
2949 Result += "\tstruct _objc_protocol **protocol_list;\n";
2950 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2951 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2952 Result += "};\n";
2953
2954 objc_protocol = true;
2955 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002956
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002957 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2958 Result += PDecl->getName();
2959 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
2960 "{\n\t0, \"";
2961 Result += PDecl->getName();
2962 Result += "\", 0, ";
2963 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2964 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
2965 Result += PDecl->getName();
2966 Result += ", ";
2967 }
2968 else
2969 Result += "0, ";
2970 if (PDecl->getNumClassMethods() > 0) {
2971 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
2972 Result += PDecl->getName();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002973 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002974 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002975 else
2976 Result += "0\n";
2977 Result += "};\n";
2978
2979 // Mark this protocol as having been generated.
2980 if (!ObjCSynthesizedProtocols.insert(PDecl))
2981 assert(false && "protocol already synthesized");
2982 }
2983 // Output the top lovel protocol meta-data for the class.
2984 /* struct _objc_protocol_list {
2985 struct _objc_protocol_list *next;
2986 int protocol_count;
2987 struct _objc_protocol *class_protocols[];
2988 }
2989 */
2990 Result += "\nstatic struct {\n";
2991 Result += "\tstruct _objc_protocol_list *next;\n";
2992 Result += "\tint protocol_count;\n";
2993 Result += "\tstruct _objc_protocol *class_protocols[";
2994 Result += utostr(Protocols.size());
2995 Result += "];\n} _OBJC_";
2996 Result += prefix;
2997 Result += "_PROTOCOLS_";
2998 Result += ClassName;
2999 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3000 "{\n\t0, ";
3001 Result += utostr(Protocols.size());
3002 Result += "\n";
3003
3004 Result += "\t,{&_OBJC_PROTOCOL_";
3005 Result += Protocols[0]->getName();
3006 Result += " \n";
3007
3008 for (unsigned i = 1; i != Protocols.size(); i++) {
3009 Result += "\t ,&_OBJC_PROTOCOL_";
3010 Result += Protocols[i]->getName();
3011 Result += "\n";
3012 }
3013 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003014}
3015
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003016/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003017/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00003018void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003019 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003020 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003021 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003022 ObjCCategoryDecl *CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003023 for (CDecl = ClassDecl->getCategoryList(); CDecl;
3024 CDecl = CDecl->getNextClassCategory())
3025 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3026 break;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003027
Chris Lattnereb44eee2007-12-23 01:40:15 +00003028 std::string FullCategoryName = ClassDecl->getName();
3029 FullCategoryName += '_';
3030 FullCategoryName += IDecl->getName();
3031
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003032 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003033 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003034 true, "CATEGORY_", FullCategoryName.c_str(),
3035 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003036
3037 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003038 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003039 false, "CATEGORY_", FullCategoryName.c_str(),
3040 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003041
3042 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00003043 // Null CDecl is case of a category implementation with no category interface
3044 if (CDecl)
Chris Lattner780f3292008-07-21 21:32:27 +00003045 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Chris Lattnereb44eee2007-12-23 01:40:15 +00003046 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003047
3048 /* struct _objc_category {
3049 char *category_name;
3050 char *class_name;
3051 struct _objc_method_list *instance_methods;
3052 struct _objc_method_list *class_methods;
3053 struct _objc_protocol_list *protocols;
3054 // Objective-C 1.0 extensions
3055 uint32_t size; // sizeof (struct _objc_category)
3056 struct _objc_property_list *instance_properties; // category's own
3057 // @property decl.
3058 };
3059 */
3060
3061 static bool objc_category = false;
3062 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003063 Result += "\nstruct _objc_category {\n";
3064 Result += "\tchar *category_name;\n";
3065 Result += "\tchar *class_name;\n";
3066 Result += "\tstruct _objc_method_list *instance_methods;\n";
3067 Result += "\tstruct _objc_method_list *class_methods;\n";
3068 Result += "\tstruct _objc_protocol_list *protocols;\n";
3069 Result += "\tunsigned int size;\n";
3070 Result += "\tstruct _objc_property_list *instance_properties;\n";
3071 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003072 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003073 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003074 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3075 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003076 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003077 Result += IDecl->getName();
3078 Result += "\"\n\t, \"";
3079 Result += ClassDecl->getName();
3080 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003081
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003082 if (IDecl->getNumInstanceMethods() > 0) {
3083 Result += "\t, (struct _objc_method_list *)"
3084 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3085 Result += FullCategoryName;
3086 Result += "\n";
3087 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003088 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003089 Result += "\t, 0\n";
3090 if (IDecl->getNumClassMethods() > 0) {
3091 Result += "\t, (struct _objc_method_list *)"
3092 "&_OBJC_CATEGORY_CLASS_METHODS_";
3093 Result += FullCategoryName;
3094 Result += "\n";
3095 }
3096 else
3097 Result += "\t, 0\n";
3098
Chris Lattner780f3292008-07-21 21:32:27 +00003099 if (CDecl && !CDecl->getReferencedProtocols().empty()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003100 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
3101 Result += FullCategoryName;
3102 Result += "\n";
3103 }
3104 else
3105 Result += "\t, 0\n";
3106 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003107}
3108
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003109/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3110/// ivar offset.
Steve Naroffb29b4272008-04-14 22:03:09 +00003111void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003112 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003113 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00003114 if (ivar->isBitField()) {
3115 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3116 // place all bitfields at offset 0.
3117 Result += "0";
3118 } else {
3119 Result += "__OFFSETOFIVAR__(struct ";
3120 Result += IDecl->getName();
3121 if (LangOpts.Microsoft)
3122 Result += "_IMPL";
3123 Result += ", ";
3124 Result += ivar->getName();
3125 Result += ")";
3126 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003127}
3128
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003129//===----------------------------------------------------------------------===//
3130// Meta Data Emission
3131//===----------------------------------------------------------------------===//
3132
Steve Naroffb29b4272008-04-14 22:03:09 +00003133void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003134 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003135 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003136
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003137 // Explictly declared @interface's are already synthesized.
3138 if (CDecl->ImplicitInterfaceDecl()) {
3139 // FIXME: Implementation of a class with no @interface (legacy) doese not
3140 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003141 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003142 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003143
Chris Lattnerbe6df082007-12-12 07:56:42 +00003144 // Build _objc_ivar_list metadata for classes ivars if needed
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003145 unsigned NumIvars = !IDecl->ivar_empty()
3146 ? IDecl->ivar_size()
3147 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003148 if (NumIvars > 0) {
3149 static bool objc_ivar = false;
3150 if (!objc_ivar) {
3151 /* struct _objc_ivar {
3152 char *ivar_name;
3153 char *ivar_type;
3154 int ivar_offset;
3155 };
3156 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003157 Result += "\nstruct _objc_ivar {\n";
3158 Result += "\tchar *ivar_name;\n";
3159 Result += "\tchar *ivar_type;\n";
3160 Result += "\tint ivar_offset;\n";
3161 Result += "};\n";
3162
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003163 objc_ivar = true;
3164 }
3165
Steve Naroff946a6932008-03-11 00:12:29 +00003166 /* struct {
3167 int ivar_count;
3168 struct _objc_ivar ivar_list[nIvars];
3169 };
3170 */
3171 Result += "\nstatic struct {\n";
3172 Result += "\tint ivar_count;\n";
3173 Result += "\tstruct _objc_ivar ivar_list[";
3174 Result += utostr(NumIvars);
3175 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003176 Result += IDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00003177 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003178 "{\n\t";
3179 Result += utostr(NumIvars);
3180 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003181
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003182 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003183 if (!IDecl->ivar_empty()) {
Chris Lattnerbe6df082007-12-12 07:56:42 +00003184 IVI = IDecl->ivar_begin();
3185 IVE = IDecl->ivar_end();
3186 } else {
3187 IVI = CDecl->ivar_begin();
3188 IVE = CDecl->ivar_end();
3189 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003190 Result += "\t,{{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003191 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003192 Result += "\", \"";
3193 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003194 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003195 Result += StrEncoding;
3196 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003197 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003198 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003199 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003200 Result += "\t ,{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003201 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003202 Result += "\", \"";
3203 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003204 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003205 Result += StrEncoding;
3206 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003207 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003208 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003209 }
3210
3211 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003212 }
3213
3214 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003215 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003216 true, "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003217
3218 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003219 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003220 false, "", IDecl->getName(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003221
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003222 // Protocols referenced in class declaration?
Chris Lattner780f3292008-07-21 21:32:27 +00003223 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003224 "CLASS", CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003225
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003226
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003227 // Declaration of class/meta-class metadata
3228 /* struct _objc_class {
3229 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003230 const char *super_class_name;
3231 char *name;
3232 long version;
3233 long info;
3234 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003235 struct _objc_ivar_list *ivars;
3236 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003237 struct objc_cache *cache;
3238 struct objc_protocol_list *protocols;
3239 const char *ivar_layout;
3240 struct _objc_class_ext *ext;
3241 };
3242 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003243 static bool objc_class = false;
3244 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003245 Result += "\nstruct _objc_class {\n";
3246 Result += "\tstruct _objc_class *isa;\n";
3247 Result += "\tconst char *super_class_name;\n";
3248 Result += "\tchar *name;\n";
3249 Result += "\tlong version;\n";
3250 Result += "\tlong info;\n";
3251 Result += "\tlong instance_size;\n";
3252 Result += "\tstruct _objc_ivar_list *ivars;\n";
3253 Result += "\tstruct _objc_method_list *methods;\n";
3254 Result += "\tstruct objc_cache *cache;\n";
3255 Result += "\tstruct _objc_protocol_list *protocols;\n";
3256 Result += "\tconst char *ivar_layout;\n";
3257 Result += "\tstruct _objc_class_ext *ext;\n";
3258 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003259 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003260 }
3261
3262 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003263 ObjCInterfaceDecl *RootClass = 0;
3264 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003265 while (SuperClass) {
3266 RootClass = SuperClass;
3267 SuperClass = SuperClass->getSuperClass();
3268 }
3269 SuperClass = CDecl->getSuperClass();
3270
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003271 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
3272 Result += CDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00003273 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003274 "{\n\t(struct _objc_class *)\"";
3275 Result += (RootClass ? RootClass->getName() : CDecl->getName());
3276 Result += "\"";
3277
3278 if (SuperClass) {
3279 Result += ", \"";
3280 Result += SuperClass->getName();
3281 Result += "\", \"";
3282 Result += CDecl->getName();
3283 Result += "\"";
3284 }
3285 else {
3286 Result += ", 0, \"";
3287 Result += CDecl->getName();
3288 Result += "\"";
3289 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003290 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003291 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003292 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffb26d7132007-12-05 21:49:40 +00003293 if (IDecl->getNumClassMethods() > 0) {
Steve Naroff23f41272008-03-11 18:14:26 +00003294 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Steve Naroffb26d7132007-12-05 21:49:40 +00003295 Result += IDecl->getName();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003296 Result += "\n";
3297 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003298 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003299 Result += ", 0\n";
Chris Lattner3db6cae2008-07-21 18:19:38 +00003300 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003301 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003302 Result += CDecl->getName();
3303 Result += ",0,0\n";
3304 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003305 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003306 Result += "\t,0,0,0,0\n";
3307 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003308
3309 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003310 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
3311 Result += CDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00003312 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003313 "{\n\t&_OBJC_METACLASS_";
3314 Result += CDecl->getName();
3315 if (SuperClass) {
3316 Result += ", \"";
3317 Result += SuperClass->getName();
3318 Result += "\", \"";
3319 Result += CDecl->getName();
3320 Result += "\"";
3321 }
3322 else {
3323 Result += ", 0, \"";
3324 Result += CDecl->getName();
3325 Result += "\"";
3326 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003327 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003328 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003329 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003330 Result += ",0";
3331 else {
3332 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003333 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003334 Result += CDecl->getName();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003335 if (LangOpts.Microsoft)
3336 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003337 Result += ")";
3338 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003339 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00003340 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003341 Result += CDecl->getName();
3342 Result += "\n\t";
3343 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003344 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003345 Result += ",0";
3346 if (IDecl->getNumInstanceMethods() > 0) {
Steve Naroff946a6932008-03-11 00:12:29 +00003347 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003348 Result += CDecl->getName();
3349 Result += ", 0\n\t";
3350 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003351 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003352 Result += ",0,0";
Chris Lattner3db6cae2008-07-21 18:19:38 +00003353 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003354 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003355 Result += CDecl->getName();
3356 Result += ", 0,0\n";
3357 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003358 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003359 Result += ",0,0,0\n";
3360 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003361}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003362
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003363/// RewriteImplementations - This routine rewrites all method implementations
3364/// and emits meta-data.
3365
Steve Naroffb29b4272008-04-14 22:03:09 +00003366void RewriteObjC::RewriteImplementations(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003367 int ClsDefCount = ClassImplementation.size();
3368 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003369
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003370 if (ClsDefCount == 0 && CatDefCount == 0)
3371 return;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003372 // Rewrite implemented methods
3373 for (int i = 0; i < ClsDefCount; i++)
3374 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003375
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003376 for (int i = 0; i < CatDefCount; i++)
3377 RewriteImplementationDecl(CategoryImplementation[i]);
3378
Steve Naroff5df5b762008-05-07 21:23:49 +00003379 // This is needed for determining instance variable offsets.
Steve Naroffa11440b2008-08-05 18:47:23 +00003380 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003381 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003382 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003383 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003384
3385 // For each implemented category, write out all its meta data.
3386 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003387 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003388
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003389 // Write objc_symtab metadata
3390 /*
3391 struct _objc_symtab
3392 {
3393 long sel_ref_cnt;
3394 SEL *refs;
3395 short cls_def_cnt;
3396 short cat_def_cnt;
3397 void *defs[cls_def_cnt + cat_def_cnt];
3398 };
3399 */
3400
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003401 Result += "\nstruct _objc_symtab {\n";
3402 Result += "\tlong sel_ref_cnt;\n";
3403 Result += "\tSEL *refs;\n";
3404 Result += "\tshort cls_def_cnt;\n";
3405 Result += "\tshort cat_def_cnt;\n";
3406 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3407 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003408
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003409 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00003410 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003411 Result += "\t0, 0, " + utostr(ClsDefCount)
3412 + ", " + utostr(CatDefCount) + "\n";
3413 for (int i = 0; i < ClsDefCount; i++) {
3414 Result += "\t,&_OBJC_CLASS_";
3415 Result += ClassImplementation[i]->getName();
3416 Result += "\n";
3417 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003418
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003419 for (int i = 0; i < CatDefCount; i++) {
3420 Result += "\t,&_OBJC_CATEGORY_";
3421 Result += CategoryImplementation[i]->getClassInterface()->getName();
3422 Result += "_";
3423 Result += CategoryImplementation[i]->getName();
3424 Result += "\n";
3425 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003426
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003427 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003428
3429 // Write objc_module metadata
3430
3431 /*
3432 struct _objc_module {
3433 long version;
3434 long size;
3435 const char *name;
3436 struct _objc_symtab *symtab;
3437 }
3438 */
3439
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003440 Result += "\nstruct _objc_module {\n";
3441 Result += "\tlong version;\n";
3442 Result += "\tlong size;\n";
3443 Result += "\tconst char *name;\n";
3444 Result += "\tstruct _objc_symtab *symtab;\n";
3445 Result += "};\n\n";
3446 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00003447 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003448 Result += "\t" + utostr(OBJC_ABI_VERSION) +
3449 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003450 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003451
3452 if (LangOpts.Microsoft) {
3453 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00003454 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003455 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3456 Result += "&_OBJC_MODULES;\n";
3457 Result += "#pragma data_seg(pop)\n\n";
3458 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003459}
Chris Lattner311ff022007-10-16 22:36:42 +00003460
Steve Naroff54055232008-10-27 17:20:55 +00003461std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3462 const char *funcName,
3463 std::string Tag) {
3464 const FunctionType *AFT = CE->getFunctionType();
3465 QualType RT = AFT->getResultType();
3466 std::string StructRef = "struct " + Tag;
3467 std::string S = "static " + RT.getAsString() + " __" +
3468 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003469
Steve Naroff54055232008-10-27 17:20:55 +00003470 BlockDecl *BD = CE->getBlockDecl();
3471
3472 if (isa<FunctionTypeNoProto>(AFT)) {
3473 S += "()";
3474 } else if (BD->param_empty()) {
3475 S += "(" + StructRef + " *__cself)";
3476 } else {
3477 const FunctionTypeProto *FT = cast<FunctionTypeProto>(AFT);
3478 assert(FT && "SynthesizeBlockFunc: No function proto");
3479 S += '(';
3480 // first add the implicit argument.
3481 S += StructRef + " *__cself, ";
3482 std::string ParamStr;
3483 for (BlockDecl::param_iterator AI = BD->param_begin(),
3484 E = BD->param_end(); AI != E; ++AI) {
3485 if (AI != BD->param_begin()) S += ", ";
3486 ParamStr = (*AI)->getName();
3487 (*AI)->getType().getAsStringInternal(ParamStr);
3488 S += ParamStr;
3489 }
3490 if (FT->isVariadic()) {
3491 if (!BD->param_empty()) S += ", ";
3492 S += "...";
3493 }
3494 S += ')';
3495 }
3496 S += " {\n";
3497
3498 // Create local declarations to avoid rewriting all closure decl ref exprs.
3499 // First, emit a declaration for all "by ref" decls.
3500 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3501 E = BlockByRefDecls.end(); I != E; ++I) {
3502 S += " ";
3503 std::string Name = (*I)->getName();
3504 Context->getPointerType((*I)->getType()).getAsStringInternal(Name);
3505 S += Name + " = __cself->" + (*I)->getName() + "; // bound by ref\n";
3506 }
3507 // Next, emit a declaration for all "by copy" declarations.
3508 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3509 E = BlockByCopyDecls.end(); I != E; ++I) {
3510 S += " ";
3511 std::string Name = (*I)->getName();
3512 // Handle nested closure invocation. For example:
3513 //
3514 // void (^myImportedClosure)(void);
3515 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3516 //
3517 // void (^anotherClosure)(void);
3518 // anotherClosure = ^(void) {
3519 // myImportedClosure(); // import and invoke the closure
3520 // };
3521 //
3522 if (isBlockPointerType((*I)->getType()))
3523 S += "struct __block_impl *";
3524 else
3525 (*I)->getType().getAsStringInternal(Name);
3526 S += Name + " = __cself->" + (*I)->getName() + "; // bound by copy\n";
3527 }
3528 std::string RewrittenStr = RewrittenBlockExprs[CE];
3529 const char *cstr = RewrittenStr.c_str();
3530 while (*cstr++ != '{') ;
3531 S += cstr;
3532 S += "\n";
3533 return S;
3534}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003535
Steve Naroff54055232008-10-27 17:20:55 +00003536std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3537 const char *funcName,
3538 std::string Tag) {
3539 std::string StructRef = "struct " + Tag;
3540 std::string S = "static void __";
3541
3542 S += funcName;
3543 S += "_block_copy_" + utostr(i);
3544 S += "(" + StructRef;
3545 S += "*dst, " + StructRef;
3546 S += "*src) {";
3547 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3548 E = ImportedBlockDecls.end(); I != E; ++I) {
3549 S += "_Block_copy_assign(&dst->";
3550 S += (*I)->getName();
3551 S += ", src->";
3552 S += (*I)->getName();
3553 S += ");}";
3554 }
3555 S += "\nstatic void __";
3556 S += funcName;
3557 S += "_block_dispose_" + utostr(i);
3558 S += "(" + StructRef;
3559 S += "*src) {";
3560 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3561 E = ImportedBlockDecls.end(); I != E; ++I) {
3562 S += "_Block_destroy(src->";
3563 S += (*I)->getName();
3564 S += ");";
3565 }
3566 S += "}\n";
3567 return S;
3568}
3569
3570std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3571 bool hasCopyDisposeHelpers) {
3572 std::string S = "struct " + Tag;
3573 std::string Constructor = " " + Tag;
3574
3575 S += " {\n struct __block_impl impl;\n";
3576
3577 if (hasCopyDisposeHelpers)
3578 S += " void *copy;\n void *dispose;\n";
3579
3580 Constructor += "(void *fp";
3581
3582 if (hasCopyDisposeHelpers)
3583 Constructor += ", void *copyHelp, void *disposeHelp";
3584
3585 if (BlockDeclRefs.size()) {
3586 // Output all "by copy" declarations.
3587 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3588 E = BlockByCopyDecls.end(); I != E; ++I) {
3589 S += " ";
3590 std::string FieldName = (*I)->getName();
3591 std::string ArgName = "_" + FieldName;
3592 // Handle nested closure invocation. For example:
3593 //
3594 // void (^myImportedBlock)(void);
3595 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3596 //
3597 // void (^anotherBlock)(void);
3598 // anotherBlock = ^(void) {
3599 // myImportedBlock(); // import and invoke the closure
3600 // };
3601 //
3602 if (isBlockPointerType((*I)->getType())) {
3603 S += "struct __block_impl *";
3604 Constructor += ", void *" + ArgName;
3605 } else {
3606 (*I)->getType().getAsStringInternal(FieldName);
3607 (*I)->getType().getAsStringInternal(ArgName);
3608 Constructor += ", " + ArgName;
3609 }
3610 S += FieldName + ";\n";
3611 }
3612 // Output all "by ref" declarations.
3613 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3614 E = BlockByRefDecls.end(); I != E; ++I) {
3615 S += " ";
3616 std::string FieldName = (*I)->getName();
3617 std::string ArgName = "_" + FieldName;
3618 // Handle nested closure invocation. For example:
3619 //
3620 // void (^myImportedBlock)(void);
3621 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3622 //
3623 // void (^anotherBlock)(void);
3624 // anotherBlock = ^(void) {
3625 // myImportedBlock(); // import and invoke the closure
3626 // };
3627 //
3628 if (isBlockPointerType((*I)->getType())) {
3629 S += "struct __block_impl *";
3630 Constructor += ", void *" + ArgName;
3631 } else {
3632 Context->getPointerType((*I)->getType()).getAsStringInternal(FieldName);
3633 Context->getPointerType((*I)->getType()).getAsStringInternal(ArgName);
3634 Constructor += ", " + ArgName;
3635 }
3636 S += FieldName + "; // by ref\n";
3637 }
3638 // Finish writing the constructor.
3639 // FIXME: handle NSConcreteGlobalBlock.
3640 Constructor += ", int flags=0) {\n";
3641 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3642 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3643
3644 if (hasCopyDisposeHelpers)
3645 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3646
3647 // Initialize all "by copy" arguments.
3648 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3649 E = BlockByCopyDecls.end(); I != E; ++I) {
3650 std::string Name = (*I)->getName();
3651 Constructor += " ";
3652 if (isBlockPointerType((*I)->getType()))
3653 Constructor += Name + " = (struct __block_impl *)_";
3654 else
3655 Constructor += Name + " = _";
3656 Constructor += Name + ";\n";
3657 }
3658 // Initialize all "by ref" arguments.
3659 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3660 E = BlockByRefDecls.end(); I != E; ++I) {
3661 std::string Name = (*I)->getName();
3662 Constructor += " ";
3663 if (isBlockPointerType((*I)->getType()))
3664 Constructor += Name + " = (struct __block_impl *)_";
3665 else
3666 Constructor += Name + " = _";
3667 Constructor += Name + ";\n";
3668 }
3669 } else {
3670 // Finish writing the constructor.
3671 // FIXME: handle NSConcreteGlobalBlock.
3672 Constructor += ", int flags=0) {\n";
3673 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3674 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3675 if (hasCopyDisposeHelpers)
3676 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3677 }
3678 Constructor += " ";
3679 Constructor += "}\n";
3680 S += Constructor;
3681 S += "};\n";
3682 return S;
3683}
3684
3685void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3686 const char *FunName) {
3687 // Insert closures that were part of the function.
3688 for (unsigned i = 0; i < Blocks.size(); i++) {
3689
3690 CollectBlockDeclRefInfo(Blocks[i]);
3691
3692 std::string Tag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
3693
3694 std::string CI = SynthesizeBlockImpl(Blocks[i], Tag,
3695 ImportedBlockDecls.size() > 0);
3696
3697 InsertText(FunLocStart, CI.c_str(), CI.size());
3698
3699 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, Tag);
3700
3701 InsertText(FunLocStart, CF.c_str(), CF.size());
3702
3703 if (ImportedBlockDecls.size()) {
3704 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, Tag);
3705 InsertText(FunLocStart, HF.c_str(), HF.size());
3706 }
3707
3708 BlockDeclRefs.clear();
3709 BlockByRefDecls.clear();
3710 BlockByCopyDecls.clear();
3711 BlockCallExprs.clear();
3712 ImportedBlockDecls.clear();
3713 }
3714 Blocks.clear();
3715 RewrittenBlockExprs.clear();
3716}
3717
3718void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3719 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
3720 const char *FuncName = FD->getName();
3721
3722 SynthesizeBlockLiterals(FunLocStart, FuncName);
3723}
3724
3725void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
3726 SourceLocation FunLocStart = MD->getLocStart();
3727 std::string FuncName = std::string(MD->getSelector().getName());
3728 // Convert colons to underscores.
3729 std::string::size_type loc = 0;
3730 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3731 FuncName.replace(loc, 1, "_");
3732
3733 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
3734}
3735
3736void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
3737 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3738 CI != E; ++CI)
3739 if (*CI) {
3740 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3741 GetBlockDeclRefExprs(CBE->getBody());
3742 else
3743 GetBlockDeclRefExprs(*CI);
3744 }
3745 // Handle specific things.
3746 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
3747 // FIXME: Handle enums.
3748 if (!isa<FunctionDecl>(CDRE->getDecl()))
3749 BlockDeclRefs.push_back(CDRE);
3750 return;
3751}
3752
3753void RewriteObjC::GetBlockCallExprs(Stmt *S) {
3754 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3755 CI != E; ++CI)
3756 if (*CI) {
3757 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3758 GetBlockCallExprs(CBE->getBody());
3759 else
3760 GetBlockCallExprs(*CI);
3761 }
3762
3763 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
3764 if (CE->getCallee()->getType()->isBlockPointerType()) {
3765 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
3766 }
3767 }
3768 return;
3769}
3770
3771std::string RewriteObjC::SynthesizeBlockCall(CallExpr *Exp) {
3772 // Navigate to relevant type information.
3773 const char *closureName = 0;
3774 const BlockPointerType *CPT = 0;
3775
3776 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp->getCallee())) {
3777 closureName = DRE->getDecl()->getName();
3778 CPT = DRE->getType()->getAsBlockPointerType();
3779 } else if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(Exp->getCallee())) {
3780 closureName = CDRE->getDecl()->getName();
3781 CPT = CDRE->getType()->getAsBlockPointerType();
3782 } else if (MemberExpr *MExpr = dyn_cast<MemberExpr>(Exp->getCallee())) {
3783 closureName = MExpr->getMemberDecl()->getName();
3784 CPT = MExpr->getType()->getAsBlockPointerType();
3785 } else {
3786 assert(1 && "RewriteBlockClass: Bad type");
3787 }
3788 assert(CPT && "RewriteBlockClass: Bad type");
3789 const FunctionType *FT = CPT->getPointeeType()->getAsFunctionType();
3790 assert(FT && "RewriteBlockClass: Bad type");
3791 const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(FT);
3792 // FTP will be null for closures that don't take arguments.
3793
3794 // Build a closure call - start with a paren expr to enforce precedence.
3795 std::string BlockCall = "(";
3796
3797 // Synthesize the cast.
3798 BlockCall += "(" + Exp->getType().getAsString() + "(*)";
3799 BlockCall += "(struct __block_impl *";
3800 if (FTP) {
3801 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
3802 E = FTP->arg_type_end(); I && (I != E); ++I)
3803 BlockCall += ", " + (*I).getAsString();
3804 }
3805 BlockCall += "))"; // close the argument list and paren expression.
3806
3807 // Invoke the closure. We need to cast it since the declaration type is
3808 // bogus (it's a function pointer type)
3809 BlockCall += "((struct __block_impl *)";
3810 std::string closureExprBufStr;
3811 llvm::raw_string_ostream closureExprBuf(closureExprBufStr);
3812 Exp->getCallee()->printPretty(closureExprBuf);
3813 BlockCall += closureExprBuf.str();
3814 BlockCall += ")->FuncPtr)";
3815
3816 // Add the arguments.
3817 BlockCall += "((struct __block_impl *)";
3818 BlockCall += closureExprBuf.str();
3819 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3820 E = Exp->arg_end(); I != E; ++I) {
3821 std::string syncExprBufS;
3822 llvm::raw_string_ostream Buf(syncExprBufS);
3823 (*I)->printPretty(Buf);
3824 BlockCall += ", " + Buf.str();
3825 }
3826 return BlockCall;
3827}
3828
3829void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
3830 std::string BlockCall = SynthesizeBlockCall(Exp);
3831
3832 const char *startBuf = SM->getCharacterData(Exp->getLocStart());
3833 const char *endBuf = SM->getCharacterData(Exp->getLocEnd());
3834
3835 ReplaceText(Exp->getLocStart(), endBuf-startBuf,
3836 BlockCall.c_str(), BlockCall.size());
3837}
3838
3839void RewriteObjC::RewriteBlockDeclRefExpr(BlockDeclRefExpr *BDRE) {
3840 // FIXME: Add more elaborate code generation required by the ABI.
3841 InsertText(BDRE->getLocStart(), "*", 1);
3842}
3843
3844void RewriteObjC::RewriteCastExpr(CastExpr *CE) {
3845 SourceLocation LocStart = CE->getLocStart();
3846 SourceLocation LocEnd = CE->getLocEnd();
3847
3848 const char *startBuf = SM->getCharacterData(LocStart);
3849 const char *endBuf = SM->getCharacterData(LocEnd);
3850
3851 // advance the location to startArgList.
3852 const char *argPtr = startBuf;
3853
3854 while (*argPtr++ && (argPtr < endBuf)) {
3855 switch (*argPtr) {
3856 case '^':
3857 // Replace the '^' with '*'.
3858 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
3859 ReplaceText(LocStart, 1, "*", 1);
3860 break;
3861 }
3862 }
3863 return;
3864}
3865
3866void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
3867 SourceLocation DeclLoc = FD->getLocation();
3868 unsigned parenCount = 0;
3869
3870 // We have 1 or more arguments that have closure pointers.
3871 const char *startBuf = SM->getCharacterData(DeclLoc);
3872 const char *startArgList = strchr(startBuf, '(');
3873
3874 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
3875
3876 parenCount++;
3877 // advance the location to startArgList.
3878 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
3879 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
3880
3881 const char *argPtr = startArgList;
3882
3883 while (*argPtr++ && parenCount) {
3884 switch (*argPtr) {
3885 case '^':
3886 // Replace the '^' with '*'.
3887 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
3888 ReplaceText(DeclLoc, 1, "*", 1);
3889 break;
3890 case '(':
3891 parenCount++;
3892 break;
3893 case ')':
3894 parenCount--;
3895 break;
3896 }
3897 }
3898 return;
3899}
3900
3901bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
3902 const FunctionTypeProto *FTP;
3903 const PointerType *PT = QT->getAsPointerType();
3904 if (PT) {
3905 FTP = PT->getPointeeType()->getAsFunctionTypeProto();
3906 } else {
3907 const BlockPointerType *BPT = QT->getAsBlockPointerType();
3908 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
3909 FTP = BPT->getPointeeType()->getAsFunctionTypeProto();
3910 }
3911 if (FTP) {
3912 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
3913 E = FTP->arg_type_end(); I != E; ++I)
3914 if (isBlockPointerType(*I))
3915 return true;
3916 }
3917 return false;
3918}
3919
3920void RewriteObjC::GetExtentOfArgList(const char *Name,
3921 const char *&LParen, const char *&RParen) {
3922 const char *argPtr = strchr(Name, '(');
3923 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
3924
3925 LParen = argPtr; // output the start.
3926 argPtr++; // skip past the left paren.
3927 unsigned parenCount = 1;
3928
3929 while (*argPtr && parenCount) {
3930 switch (*argPtr) {
3931 case '(': parenCount++; break;
3932 case ')': parenCount--; break;
3933 default: break;
3934 }
3935 if (parenCount) argPtr++;
3936 }
3937 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
3938 RParen = argPtr; // output the end
3939}
3940
3941void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
3942 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3943 RewriteBlockPointerFunctionArgs(FD);
3944 return;
3945 }
3946 // Handle Variables and Typedefs.
3947 SourceLocation DeclLoc = ND->getLocation();
3948 QualType DeclT;
3949 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3950 DeclT = VD->getType();
3951 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
3952 DeclT = TDD->getUnderlyingType();
3953 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
3954 DeclT = FD->getType();
3955 else
3956 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
3957
3958 const char *startBuf = SM->getCharacterData(DeclLoc);
3959 const char *endBuf = startBuf;
3960 // scan backward (from the decl location) for the end of the previous decl.
3961 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
3962 startBuf--;
3963
3964 // *startBuf != '^' if we are dealing with a pointer to function that
3965 // may take block argument types (which will be handled below).
3966 if (*startBuf == '^') {
3967 // Replace the '^' with '*', computing a negative offset.
3968 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
3969 ReplaceText(DeclLoc, 1, "*", 1);
3970 }
3971 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
3972 // Replace the '^' with '*' for arguments.
3973 DeclLoc = ND->getLocation();
3974 startBuf = SM->getCharacterData(DeclLoc);
3975 const char *argListBegin, *argListEnd;
3976 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
3977 while (argListBegin < argListEnd) {
3978 if (*argListBegin == '^') {
3979 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
3980 ReplaceText(CaretLoc, 1, "*", 1);
3981 }
3982 argListBegin++;
3983 }
3984 }
3985 return;
3986}
3987
3988void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
3989 // Add initializers for any closure decl refs.
3990 GetBlockDeclRefExprs(Exp->getBody());
3991 if (BlockDeclRefs.size()) {
3992 // Unique all "by copy" declarations.
3993 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3994 if (!BlockDeclRefs[i]->isByRef())
3995 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
3996 // Unique all "by ref" declarations.
3997 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3998 if (BlockDeclRefs[i]->isByRef()) {
3999 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
4000 }
4001 // Find any imported blocks...they will need special attention.
4002 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4003 if (isBlockPointerType(BlockDeclRefs[i]->getType())) {
4004 GetBlockCallExprs(Blocks[i]);
4005 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4006 }
4007 }
4008}
4009
4010std::string RewriteObjC::SynthesizeBlockInitExpr(BlockExpr *Exp, VarDecl *VD) {
4011 Blocks.push_back(Exp);
4012
4013 CollectBlockDeclRefInfo(Exp);
4014 std::string FuncName;
4015
4016 if (CurFunctionDef)
4017 FuncName = std::string(CurFunctionDef->getName());
4018 else if (CurMethodDef) {
4019 FuncName = std::string(CurMethodDef->getSelector().getName());
4020 // Convert colons to underscores.
4021 std::string::size_type loc = 0;
4022 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4023 FuncName.replace(loc, 1, "_");
4024 } else if (VD)
4025 FuncName = std::string(VD->getName());
4026
4027 std::string BlockNumber = utostr(Blocks.size()-1);
4028
4029 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4030 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
4031
4032 std::string FunkTypeStr;
4033
4034 // Get a pointer to the function type so we can cast appropriately.
4035 Context->getPointerType(QualType(Exp->getFunctionType(),0)).getAsStringInternal(FunkTypeStr);
4036
4037 // Rewrite the closure block with a compound literal. The first cast is
4038 // to prevent warnings from the C compiler.
4039 std::string Init = "(" + FunkTypeStr;
4040
4041 Init += ")&" + Tag;
4042
4043 // Initialize the block function.
4044 Init += "((void*)" + Func;
4045
4046 if (ImportedBlockDecls.size()) {
4047 std::string Buf = "__" + FuncName + "_block_copy_" + BlockNumber;
4048 Init += ",(void*)" + Buf;
4049 Buf = "__" + FuncName + "_block_dispose_" + BlockNumber;
4050 Init += ",(void*)" + Buf;
4051 }
4052 // Add initializers for any closure decl refs.
4053 if (BlockDeclRefs.size()) {
4054 // Output all "by copy" declarations.
4055 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4056 E = BlockByCopyDecls.end(); I != E; ++I) {
4057 Init += ",";
4058 if (isObjCType((*I)->getType())) {
4059 Init += "[[";
4060 Init += (*I)->getName();
4061 Init += " retain] autorelease]";
4062 } else if (isBlockPointerType((*I)->getType())) {
4063 Init += "(void *)";
4064 Init += (*I)->getName();
4065 } else {
4066 Init += (*I)->getName();
4067 }
4068 }
4069 // Output all "by ref" declarations.
4070 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4071 E = BlockByRefDecls.end(); I != E; ++I) {
4072 Init += ",&";
4073 Init += (*I)->getName();
4074 }
4075 }
4076 Init += ")";
4077 BlockDeclRefs.clear();
4078 BlockByRefDecls.clear();
4079 BlockByCopyDecls.clear();
4080 ImportedBlockDecls.clear();
4081
4082 return Init;
4083}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00004084