blob: 69aedcc2dd85962dd179fd935de4150c03e5efcb [file] [log] [blame]
Steve Naroffb29b4272008-04-14 22:03:09 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
Chris Lattner77cd2a02007-10-11 00:43:27 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner77cd2a02007-10-11 00:43:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
14#include "ASTConsumers.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Ted Kremeneke3a61982008-05-31 20:11:04 +000018#include "clang/AST/TranslationUnit.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000019#include "clang/Basic/SourceManager.h"
Steve Naroffebf2b562007-10-23 23:50:29 +000020#include "clang/Basic/IdentifierTable.h"
Chris Lattner07506182007-11-30 22:53:43 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattner26de4652007-12-02 01:13:47 +000022#include "clang/Lex/Lexer.h"
Chris Lattner158ecb92007-10-25 17:07:24 +000023#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000024#include "llvm/ADT/SmallPtrSet.h"
Ted Kremeneka95d3752008-09-13 05:16:45 +000025#include "llvm/ADT/OwningPtr.h"
Chris Lattner26de4652007-12-02 01:13:47 +000026#include "llvm/Support/MemoryBuffer.h"
Steve Naroff0113c9d2008-01-28 21:34:52 +000027#include "llvm/Support/CommandLine.h"
Dan Gohman63e2dcc2008-05-21 20:19:16 +000028#include "llvm/Support/Streams.h"
Ted Kremeneka95d3752008-09-13 05:16:45 +000029#include "llvm/Support/raw_ostream.h"
Chris Lattnerc68ab772008-03-22 00:08:40 +000030#include "llvm/System/Path.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000031using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000032using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000033
Steve Naroff0113c9d2008-01-28 21:34:52 +000034static llvm::cl::opt<bool>
35SilenceRewriteMacroWarning("Wno-rewrite-macros", llvm::cl::init(false),
36 llvm::cl::desc("Silence ObjC rewriting warnings"));
37
Chris Lattner77cd2a02007-10-11 00:43:27 +000038namespace {
Steve Naroffb29b4272008-04-14 22:03:09 +000039 class RewriteObjC : public ASTConsumer {
Chris Lattner2c64b7b2007-10-16 21:07:07 +000040 Rewriter Rewrite;
Chris Lattnere365c502007-11-30 22:25:36 +000041 Diagnostic &Diags;
Steve Naroff4f943c22008-03-10 20:43:59 +000042 const LangOptions &LangOpts;
Steve Narofff69cc5d2008-01-30 19:17:43 +000043 unsigned RewriteFailedDiag;
44
Chris Lattner01c57482007-10-17 22:35:30 +000045 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000046 SourceManager *SM;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000047 TranslationUnitDecl *TUDecl;
Chris Lattner8a12c272007-10-11 18:38:32 +000048 unsigned MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000049 const char *MainFileStart, *MainFileEnd;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000050 SourceLocation LastIncLoc;
Steve Naroffba92b2e2008-03-27 22:29:16 +000051
Ted Kremeneka526c5c2008-01-07 19:49:32 +000052 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
53 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
54 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Narofffbfe8252008-05-06 18:26:51 +000055 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000056 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
57 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000058 llvm::SmallVector<Stmt *, 32> Stmts;
59 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroffebf2b562007-10-23 23:50:29 +000060
Steve Naroffd82a9ab2008-03-15 00:55:56 +000061 unsigned NumObjCStringLiterals;
62
Steve Naroffebf2b562007-10-23 23:50:29 +000063 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000064 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000065 FunctionDecl *MsgSendStretFunctionDecl;
66 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000067 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000068 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000069 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000070 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000071 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +000072 FunctionDecl *GetProtocolFunctionDecl;
Steve Naroffc0a123c2008-03-11 17:37:02 +000073 FunctionDecl *SuperContructorFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000074
Steve Naroffbeaf2992007-11-03 11:27:19 +000075 // ObjC string constant support.
Steve Naroff248a7532008-04-15 22:42:06 +000076 VarDecl *ConstantStringClassReference;
Steve Naroffbeaf2992007-11-03 11:27:19 +000077 RecordDecl *NSStringRecord;
Steve Naroffab972d32007-11-04 22:37:50 +000078
Fariborz Jahanianb586cce2008-01-16 00:09:11 +000079 // ObjC foreach break/continue generation support.
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000080 int BcLabelCount;
81
Steve Naroff874e2322007-11-15 10:28:18 +000082 // Needed for super.
Steve Naroff54055232008-10-27 17:20:55 +000083 ObjCMethodDecl *CurMethodDef;
Steve Naroff874e2322007-11-15 10:28:18 +000084 RecordDecl *SuperStructDecl;
Steve Naroffd82a9ab2008-03-15 00:55:56 +000085 RecordDecl *ConstantStringDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000086
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +000087 // Needed for header files being rewritten
88 bool IsHeader;
89
Steve Naroffa7b402d2008-03-28 22:26:09 +000090 std::string InFileName;
91 std::string OutFileName;
92
Steve Naroffba92b2e2008-03-27 22:29:16 +000093 std::string Preamble;
Steve Naroff54055232008-10-27 17:20:55 +000094
95 // Block expressions.
96 llvm::SmallVector<BlockExpr *, 32> Blocks;
97 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
98 llvm::DenseMap<BlockDeclRefExpr *, CallExpr *> BlockCallExprs;
Steve Naroffba92b2e2008-03-27 22:29:16 +000099
Steve Naroff54055232008-10-27 17:20:55 +0000100 // Block related declarations.
101 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDecls;
102 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDecls;
103 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
104
105 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
106
107 FunctionDecl *CurFunctionDef;
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000108 VarDecl *GlobalVarDecl;
109
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000110 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +0000111 public:
Ted Kremeneke3a61982008-05-31 20:11:04 +0000112 virtual void Initialize(ASTContext &context);
113
114 virtual void InitializeTU(TranslationUnit &TU) {
115 TU.SetOwnsDecls(false);
116 Initialize(TU.getContext());
117 }
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000118
Chris Lattner8a12c272007-10-11 18:38:32 +0000119
Chris Lattnerf04da132007-10-24 17:06:59 +0000120 // Top Level Driver code.
121 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000122 void HandleDeclInMainFile(Decl *D);
Steve Naroffb29b4272008-04-14 22:03:09 +0000123 RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000124 Diagnostic &D, const LangOptions &LOpts);
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000125
126 ~RewriteObjC() {}
127
128 virtual void HandleTranslationUnit(TranslationUnit& TU);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000129
130 void ReplaceStmt(Stmt *Old, Stmt *New) {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000131 // If replacement succeeded or warning disabled return with no warning.
132 if (!Rewrite.ReplaceStmt(Old, New) || SilenceRewriteMacroWarning)
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000133 return;
134
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000135 SourceRange Range = Old->getSourceRange();
136 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag,
137 0, 0, &Range, 1);
138 }
139
Steve Naroffba92b2e2008-03-27 22:29:16 +0000140 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
141 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000142 // If insertion succeeded or warning disabled return with no warning.
Steve Naroffba92b2e2008-03-27 22:29:16 +0000143 if (!Rewrite.InsertText(Loc, StrData, StrLen, InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000144 SilenceRewriteMacroWarning)
145 return;
146
147 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
148 }
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000149
Chris Lattneraadaf782008-01-31 19:51:04 +0000150 void RemoveText(SourceLocation Loc, unsigned StrLen) {
151 // If removal succeeded or warning disabled return with no warning.
152 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
153 return;
154
155 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
156 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000157
Chris Lattneraadaf782008-01-31 19:51:04 +0000158 void ReplaceText(SourceLocation Start, unsigned OrigLength,
159 const char *NewStr, unsigned NewLength) {
160 // If removal succeeded or warning disabled return with no warning.
161 if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength) ||
162 SilenceRewriteMacroWarning)
163 return;
164
165 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
166 }
167
Chris Lattnerf04da132007-10-24 17:06:59 +0000168 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000169 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000170 void RewriteInclude();
Chris Lattnerf04da132007-10-24 17:06:59 +0000171 void RewriteTabs();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000172 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
173 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000174 void RewriteImplementationDecl(NamedDecl *Dcl);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000175 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
176 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
177 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
178 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
179 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Chris Lattner55d13b42008-03-16 21:23:50 +0000180 void RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +0000181 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000182 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroff4f95b752008-07-29 18:15:38 +0000183 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffd5255f52007-11-01 13:24:47 +0000184 bool needToScanForQualifiers(QualType T);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000185 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000186 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000187 QualType getConstantStringStructType();
Steve Naroffbaf58c32008-05-31 14:15:04 +0000188 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Chris Lattner311ff022007-10-16 22:36:42 +0000189
Chris Lattnerf04da132007-10-24 17:06:59 +0000190 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000191 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000192 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000193 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart);
Steve Naroffb42f8412007-11-05 14:50:49 +0000194 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000195 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000196 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000197 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000198 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000199 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000200 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
201 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
202 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000203 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
204 SourceLocation OrigEnd);
Steve Naroff934f2762007-10-24 22:48:43 +0000205 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
206 Expr **args, unsigned nargs);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000207 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000208 Stmt *RewriteBreakStmt(BreakStmt *S);
209 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000210 void SynthCountByEnumWithState(std::string &buf);
211
Steve Naroff09b266e2007-10-30 23:14:51 +0000212 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000213 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000214 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000215 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000216 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000217 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000218 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000219 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000220 void SynthGetProtocolFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000221 void SynthSuperContructorFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000222
Chris Lattnerf04da132007-10-24 17:06:59 +0000223 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000224 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000225 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000226
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000227 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000228 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000229
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000230 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
231 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000232 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000233 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000234 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000235 const char *ClassName,
236 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000237
Chris Lattner780f3292008-07-21 21:32:27 +0000238 void RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl>
239 &Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000240 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000241 const char *ClassName,
242 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000243 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000244 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000245 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
246 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000247 std::string &Result);
Steve Narofface66252008-11-13 20:07:04 +0000248 void RewriteImplementations();
249 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Steve Naroff54055232008-10-27 17:20:55 +0000250
251 // Block rewriting.
252 void RewriteBlocksInFunctionTypeProto(QualType funcType, NamedDecl *D);
253 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
254
255 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
256 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
257
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000258 // Block specific rewrite rules.
Steve Naroff54055232008-10-27 17:20:55 +0000259 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);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +0000270 Stmt *SynthesizeBlockCall(CallExpr *Exp);
Steve Naroff54055232008-10-27 17:20:55 +0000271 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);
Steve Naroffb2f9e512008-11-03 23:29:32 +0000302 void RewriteCastExpr(CStyleCastExpr *CE);
Steve Narofffa15fd92008-10-28 20:29:00 +0000303
304 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000305 Stmt *SynthBlockInitExpr(BlockExpr *Exp);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000306 };
307}
308
Steve Naroff54055232008-10-27 17:20:55 +0000309void RewriteObjC::RewriteBlocksInFunctionTypeProto(QualType funcType,
310 NamedDecl *D) {
311 if (FunctionTypeProto *fproto = dyn_cast<FunctionTypeProto>(funcType)) {
312 for (FunctionTypeProto::arg_type_iterator I = fproto->arg_type_begin(),
313 E = fproto->arg_type_end(); I && (I != E); ++I)
314 if (isBlockPointerType(*I)) {
315 // All the args are checked/rewritten. Don't call twice!
316 RewriteBlockPointerDecl(D);
317 break;
318 }
319 }
320}
321
322void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
323 const PointerType *PT = funcType->getAsPointerType();
324 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
325 RewriteBlocksInFunctionTypeProto(PT->getPointeeType(), ND);
326}
327
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000328static bool IsHeaderFile(const std::string &Filename) {
329 std::string::size_type DotPos = Filename.rfind('.');
330
331 if (DotPos == std::string::npos) {
332 // no file extension
333 return false;
334 }
335
336 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
337 // C header: .h
338 // C++ header: .hh or .H;
339 return Ext == "h" || Ext == "hh" || Ext == "H";
340}
341
Steve Naroffb29b4272008-04-14 22:03:09 +0000342RewriteObjC::RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000343 Diagnostic &D, const LangOptions &LOpts)
344 : Diags(D), LangOpts(LOpts) {
345 IsHeader = IsHeaderFile(inFile);
346 InFileName = inFile;
347 OutFileName = outFile;
348 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
349 "rewriting sub-expression within a macro (may not be correct)");
350}
351
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000352ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
Chris Lattnerc68ab772008-03-22 00:08:40 +0000353 const std::string& OutFile,
Steve Naroff4f943c22008-03-10 20:43:59 +0000354 Diagnostic &Diags,
355 const LangOptions &LOpts) {
Steve Naroffb29b4272008-04-14 22:03:09 +0000356 return new RewriteObjC(InFile, OutFile, Diags, LOpts);
Chris Lattnere365c502007-11-30 22:25:36 +0000357}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000358
Steve Naroffb29b4272008-04-14 22:03:09 +0000359void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000360 Context = &context;
361 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000362 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000363 MsgSendFunctionDecl = 0;
364 MsgSendSuperFunctionDecl = 0;
365 MsgSendStretFunctionDecl = 0;
366 MsgSendSuperStretFunctionDecl = 0;
367 MsgSendFpretFunctionDecl = 0;
368 GetClassFunctionDecl = 0;
369 GetMetaClassFunctionDecl = 0;
370 SelGetUidFunctionDecl = 0;
371 CFStringFunctionDecl = 0;
372 GetProtocolFunctionDecl = 0;
373 ConstantStringClassReference = 0;
374 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000375 CurMethodDef = 0;
376 CurFunctionDef = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000377 SuperStructDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000378 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000379 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000380 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000381 NumObjCStringLiterals = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000382
383 // Get the ID and start/end of the main file.
384 MainFileID = SM->getMainFileID();
385 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
386 MainFileStart = MainBuf->getBufferStart();
387 MainFileEnd = MainBuf->getBufferEnd();
Steve Naroffba92b2e2008-03-27 22:29:16 +0000388
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000389 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000390
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000391 // declaring objc_selector outside the parameter list removes a silly
392 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000393 if (IsHeader)
394 Preamble = "#pragma once\n";
395 Preamble += "struct objc_selector; struct objc_class;\n";
396 Preamble += "#ifndef OBJC_SUPER\n";
397 Preamble += "struct objc_super { struct objc_object *object; ";
398 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000399 if (LangOpts.Microsoft) {
400 // Add a constructor for creating temporary objects.
Steve Naroffba92b2e2008-03-27 22:29:16 +0000401 Preamble += "objc_super(struct objc_object *o, struct objc_object *s) : ";
402 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000403 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000404 Preamble += "};\n";
405 Preamble += "#define OBJC_SUPER\n";
406 Preamble += "#endif\n";
407 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
408 Preamble += "typedef struct objc_object Protocol;\n";
409 Preamble += "#define _REWRITER_typedef_Protocol\n";
410 Preamble += "#endif\n";
Steve Naroff3c64d9e2008-03-12 13:19:12 +0000411 if (LangOpts.Microsoft)
Steve Naroff69c827f2008-05-06 22:45:19 +0000412 Preamble += "#define __OBJC_RW_EXTERN extern \"C\" __declspec(dllimport)\n";
413 else
414 Preamble += "#define __OBJC_RW_EXTERN extern\n";
415 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000416 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000417 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000418 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000419 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000420 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000421 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000422 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff1284db82008-05-08 22:02:18 +0000423 Preamble += "__OBJC_RW_EXTERN double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000424 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff0757612008-05-08 17:52:16 +0000425 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000426 Preamble += "(const char *);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000427 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000428 Preamble += "(const char *);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000429 Preamble += "__OBJC_RW_EXTERN void objc_exception_throw(struct objc_object *);\n";
430 Preamble += "__OBJC_RW_EXTERN void objc_exception_try_enter(void *);\n";
431 Preamble += "__OBJC_RW_EXTERN void objc_exception_try_exit(void *);\n";
432 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_exception_extract(void *);\n";
433 Preamble += "__OBJC_RW_EXTERN int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000434 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000435 // @synchronized hooks.
436 Preamble += "__OBJC_RW_EXTERN void objc_sync_enter(struct objc_object *);\n";
437 Preamble += "__OBJC_RW_EXTERN void objc_sync_exit(struct objc_object *);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000438 Preamble += "__OBJC_RW_EXTERN Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000439 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
440 Preamble += "struct __objcFastEnumerationState {\n\t";
441 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000442 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000443 Preamble += "unsigned long *mutationsPtr;\n\t";
444 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff73ebd6d2008-06-02 20:23:21 +0000445 Preamble += "__OBJC_RW_EXTERN void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000446 Preamble += "#define __FASTENUMERATIONSTATE\n";
447 Preamble += "#endif\n";
448 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
449 Preamble += "struct __NSConstantStringImpl {\n";
450 Preamble += " int *isa;\n";
451 Preamble += " int flags;\n";
452 Preamble += " char *str;\n";
453 Preamble += " long length;\n";
454 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000455 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
456 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
457 Preamble += "#else\n";
Steve Naroff73b17cd2008-05-15 21:12:10 +0000458 Preamble += "__OBJC_RW_EXTERN int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000459 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000460 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
461 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000462 // Blocks preamble.
463 Preamble += "#ifndef BLOCK_IMPL\n";
464 Preamble += "#define BLOCK_IMPL\n";
465 Preamble += "struct __block_impl {\n";
466 Preamble += " void *isa;\n";
467 Preamble += " int Flags;\n";
468 Preamble += " int Size;\n";
469 Preamble += " void *FuncPtr;\n";
470 Preamble += "};\n";
471 Preamble += "enum {\n";
472 Preamble += " BLOCK_HAS_COPY_DISPOSE = (1<<25),\n";
473 Preamble += " BLOCK_IS_GLOBAL = (1<<28)\n";
474 Preamble += "};\n";
Steve Naroff54055232008-10-27 17:20:55 +0000475 Preamble += "// Runtime copy/destroy helper functions\n";
476 Preamble += "__OBJC_RW_EXTERN void _Block_copy_assign(void *, void *);\n";
477 Preamble += "__OBJC_RW_EXTERN void _Block_byref_assign_copy(void *, void *);\n";
478 Preamble += "__OBJC_RW_EXTERN void _Block_destroy(void *);\n";
479 Preamble += "__OBJC_RW_EXTERN void _Block_byref_release(void *);\n";
480 Preamble += "__OBJC_RW_EXTERN void *_NSConcreteGlobalBlock;\n";
481 Preamble += "__OBJC_RW_EXTERN void *_NSConcreteStackBlock;\n";
482 Preamble += "#endif\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000483 if (LangOpts.Microsoft) {
484 Preamble += "#undef __OBJC_RW_EXTERN\n";
485 Preamble += "#define __attribute__(X)\n";
486 }
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000487}
488
489
Chris Lattnerf04da132007-10-24 17:06:59 +0000490//===----------------------------------------------------------------------===//
491// Top Level Driver Code
492//===----------------------------------------------------------------------===//
493
Steve Naroffb29b4272008-04-14 22:03:09 +0000494void RewriteObjC::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000495 // Two cases: either the decl could be in the main file, or it could be in a
496 // #included file. If the former, rewrite it now. If the later, check to see
497 // if we rewrote the #include/#import.
498 SourceLocation Loc = D->getLocation();
499 Loc = SM->getLogicalLoc(Loc);
500
501 // If this is for a builtin, ignore it.
502 if (Loc.isInvalid()) return;
503
Steve Naroffebf2b562007-10-23 23:50:29 +0000504 // Look for built-in declarations that we need to refer during the rewrite.
505 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000506 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000507 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000508 // declared in <Foundation/NSString.h>
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000509 if (strcmp(FVD->getIdentifierName(), "_NSConstantStringClassReference") == 0) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000510 ConstantStringClassReference = FVD;
511 return;
512 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000513 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000514 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000515 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000516 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000517 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000518 RewriteProtocolDecl(PD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000519 } else if (ObjCForwardProtocolDecl *FP =
520 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000521 RewriteForwardProtocolDecl(FP);
Steve Naroffebf2b562007-10-23 23:50:29 +0000522 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000523 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000524 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000525 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000526}
527
Chris Lattnerf04da132007-10-24 17:06:59 +0000528//===----------------------------------------------------------------------===//
529// Syntactic (non-AST) Rewriting Code
530//===----------------------------------------------------------------------===//
531
Steve Naroffb29b4272008-04-14 22:03:09 +0000532void RewriteObjC::RewriteInclude() {
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000533 SourceLocation LocStart = SourceLocation::getFileLoc(MainFileID, 0);
534 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
535 const char *MainBufStart = MainBuf.first;
536 const char *MainBufEnd = MainBuf.second;
537 size_t ImportLen = strlen("import");
538 size_t IncludeLen = strlen("include");
539
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000540 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000541 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
542 if (*BufPtr == '#') {
543 if (++BufPtr == MainBufEnd)
544 return;
545 while (*BufPtr == ' ' || *BufPtr == '\t')
546 if (++BufPtr == MainBufEnd)
547 return;
548 if (!strncmp(BufPtr, "import", ImportLen)) {
549 // replace import with include
550 SourceLocation ImportLoc =
551 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattneraadaf782008-01-31 19:51:04 +0000552 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000553 BufPtr += ImportLen;
554 }
555 }
556 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000557}
558
Steve Naroffb29b4272008-04-14 22:03:09 +0000559void RewriteObjC::RewriteTabs() {
Chris Lattnerf04da132007-10-24 17:06:59 +0000560 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
561 const char *MainBufStart = MainBuf.first;
562 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000563
Chris Lattnerf04da132007-10-24 17:06:59 +0000564 // Loop over the whole file, looking for tabs.
565 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
566 if (*BufPtr != '\t')
567 continue;
568
569 // Okay, we found a tab. This tab will turn into at least one character,
570 // but it depends on which 'virtual column' it is in. Compute that now.
571 unsigned VCol = 0;
572 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
573 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
574 ++VCol;
575
576 // Okay, now that we know the virtual column, we know how many spaces to
577 // insert. We assume 8-character tab-stops.
578 unsigned Spaces = 8-(VCol & 7);
579
580 // Get the location of the tab.
581 SourceLocation TabLoc =
582 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
583
584 // Rewrite the single tab character into a sequence of spaces.
Chris Lattneraadaf782008-01-31 19:51:04 +0000585 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerf04da132007-10-24 17:06:59 +0000586 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000587}
588
589
Steve Naroffb29b4272008-04-14 22:03:09 +0000590void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000591 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000592 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerf04da132007-10-24 17:06:59 +0000593
594 // Get the start location and compute the semi location.
595 SourceLocation startLoc = ClassDecl->getLocation();
596 const char *startBuf = SM->getCharacterData(startLoc);
597 const char *semiPtr = strchr(startBuf, ';');
598
599 // Translate to typedef's that forward reference structs with the same name
600 // as the class. As a convenience, we include the original declaration
601 // as a comment.
602 std::string typedefString;
603 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000604 typedefString.append(startBuf, semiPtr-startBuf+1);
605 typedefString += "\n";
606 for (int i = 0; i < numDecls; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000607 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000608 typedefString += "#ifndef _REWRITER_typedef_";
609 typedefString += ForwardDecl->getName();
610 typedefString += "\n";
611 typedefString += "#define _REWRITER_typedef_";
612 typedefString += ForwardDecl->getName();
613 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000614 typedefString += "typedef struct objc_object ";
Steve Naroff934f2762007-10-24 22:48:43 +0000615 typedefString += ForwardDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000616 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000617 }
618
619 // Replace the @class with typedefs corresponding to the classes.
Chris Lattneraadaf782008-01-31 19:51:04 +0000620 ReplaceText(startLoc, semiPtr-startBuf+1,
621 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000622}
623
Steve Naroffb29b4272008-04-14 22:03:09 +0000624void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000625 SourceLocation LocStart = Method->getLocStart();
626 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000627
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000628 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
Steve Naroff94ac21e2008-10-21 13:37:27 +0000629 InsertText(LocStart, "#if 0\n", 6);
630 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000631 } else {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000632 InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000633 }
634}
635
Steve Naroffb29b4272008-04-14 22:03:09 +0000636void RewriteObjC::RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000637{
Chris Lattner55d13b42008-03-16 21:23:50 +0000638 for (unsigned i = 0; i < nProperties; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000639 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000640 SourceLocation Loc = Property->getLocation();
641
Chris Lattneraadaf782008-01-31 19:51:04 +0000642 ReplaceText(Loc, 0, "// ", 3);
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000643
644 // FIXME: handle properties that are declared across multiple lines.
645 }
646}
647
Steve Naroffb29b4272008-04-14 22:03:09 +0000648void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000649 SourceLocation LocStart = CatDecl->getLocStart();
650
651 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000652 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000653
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000654 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000655 E = CatDecl->instmeth_end(); I != E; ++I)
656 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000657 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000658 E = CatDecl->classmeth_end(); I != E; ++I)
659 RewriteMethodDeclaration(*I);
660
Steve Naroff423cb562007-10-30 13:30:57 +0000661 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000662 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000663}
664
Steve Naroffb29b4272008-04-14 22:03:09 +0000665void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000666 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000667
Steve Naroff752d6ef2007-10-30 16:42:30 +0000668 SourceLocation LocStart = PDecl->getLocStart();
669
670 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000671 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000672
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000673 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000674 E = PDecl->instmeth_end(); I != E; ++I)
675 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000676 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000677 E = PDecl->classmeth_end(); I != E; ++I)
678 RewriteMethodDeclaration(*I);
679
Steve Naroff752d6ef2007-10-30 16:42:30 +0000680 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000681 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattneraadaf782008-01-31 19:51:04 +0000682 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000683
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000684 // Must comment out @optional/@required
685 const char *startBuf = SM->getCharacterData(LocStart);
686 const char *endBuf = SM->getCharacterData(LocEnd);
687 for (const char *p = startBuf; p < endBuf; p++) {
688 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
689 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000690 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000691 ReplaceText(OptionalLoc, strlen("@optional"),
692 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000693
694 }
695 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
696 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000697 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000698 ReplaceText(OptionalLoc, strlen("@required"),
699 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000700
701 }
702 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000703}
704
Steve Naroffb29b4272008-04-14 22:03:09 +0000705void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000706 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000707 if (LocStart.isInvalid())
708 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000709 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000710 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000711}
712
Steve Naroffb29b4272008-04-14 22:03:09 +0000713void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000714 std::string &ResultStr) {
Steve Naroffced80a82008-10-30 12:09:33 +0000715 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroff76e429d2008-07-16 14:40:40 +0000716 const FunctionType *FPRetType = 0;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000717 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000718 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000719 ResultStr += "id";
Steve Naroff76e429d2008-07-16 14:40:40 +0000720 else if (OMD->getResultType()->isFunctionPointerType()) {
721 // needs special handling, since pointer-to-functions have special
722 // syntax (where a decaration models use).
723 QualType retType = OMD->getResultType();
724 if (const PointerType* PT = retType->getAsPointerType()) {
725 QualType PointeeTy = PT->getPointeeType();
726 if ((FPRetType = PointeeTy->getAsFunctionType())) {
727 ResultStr += FPRetType->getResultType().getAsString();
728 ResultStr += "(*";
729 }
730 }
731 } else
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000732 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000733 ResultStr += " ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000734
735 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000736 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000737
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000738 if (OMD->isInstance())
739 NameStr += "_I_";
740 else
741 NameStr += "_C_";
742
743 NameStr += OMD->getClassInterface()->getName();
744 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000745
746 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000747 if (ObjCCategoryImplDecl *CID =
748 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000749 NameStr += CID->getName();
750 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000751 }
Steve Naroff563b8282008-04-04 22:23:44 +0000752 // Append selector names, replacing ':' with '_'
753 if (OMD->getSelector().getName().find(':') == std::string::npos)
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000754 NameStr += OMD->getSelector().getName();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000755 else {
756 std::string selString = OMD->getSelector().getName();
757 int len = selString.size();
758 for (int i = 0; i < len; i++)
759 if (selString[i] == ':')
760 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000761 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000762 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000763 // Remember this name for metadata emission
764 MethodInternalNames[OMD] = NameStr;
765 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000766
767 // Rewrite arguments
768 ResultStr += "(";
769
770 // invisible arguments
771 if (OMD->isInstance()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000772 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000773 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +0000774 if (!LangOpts.Microsoft) {
775 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
776 ResultStr += "struct ";
777 }
778 // When rewriting for Microsoft, explicitly omit the structure name.
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000779 ResultStr += OMD->getClassInterface()->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000780 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000781 }
782 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000783 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000784
785 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000786 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000787 ResultStr += " _cmd";
788
789 // Method arguments.
Chris Lattner58cce3b2008-03-16 01:07:14 +0000790 for (unsigned i = 0; i < OMD->getNumParams(); i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000791 ParmVarDecl *PDecl = OMD->getParamDecl(i);
792 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +0000793 if (PDecl->getType()->isObjCQualifiedIdType()) {
794 ResultStr += "id ";
795 ResultStr += PDecl->getName();
796 } else {
797 std::string Name = PDecl->getName();
Steve Naroffc8ad87b2008-10-30 14:45:29 +0000798 if (isBlockPointerType(PDecl->getType())) {
799 // Make sure we convert "t (^)(...)" to "t (*)(...)".
800 const BlockPointerType *BPT = PDecl->getType()->getAsBlockPointerType();
801 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name);
802 } else
803 PDecl->getType().getAsStringInternal(Name);
Steve Naroff543409e2008-04-18 21:13:19 +0000804 ResultStr += Name;
805 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000806 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +0000807 if (OMD->isVariadic())
808 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000809 ResultStr += ") ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000810
Steve Naroff76e429d2008-07-16 14:40:40 +0000811 if (FPRetType) {
812 ResultStr += ")"; // close the precedence "scope" for "*".
813
814 // Now, emit the argument types (if any).
815 if (const FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(FPRetType)) {
816 ResultStr += "(";
817 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
818 if (i) ResultStr += ", ";
819 std::string ParamStr = FT->getArgType(i).getAsString();
820 ResultStr += ParamStr;
821 }
822 if (FT->isVariadic()) {
823 if (FT->getNumArgs()) ResultStr += ", ";
824 ResultStr += "...";
825 }
826 ResultStr += ")";
827 } else {
828 ResultStr += "()";
829 }
830 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000831}
Steve Naroffb29b4272008-04-14 22:03:09 +0000832void RewriteObjC::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000833 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
834 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000835
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000836 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000837 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000838 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000839 InsertText(CID->getLocStart(), "// ", 3);
Steve Narofface66252008-11-13 20:07:04 +0000840
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000841 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000842 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
843 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000844 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000845 ObjCMethodDecl *OMD = *I;
846 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000847 SourceLocation LocStart = OMD->getLocStart();
848 SourceLocation LocEnd = OMD->getBody()->getLocStart();
849
850 const char *startBuf = SM->getCharacterData(LocStart);
851 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000852 ReplaceText(LocStart, endBuf-startBuf,
853 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000854 }
855
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000856 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000857 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
858 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000859 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000860 ObjCMethodDecl *OMD = *I;
861 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000862 SourceLocation LocStart = OMD->getLocStart();
863 SourceLocation LocEnd = OMD->getBody()->getLocStart();
864
865 const char *startBuf = SM->getCharacterData(LocStart);
866 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000867 ReplaceText(LocStart, endBuf-startBuf,
868 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000869 }
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000870 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000871 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000872 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000873 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000874}
875
Steve Naroffb29b4272008-04-14 22:03:09 +0000876void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000877 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000878 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000879 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +0000880 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff32174822007-11-09 12:50:28 +0000881 ResultStr += ClassDecl->getName();
882 ResultStr += "\n";
883 ResultStr += "#define _REWRITER_typedef_";
884 ResultStr += ClassDecl->getName();
885 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000886 ResultStr += "typedef struct objc_object ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000887 ResultStr += ClassDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000888 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000889 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000890 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000891 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000892 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Narofff908a872007-10-30 02:23:23 +0000893
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000894 RewriteProperties(ClassDecl->getNumPropertyDecl(),
895 ClassDecl->getPropertyDecl());
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000896 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000897 E = ClassDecl->instmeth_end(); I != E; ++I)
898 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000899 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000900 E = ClassDecl->classmeth_end(); I != E; ++I)
901 RewriteMethodDeclaration(*I);
902
Steve Naroff2feac5e2007-10-30 03:43:13 +0000903 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000904 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000905}
906
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000907Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
908 SourceLocation OrigStart) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000909 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff54055232008-10-27 17:20:55 +0000910 if (CurMethodDef) {
Steve Naroff05b8c782008-03-12 00:25:36 +0000911 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +0000912 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
913 // lookup which class implements the instance variable.
914 ObjCInterfaceDecl *clsDeclared = 0;
915 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
916 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
917
918 // Synthesize an explicit cast to gain access to the ivar.
919 std::string RecName = clsDeclared->getIdentifier()->getName();
920 RecName += "_IMPL";
921 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000922 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +0000923 SourceLocation(), II);
Steve Narofff0757612008-05-08 17:52:16 +0000924 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
925 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Douglas Gregor6eec8e82008-10-28 15:36:24 +0000926 CastExpr *castExpr = new CStyleCastExpr(castT, IV->getBase(), castT,
Steve Naroffb2f9e512008-11-03 23:29:32 +0000927 SourceLocation(), SourceLocation());
Steve Narofff0757612008-05-08 17:52:16 +0000928 // Don't forget the parens to enforce the proper binding.
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000929 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
930 IV->getBase()->getLocEnd(),
931 castExpr);
Steve Narofff0757612008-05-08 17:52:16 +0000932 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +0000933 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000934 MemberExpr *ME = new MemberExpr(PE, true, D, IV->getLocation(),
935 D->getType());
Steve Narofff0757612008-05-08 17:52:16 +0000936 ReplaceStmt(IV, ME);
937 delete IV;
938 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000939 }
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000940
941 ReplaceStmt(IV->getBase(), PE);
942 // Cannot delete IV->getBase(), since PE points to it.
943 // Replace the old base with the cast. This is important when doing
944 // embedded rewrites. For example, [newInv->_container addObject:0].
945 IV->setBase(PE);
946 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000947 }
Steve Naroff84472a82008-04-18 21:55:08 +0000948 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +0000949 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
950
951 // Explicit ivar refs need to have a cast inserted.
952 // FIXME: consider sharing some of this code with the code above.
953 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +0000954 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +0000955 // lookup which class implements the instance variable.
956 ObjCInterfaceDecl *clsDeclared = 0;
Steve Narofff0757612008-05-08 17:52:16 +0000957 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +0000958 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
959
960 // Synthesize an explicit cast to gain access to the ivar.
961 std::string RecName = clsDeclared->getIdentifier()->getName();
962 RecName += "_IMPL";
963 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000964 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +0000965 SourceLocation(), II);
Steve Naroff9f525972008-05-06 23:20:07 +0000966 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
967 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Douglas Gregor6eec8e82008-10-28 15:36:24 +0000968 CastExpr *castExpr = new CStyleCastExpr(castT, IV->getBase(), castT,
Steve Naroffb2f9e512008-11-03 23:29:32 +0000969 SourceLocation(), SourceLocation());
Steve Naroff9f525972008-05-06 23:20:07 +0000970 // Don't forget the parens to enforce the proper binding.
Chris Lattner8d366162008-05-28 16:38:23 +0000971 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
972 IV->getBase()->getLocEnd(), castExpr);
Steve Naroff9f525972008-05-06 23:20:07 +0000973 ReplaceStmt(IV->getBase(), PE);
974 // Cannot delete IV->getBase(), since PE points to it.
975 // Replace the old base with the cast. This is important when doing
976 // embedded rewrites. For example, [newInv->_container addObject:0].
977 IV->setBase(PE);
978 return IV;
979 }
Steve Naroffc2a689b2007-11-15 11:33:00 +0000980 }
Steve Naroff84472a82008-04-18 21:55:08 +0000981 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +0000982}
983
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000984/// SynthCountByEnumWithState - To print:
985/// ((unsigned int (*)
986/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
987/// (void *)objc_msgSend)((id)l_collection,
988/// sel_registerName(
989/// "countByEnumeratingWithState:objects:count:"),
990/// &enumState,
991/// (id *)items, (unsigned int)16)
992///
Steve Naroffb29b4272008-04-14 22:03:09 +0000993void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000994 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
995 "id *, unsigned int))(void *)objc_msgSend)";
996 buf += "\n\t\t";
997 buf += "((id)l_collection,\n\t\t";
998 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
999 buf += "\n\t\t";
1000 buf += "&enumState, "
1001 "(id *)items, (unsigned int)16)";
1002}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001003
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001004/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1005/// statement to exit to its outer synthesized loop.
1006///
Steve Naroffb29b4272008-04-14 22:03:09 +00001007Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001008 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1009 return S;
1010 // replace break with goto __break_label
1011 std::string buf;
1012
1013 SourceLocation startLoc = S->getLocStart();
1014 buf = "goto __break_label_";
1015 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001016 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001017
1018 return 0;
1019}
1020
1021/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1022/// statement to continue with its inner synthesized loop.
1023///
Steve Naroffb29b4272008-04-14 22:03:09 +00001024Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001025 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1026 return S;
1027 // replace continue with goto __continue_label
1028 std::string buf;
1029
1030 SourceLocation startLoc = S->getLocStart();
1031 buf = "goto __continue_label_";
1032 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001033 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001034
1035 return 0;
1036}
1037
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001038/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001039/// It rewrites:
1040/// for ( type elem in collection) { stmts; }
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001041
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001042/// Into:
1043/// {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001044/// type elem;
1045/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001046/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001047/// id l_collection = (id)collection;
1048/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1049/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001050/// if (limit) {
1051/// unsigned long startMutations = *enumState.mutationsPtr;
1052/// do {
1053/// unsigned long counter = 0;
1054/// do {
1055/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001056/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001057/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001058/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001059/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001060/// } while (counter < limit);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001061/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1062/// objects:items count:16]);
1063/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001064/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001065/// }
1066/// else
1067/// elem = nil;
1068/// }
1069///
Steve Naroffb29b4272008-04-14 22:03:09 +00001070Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001071 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001072 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1073 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1074 "ObjCForCollectionStmt Statement stack mismatch");
1075 assert(!ObjCBcLabelNo.empty() &&
1076 "ObjCForCollectionStmt - Label No stack empty");
1077
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001078 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001079 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001080 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001081 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001082 std::string buf;
1083 buf = "\n{\n\t";
1084 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1085 // type elem;
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001086 ScopedDecl* D = DS->getSolitaryDecl();
1087 QualType ElementType = cast<ValueDecl>(D)->getType();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001088 elementTypeAsString = ElementType.getAsString();
1089 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001090 buf += " ";
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001091 elementName = D->getIdentifierName();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001092 buf += elementName;
1093 buf += ";\n\t";
1094 }
Chris Lattner06767512008-04-08 05:52:18 +00001095 else {
1096 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001097 elementName = DR->getDecl()->getIdentifierName();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001098 elementTypeAsString
1099 = cast<ValueDecl>(DR->getDecl())->getType().getAsString();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001100 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001101
1102 // struct __objcFastEnumerationState enumState = { 0 };
1103 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1104 // id items[16];
1105 buf += "id items[16];\n\t";
1106 // id l_collection = (id)
1107 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001108 // Find start location of 'collection' the hard way!
1109 const char *startCollectionBuf = startBuf;
1110 startCollectionBuf += 3; // skip 'for'
1111 startCollectionBuf = strchr(startCollectionBuf, '(');
1112 startCollectionBuf++; // skip '('
1113 // find 'in' and skip it.
1114 while (*startCollectionBuf != ' ' ||
1115 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1116 (*(startCollectionBuf+3) != ' ' &&
1117 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1118 startCollectionBuf++;
1119 startCollectionBuf += 3;
1120
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001121 // Replace: "for (type element in" with string constructed thus far.
Chris Lattneraadaf782008-01-31 19:51:04 +00001122 ReplaceText(startLoc, startCollectionBuf - startBuf,
1123 buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001124 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001125 SourceLocation rightParenLoc = S->getRParenLoc();
1126 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1127 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001128 buf = ";\n\t";
1129
1130 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1131 // objects:items count:16];
1132 // which is synthesized into:
1133 // unsigned int limit =
1134 // ((unsigned int (*)
1135 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1136 // (void *)objc_msgSend)((id)l_collection,
1137 // sel_registerName(
1138 // "countByEnumeratingWithState:objects:count:"),
1139 // (struct __objcFastEnumerationState *)&state,
1140 // (id *)items, (unsigned int)16);
1141 buf += "unsigned long limit =\n\t\t";
1142 SynthCountByEnumWithState(buf);
1143 buf += ";\n\t";
1144 /// if (limit) {
1145 /// unsigned long startMutations = *enumState.mutationsPtr;
1146 /// do {
1147 /// unsigned long counter = 0;
1148 /// do {
1149 /// if (startMutations != *enumState.mutationsPtr)
1150 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001151 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001152 buf += "if (limit) {\n\t";
1153 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1154 buf += "do {\n\t\t";
1155 buf += "unsigned long counter = 0;\n\t\t";
1156 buf += "do {\n\t\t\t";
1157 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1158 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1159 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001160 buf += " = (";
1161 buf += elementTypeAsString;
1162 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001163 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattneraadaf782008-01-31 19:51:04 +00001164 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001165
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001166 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001167 /// } while (counter < limit);
1168 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1169 /// objects:items count:16]);
1170 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001171 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001172 /// }
1173 /// else
1174 /// elem = nil;
1175 /// }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001176 ///
1177 buf = ";\n\t";
1178 buf += "__continue_label_";
1179 buf += utostr(ObjCBcLabelNo.back());
1180 buf += ": ;";
1181 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001182 buf += "} while (counter < limit);\n\t";
1183 buf += "} while (limit = ";
1184 SynthCountByEnumWithState(buf);
1185 buf += ");\n\t";
1186 buf += elementName;
1187 buf += " = nil;\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001188 buf += "__break_label_";
1189 buf += utostr(ObjCBcLabelNo.back());
1190 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001191 buf += "}\n\t";
1192 buf += "else\n\t\t";
1193 buf += elementName;
1194 buf += " = nil;\n";
1195 buf += "}\n";
Steve Naroff600e4e82008-07-21 18:26:02 +00001196
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001197 // Insert all these *after* the statement body.
Steve Naroff600e4e82008-07-21 18:26:02 +00001198 if (isa<CompoundStmt>(S->getBody())) {
1199 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1200 InsertText(endBodyLoc, buf.c_str(), buf.size());
1201 } else {
1202 /* Need to treat single statements specially. For example:
1203 *
1204 * for (A *a in b) if (stuff()) break;
1205 * for (A *a in b) xxxyy;
1206 *
1207 * The following code simply scans ahead to the semi to find the actual end.
1208 */
1209 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1210 const char *semiBuf = strchr(stmtBuf, ';');
1211 assert(semiBuf && "Can't find ';'");
1212 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1213 InsertText(endBodyLoc, buf.c_str(), buf.size());
1214 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001215 Stmts.pop_back();
1216 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001217 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001218}
1219
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001220/// RewriteObjCSynchronizedStmt -
1221/// This routine rewrites @synchronized(expr) stmt;
1222/// into:
1223/// objc_sync_enter(expr);
1224/// @try stmt @finally { objc_sync_exit(expr); }
1225///
Steve Naroffb29b4272008-04-14 22:03:09 +00001226Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001227 // Get the start location and compute the semi location.
1228 SourceLocation startLoc = S->getLocStart();
1229 const char *startBuf = SM->getCharacterData(startLoc);
1230
1231 assert((*startBuf == '@') && "bogus @synchronized location");
1232
1233 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001234 buf = "objc_sync_enter((id)";
1235 const char *lparenBuf = startBuf;
1236 while (*lparenBuf != '(') lparenBuf++;
1237 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Steve Naroffc7089f12008-08-19 13:04:19 +00001238 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1239 // the sync expression is typically a message expression that's already
1240 // been rewritten! (which implies the SourceLocation's are invalid).
1241 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001242 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001243 while (*endBuf != ')') endBuf--;
1244 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001245 buf = ");\n";
1246 // declare a new scope with two variables, _stack and _rethrow.
1247 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1248 buf += "int buf[18/*32-bit i386*/];\n";
1249 buf += "char *pointers[4];} _stack;\n";
1250 buf += "id volatile _rethrow = 0;\n";
1251 buf += "objc_exception_try_enter(&_stack);\n";
1252 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00001253 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001254 startLoc = S->getSynchBody()->getLocEnd();
1255 startBuf = SM->getCharacterData(startLoc);
1256
Steve Naroffc7089f12008-08-19 13:04:19 +00001257 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001258 SourceLocation lastCurlyLoc = startLoc;
1259 buf = "}\nelse {\n";
1260 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1261 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb2a39452008-07-16 19:47:39 +00001262 buf += " objc_sync_exit(";
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001263 Expr *syncExpr = new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00001264 S->getSynchExpr(),
1265 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00001266 SourceLocation(), SourceLocation());
Ted Kremeneka95d3752008-09-13 05:16:45 +00001267 std::string syncExprBufS;
1268 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Steve Naroff3498cc92008-08-21 13:03:03 +00001269 syncExpr->printPretty(syncExprBuf);
Steve Naroffb2a39452008-07-16 19:47:39 +00001270 buf += syncExprBuf.str();
1271 buf += ");\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001272 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1273 buf += "}\n";
1274 buf += "}";
1275
Chris Lattneraadaf782008-01-31 19:51:04 +00001276 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001277 return 0;
1278}
1279
Steve Naroffb29b4272008-04-14 22:03:09 +00001280Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001281 // Get the start location and compute the semi location.
1282 SourceLocation startLoc = S->getLocStart();
1283 const char *startBuf = SM->getCharacterData(startLoc);
1284
1285 assert((*startBuf == '@') && "bogus @try location");
1286
1287 std::string buf;
1288 // declare a new scope with two variables, _stack and _rethrow.
1289 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1290 buf += "int buf[18/*32-bit i386*/];\n";
1291 buf += "char *pointers[4];} _stack;\n";
1292 buf += "id volatile _rethrow = 0;\n";
1293 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001294 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001295
Chris Lattneraadaf782008-01-31 19:51:04 +00001296 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001297
1298 startLoc = S->getTryBody()->getLocEnd();
1299 startBuf = SM->getCharacterData(startLoc);
1300
1301 assert((*startBuf == '}') && "bogus @try block");
Steve Naroffc9ba1722008-07-16 15:31:30 +00001302
Steve Naroff75730982007-11-07 04:08:17 +00001303 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffc9ba1722008-07-16 15:31:30 +00001304 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1305 if (catchList) {
1306 startLoc = startLoc.getFileLocWithOffset(1);
1307 buf = " /* @catch begin */ else {\n";
1308 buf += " id _caught = objc_exception_extract(&_stack);\n";
1309 buf += " objc_exception_try_enter (&_stack);\n";
1310 buf += " if (_setjmp(_stack.buf))\n";
1311 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1312 buf += " else { /* @catch continue */";
1313
1314 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001315 } else { /* no catch list */
1316 buf = "}\nelse {\n";
1317 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1318 buf += "}";
1319 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffc9ba1722008-07-16 15:31:30 +00001320 }
Steve Naroff75730982007-11-07 04:08:17 +00001321 bool sawIdTypedCatch = false;
1322 Stmt *lastCatchBody = 0;
Steve Naroff75730982007-11-07 04:08:17 +00001323 while (catchList) {
1324 Stmt *catchStmt = catchList->getCatchParamStmt();
1325
1326 if (catchList == S->getCatchStmts())
1327 buf = "if ("; // we are generating code for the first catch clause
1328 else
1329 buf = "else if (";
1330 startLoc = catchList->getLocStart();
1331 startBuf = SM->getCharacterData(startLoc);
1332
1333 assert((*startBuf == '@') && "bogus @catch location");
1334
1335 const char *lParenLoc = strchr(startBuf, '(');
1336
Steve Naroffbe4b3332008-02-01 22:08:12 +00001337 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001338 // Now rewrite the body...
1339 lastCatchBody = catchList->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001340 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1341 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner06767512008-04-08 05:52:18 +00001342 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1343 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001344 assert((*bodyBuf == '{') && "bogus @catch body location");
1345
1346 buf += "1) { id _tmp = _caught;";
1347 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1348 buf.c_str(), buf.size());
1349 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Ted Kremenek50a25e22008-10-06 22:39:38 +00001350 QualType t = dyn_cast<ValueDecl>(declStmt->getSolitaryDecl())->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001351 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001352 buf += "1) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001353 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001354 sawIdTypedCatch = true;
1355 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001356 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroff75730982007-11-07 04:08:17 +00001357
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001358 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001359 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001360 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroff75730982007-11-07 04:08:17 +00001361 buf += cls->getDecl()->getName();
Steve Naroff21867b12007-11-07 18:43:40 +00001362 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001363 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001364 }
1365 }
1366 // Now rewrite the body...
1367 lastCatchBody = catchList->getCatchBody();
1368 SourceLocation rParenLoc = catchList->getRParenLoc();
1369 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1370 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1371 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1372 assert((*rParenBuf == ')') && "bogus @catch paren location");
1373 assert((*bodyBuf == '{') && "bogus @catch body location");
1374
1375 buf = " = _caught;";
1376 // Here we replace ") {" with "= _caught;" (which initializes and
1377 // declares the @catch parameter).
Chris Lattneraadaf782008-01-31 19:51:04 +00001378 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001379 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001380 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001381 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001382 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001383 catchList = catchList->getNextCatchStmt();
1384 }
1385 // Complete the catch list...
1386 if (lastCatchBody) {
1387 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001388 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1389 "bogus @catch body location");
Steve Naroff75730982007-11-07 04:08:17 +00001390
Steve Naroff378f47a2008-09-11 15:29:03 +00001391 // Insert the last (implicit) else clause *before* the right curly brace.
1392 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1393 buf = "} /* last catch end */\n";
1394 buf += "else {\n";
1395 buf += " _rethrow = _caught;\n";
1396 buf += " objc_exception_try_exit(&_stack);\n";
1397 buf += "} } /* @catch end */\n";
1398 if (!S->getFinallyStmt())
1399 buf += "}\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001400 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001401
1402 // Set lastCurlyLoc
1403 lastCurlyLoc = lastCatchBody->getLocEnd();
1404 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001405 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001406 startLoc = finalStmt->getLocStart();
1407 startBuf = SM->getCharacterData(startLoc);
1408 assert((*startBuf == '@') && "bogus @finally start");
1409
1410 buf = "/* @finally */";
Chris Lattneraadaf782008-01-31 19:51:04 +00001411 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001412
1413 Stmt *body = finalStmt->getFinallyBody();
1414 SourceLocation startLoc = body->getLocStart();
1415 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001416 assert(*SM->getCharacterData(startLoc) == '{' &&
1417 "bogus @finally body location");
1418 assert(*SM->getCharacterData(endLoc) == '}' &&
1419 "bogus @finally body location");
Steve Naroff75730982007-11-07 04:08:17 +00001420
1421 startLoc = startLoc.getFileLocWithOffset(1);
1422 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001423 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001424 endLoc = endLoc.getFileLocWithOffset(-1);
1425 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001426 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001427
1428 // Set lastCurlyLoc
1429 lastCurlyLoc = body->getLocEnd();
Steve Naroff378f47a2008-09-11 15:29:03 +00001430 } else { /* no finally clause - make sure we synthesize an implicit one */
1431 buf = "{ /* implicit finally clause */\n";
1432 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1433 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1434 buf += "}";
1435 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001436 }
1437 // Now emit the final closing curly brace...
1438 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1439 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001440 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001441 return 0;
1442}
1443
Steve Naroffb29b4272008-04-14 22:03:09 +00001444Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001445 return 0;
1446}
1447
Steve Naroffb29b4272008-04-14 22:03:09 +00001448Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001449 return 0;
1450}
1451
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001452// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff2bd03922007-11-07 15:32:26 +00001453// the throw expression is typically a message expression that's already
1454// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001455Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001456 // Get the start location and compute the semi location.
1457 SourceLocation startLoc = S->getLocStart();
1458 const char *startBuf = SM->getCharacterData(startLoc);
1459
1460 assert((*startBuf == '@') && "bogus @throw location");
1461
1462 std::string buf;
1463 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001464 if (S->getThrowExpr())
1465 buf = "objc_exception_throw(";
1466 else // add an implicit argument
1467 buf = "objc_exception_throw(_caught";
Steve Naroff4ba0acb2008-07-25 15:41:30 +00001468
1469 // handle "@ throw" correctly.
1470 const char *wBuf = strchr(startBuf, 'w');
1471 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1472 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
1473
Steve Naroff2bd03922007-11-07 15:32:26 +00001474 const char *semiBuf = strchr(startBuf, ';');
1475 assert((*semiBuf == ';') && "@throw: can't find ';'");
1476 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1477 buf = ");";
Chris Lattneraadaf782008-01-31 19:51:04 +00001478 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001479 return 0;
1480}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001481
Steve Naroffb29b4272008-04-14 22:03:09 +00001482Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001483 // Create a new string expression.
1484 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001485 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001486 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001487 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1488 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +00001489 SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001490 ReplaceStmt(Exp, Replacement);
Chris Lattnere365c502007-11-30 22:25:36 +00001491
Chris Lattner07506182007-11-30 22:53:43 +00001492 // Replace this subexpr in the parent.
Chris Lattnere64b7772007-10-24 16:57:36 +00001493 delete Exp;
1494 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001495}
1496
Steve Naroffb29b4272008-04-14 22:03:09 +00001497Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroffb42f8412007-11-05 14:50:49 +00001498 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1499 // Create a call to sel_registerName("selName").
1500 llvm::SmallVector<Expr*, 8> SelExprs;
1501 QualType argType = Context->getPointerType(Context->CharTy);
1502 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1503 Exp->getSelector().getName().size(),
1504 false, argType, SourceLocation(),
1505 SourceLocation()));
1506 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1507 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001508 ReplaceStmt(Exp, SelExp);
Steve Naroffb42f8412007-11-05 14:50:49 +00001509 delete Exp;
1510 return SelExp;
1511}
1512
Steve Naroffb29b4272008-04-14 22:03:09 +00001513CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff934f2762007-10-24 22:48:43 +00001514 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001515 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001516 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +00001517
1518 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +00001519 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +00001520
1521 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001522 QualType pToFunc = Context->getPointerType(msgSendType);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001523 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE,
1524 /*isLvalue=*/false);
Steve Naroffebf2b562007-10-23 23:50:29 +00001525
1526 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +00001527
Steve Naroff934f2762007-10-24 22:48:43 +00001528 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1529}
1530
Steve Naroffd5255f52007-11-01 13:24:47 +00001531static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1532 const char *&startRef, const char *&endRef) {
1533 while (startBuf < endBuf) {
1534 if (*startBuf == '<')
1535 startRef = startBuf; // mark the start.
1536 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001537 if (startRef && *startRef == '<') {
1538 endRef = startBuf; // mark the end.
1539 return true;
1540 }
1541 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001542 }
1543 startBuf++;
1544 }
1545 return false;
1546}
1547
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001548static void scanToNextArgument(const char *&argRef) {
1549 int angle = 0;
1550 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1551 if (*argRef == '<')
1552 angle++;
1553 else if (*argRef == '>')
1554 angle--;
1555 argRef++;
1556 }
1557 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1558}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001559
Steve Naroffb29b4272008-04-14 22:03:09 +00001560bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001561
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001562 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001563 return true;
1564
Steve Naroffd5255f52007-11-01 13:24:47 +00001565 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +00001566 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001567 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff9165ad32007-10-31 04:38:33 +00001568 return true; // we have "Class <Protocol> *".
1569 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001570 return false;
1571}
1572
Steve Naroff4f95b752008-07-29 18:15:38 +00001573void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1574 QualType Type = E->getType();
1575 if (needToScanForQualifiers(Type)) {
1576 SourceLocation Loc = E->getLocStart();
1577 const char *startBuf = SM->getCharacterData(Loc);
1578 const char *endBuf = SM->getCharacterData(E->getLocEnd());
1579 const char *startRef = 0, *endRef = 0;
1580 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1581 // Get the locations of the startRef, endRef.
1582 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1583 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1584 // Comment out the protocol references.
1585 InsertText(LessLoc, "/*", 2);
1586 InsertText(GreaterLoc, "*/", 2);
1587 }
1588 }
1589}
1590
Steve Naroffb29b4272008-04-14 22:03:09 +00001591void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001592 SourceLocation Loc;
1593 QualType Type;
1594 const FunctionTypeProto *proto = 0;
1595 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1596 Loc = VD->getLocation();
1597 Type = VD->getType();
1598 }
1599 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1600 Loc = FD->getLocation();
1601 // Check for ObjC 'id' and class types that have been adorned with protocol
1602 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1603 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1604 assert(funcType && "missing function type");
1605 proto = dyn_cast<FunctionTypeProto>(funcType);
1606 if (!proto)
1607 return;
1608 Type = proto->getResultType();
1609 }
1610 else
1611 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001612
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001613 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001614 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001615
1616 const char *endBuf = SM->getCharacterData(Loc);
1617 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00001618 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001619 startBuf--; // scan backward (from the decl location) for return type.
1620 const char *startRef = 0, *endRef = 0;
1621 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1622 // Get the locations of the startRef, endRef.
1623 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1624 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1625 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001626 InsertText(LessLoc, "/*", 2);
1627 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001628 }
1629 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001630 if (!proto)
1631 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001632 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001633 const char *startBuf = SM->getCharacterData(Loc);
1634 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001635 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1636 if (needToScanForQualifiers(proto->getArgType(i))) {
1637 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001638
Steve Naroffd5255f52007-11-01 13:24:47 +00001639 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001640 // scan forward (from the decl location) for argument types.
1641 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001642 const char *startRef = 0, *endRef = 0;
1643 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1644 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001645 SourceLocation LessLoc =
1646 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1647 SourceLocation GreaterLoc =
1648 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001649 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001650 InsertText(LessLoc, "/*", 2);
1651 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001652 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001653 startBuf = ++endBuf;
1654 }
1655 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00001656 // If the function name is derived from a macro expansion, then the
1657 // argument buffer will not follow the name. Need to speak with Chris.
1658 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001659 startBuf++; // scan forward (from the decl location) for argument types.
1660 startBuf++;
1661 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001662 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001663}
1664
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001665// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00001666void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001667 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1668 llvm::SmallVector<QualType, 16> ArgTys;
1669 ArgTys.push_back(Context->getPointerType(
1670 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001671 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001672 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001673 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001674 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001675 SourceLocation(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001676 SelGetUidIdent, getFuncType,
1677 FunctionDecl::Extern, false, 0);
1678}
1679
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001680// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
Steve Naroffb29b4272008-04-14 22:03:09 +00001681void RewriteObjC::SynthGetProtocolFunctionDecl() {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001682 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1683 llvm::SmallVector<QualType, 16> ArgTys;
1684 ArgTys.push_back(Context->getPointerType(
1685 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001686 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001687 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001688 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001689 GetProtocolFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001690 SourceLocation(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001691 SelGetProtoIdent, getFuncType,
1692 FunctionDecl::Extern, false, 0);
1693}
1694
Steve Naroffb29b4272008-04-14 22:03:09 +00001695void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001696 // declared in <objc/objc.h>
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001697 if (strcmp(FD->getIdentifierName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001698 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001699 return;
1700 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001701 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001702}
1703
Steve Naroffc0a123c2008-03-11 17:37:02 +00001704// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00001705void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00001706 if (SuperContructorFunctionDecl)
1707 return;
1708 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_super");
1709 llvm::SmallVector<QualType, 16> ArgTys;
1710 QualType argT = Context->getObjCIdType();
1711 assert(!argT.isNull() && "Can't find 'id' type");
1712 ArgTys.push_back(argT);
1713 ArgTys.push_back(argT);
1714 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1715 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001716 false, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001717 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001718 SourceLocation(),
Steve Naroffc0a123c2008-03-11 17:37:02 +00001719 msgSendIdent, msgSendType,
1720 FunctionDecl::Extern, false, 0);
1721}
1722
Steve Naroff09b266e2007-10-30 23:14:51 +00001723// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001724void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00001725 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1726 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001727 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001728 assert(!argT.isNull() && "Can't find 'id' type");
1729 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001730 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001731 assert(!argT.isNull() && "Can't find 'SEL' type");
1732 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001733 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001734 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001735 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001736 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001737 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001738 msgSendIdent, msgSendType,
1739 FunctionDecl::Extern, false, 0);
1740}
1741
Steve Naroff874e2322007-11-15 10:28:18 +00001742// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001743void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00001744 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1745 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001746 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001747 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00001748 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00001749 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1750 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1751 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001752 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00001753 assert(!argT.isNull() && "Can't find 'SEL' type");
1754 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001755 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00001756 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001757 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001758 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001759 SourceLocation(),
Steve Naroff874e2322007-11-15 10:28:18 +00001760 msgSendIdent, msgSendType,
1761 FunctionDecl::Extern, false, 0);
1762}
1763
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001764// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001765void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001766 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1767 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001768 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001769 assert(!argT.isNull() && "Can't find 'id' type");
1770 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001771 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001772 assert(!argT.isNull() && "Can't find 'SEL' type");
1773 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001774 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001775 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001776 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001777 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001778 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001779 msgSendIdent, msgSendType,
1780 FunctionDecl::Extern, false, 0);
1781}
1782
1783// SynthMsgSendSuperStretFunctionDecl -
1784// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001785void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001786 IdentifierInfo *msgSendIdent =
1787 &Context->Idents.get("objc_msgSendSuper_stret");
1788 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001789 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001790 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00001791 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001792 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1793 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1794 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001795 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001796 assert(!argT.isNull() && "Can't find 'SEL' type");
1797 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001798 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001799 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001800 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001801 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnera98e58d2008-03-15 21:24:04 +00001802 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001803 msgSendIdent, msgSendType,
1804 FunctionDecl::Extern, false, 0);
1805}
1806
Steve Naroff1284db82008-05-08 22:02:18 +00001807// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001808void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001809 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1810 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001811 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001812 assert(!argT.isNull() && "Can't find 'id' type");
1813 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001814 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001815 assert(!argT.isNull() && "Can't find 'SEL' type");
1816 ArgTys.push_back(argT);
Steve Naroff1284db82008-05-08 22:02:18 +00001817 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001818 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001819 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001820 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001821 SourceLocation(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001822 msgSendIdent, msgSendType,
1823 FunctionDecl::Extern, false, 0);
1824}
1825
Steve Naroff09b266e2007-10-30 23:14:51 +00001826// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00001827void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00001828 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1829 llvm::SmallVector<QualType, 16> ArgTys;
1830 ArgTys.push_back(Context->getPointerType(
1831 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001832 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001833 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001834 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001835 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001836 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001837 getClassIdent, getClassType,
1838 FunctionDecl::Extern, false, 0);
1839}
1840
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001841// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00001842void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001843 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1844 llvm::SmallVector<QualType, 16> ArgTys;
1845 ArgTys.push_back(Context->getPointerType(
1846 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001847 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001848 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001849 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001850 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001851 SourceLocation(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001852 getClassIdent, getClassType,
1853 FunctionDecl::Extern, false, 0);
1854}
1855
Steve Naroffb29b4272008-04-14 22:03:09 +00001856Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001857 QualType strType = getConstantStringStructType();
1858
1859 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00001860
1861 std::string tmpName = InFileName;
1862 unsigned i;
1863 for (i=0; i < tmpName.length(); i++) {
1864 char c = tmpName.at(i);
1865 // replace any non alphanumeric characters with '_'.
1866 if (!isalpha(c) && (c < '0' || c > '9'))
1867 tmpName[i] = '_';
1868 }
1869 S += tmpName;
1870 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001871 S += utostr(NumObjCStringLiterals++);
1872
Steve Naroffba92b2e2008-03-27 22:29:16 +00001873 Preamble += "static __NSConstantStringImpl " + S;
1874 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
1875 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001876 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00001877 std::string prettyBufS;
1878 llvm::raw_string_ostream prettyBuf(prettyBufS);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001879 Exp->getString()->printPretty(prettyBuf);
Steve Naroffba92b2e2008-03-27 22:29:16 +00001880 Preamble += prettyBuf.str();
1881 Preamble += ",";
Steve Naroff3652c2d2008-03-15 01:36:04 +00001882 // The minus 2 removes the begin/end double quotes.
Steve Naroffba92b2e2008-03-27 22:29:16 +00001883 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001884
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001885 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Steve Naroff248a7532008-04-15 22:42:06 +00001886 &Context->Idents.get(S.c_str()), strType,
1887 VarDecl::Static, NULL);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001888 DeclRefExpr *DRE = new DeclRefExpr(NewVD, strType, SourceLocation());
1889 Expr *Unop = new UnaryOperator(DRE, UnaryOperator::AddrOf,
1890 Context->getPointerType(DRE->getType()),
1891 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00001892 // cast to NSConstantString *
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001893 CastExpr *cast = new CStyleCastExpr(Exp->getType(), Unop,
Steve Naroffb2f9e512008-11-03 23:29:32 +00001894 Exp->getType(), SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001895 ReplaceStmt(Exp, cast);
Steve Naroff96984642007-11-08 14:30:50 +00001896 delete Exp;
1897 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00001898}
1899
Steve Naroffb29b4272008-04-14 22:03:09 +00001900ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001901 // check if we are sending a message to 'super'
Steve Naroff54055232008-10-27 17:20:55 +00001902 if (!CurMethodDef || !CurMethodDef->isInstance()) return 0;
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001903
Douglas Gregorcd9b46e2008-11-04 14:56:14 +00001904 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
1905 const PointerType *PT = Super->getType()->getAsPointerType();
Chris Lattner0d17f6f2008-06-21 18:04:54 +00001906 assert(PT);
1907 ObjCInterfaceType *IT = cast<ObjCInterfaceType>(PT->getPointeeType());
1908 return IT->getDecl();
1909 }
1910 return 0;
Steve Naroff874e2322007-11-15 10:28:18 +00001911}
1912
1913// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00001914QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00001915 if (!SuperStructDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001916 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00001917 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00001918 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00001919 QualType FieldTypes[2];
1920
1921 // struct objc_object *receiver;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001922 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00001923 // struct objc_class *super;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001924 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff874e2322007-11-15 10:28:18 +00001925 // Create fields
1926 FieldDecl *FieldDecls[2];
1927
1928 for (unsigned i = 0; i < 2; ++i)
Chris Lattnerb048c982008-04-06 04:47:34 +00001929 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00001930 FieldTypes[i]);
Steve Naroff874e2322007-11-15 10:28:18 +00001931
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001932 SuperStructDecl->defineBody(*Context, FieldDecls, 4);
Steve Naroff874e2322007-11-15 10:28:18 +00001933 }
1934 return Context->getTagDeclType(SuperStructDecl);
1935}
1936
Steve Naroffb29b4272008-04-14 22:03:09 +00001937QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001938 if (!ConstantStringDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001939 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00001940 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00001941 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001942 QualType FieldTypes[4];
1943
1944 // struct objc_object *receiver;
1945 FieldTypes[0] = Context->getObjCIdType();
1946 // int flags;
1947 FieldTypes[1] = Context->IntTy;
1948 // char *str;
1949 FieldTypes[2] = Context->getPointerType(Context->CharTy);
1950 // long length;
1951 FieldTypes[3] = Context->LongTy;
1952 // Create fields
Steve Naroff9630ec52008-03-27 22:59:54 +00001953 FieldDecl *FieldDecls[4];
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001954
1955 for (unsigned i = 0; i < 4; ++i)
Chris Lattnerb048c982008-04-06 04:47:34 +00001956 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00001957 FieldTypes[i]);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001958
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001959 ConstantStringDecl->defineBody(*Context, FieldDecls, 4);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001960 }
1961 return Context->getTagDeclType(ConstantStringDecl);
1962}
1963
Steve Naroffb29b4272008-04-14 22:03:09 +00001964Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001965 if (!SelGetUidFunctionDecl)
1966 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001967 if (!MsgSendFunctionDecl)
1968 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00001969 if (!MsgSendSuperFunctionDecl)
1970 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001971 if (!MsgSendStretFunctionDecl)
1972 SynthMsgSendStretFunctionDecl();
1973 if (!MsgSendSuperStretFunctionDecl)
1974 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001975 if (!MsgSendFpretFunctionDecl)
1976 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001977 if (!GetClassFunctionDecl)
1978 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001979 if (!GetMetaClassFunctionDecl)
1980 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001981
Steve Naroff874e2322007-11-15 10:28:18 +00001982 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001983 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1984 // May need to use objc_msgSend_stret() as well.
1985 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001986 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001987 QualType resultType = mDecl->getResultType();
Chris Lattner8b51fd72008-07-26 22:36:27 +00001988 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001989 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00001990 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001991 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001992 }
Steve Naroff874e2322007-11-15 10:28:18 +00001993
Steve Naroff934f2762007-10-24 22:48:43 +00001994 // Synthesize a call to objc_msgSend().
1995 llvm::SmallVector<Expr*, 8> MsgExprs;
1996 IdentifierInfo *clsName = Exp->getClassName();
1997
1998 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1999 if (clsName) { // class message.
Steve Narofffc93d522008-07-24 19:44:33 +00002000 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2001 // the 'super' idiom within a class method.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002002 if (!strcmp(clsName->getName(), "super")) {
2003 MsgSendFlavor = MsgSendSuperFunctionDecl;
2004 if (MsgSendStretFlavor)
2005 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2006 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2007
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002008 ObjCInterfaceDecl *SuperDecl =
Steve Naroff54055232008-10-27 17:20:55 +00002009 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002010
2011 llvm::SmallVector<Expr*, 4> InitExprs;
2012
2013 // set the receiver to self, the first argument to all methods.
Chris Lattner41110242008-06-17 18:05:57 +00002014 InitExprs.push_back(new DeclRefExpr(
Steve Naroff54055232008-10-27 17:20:55 +00002015 CurMethodDef->getSelfDecl(),
Chris Lattner41110242008-06-17 18:05:57 +00002016 Context->getObjCIdType(),
2017 SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002018 llvm::SmallVector<Expr*, 8> ClsExprs;
2019 QualType argType = Context->getPointerType(Context->CharTy);
2020 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2021 SuperDecl->getIdentifier()->getLength(),
2022 false, argType, SourceLocation(),
2023 SourceLocation()));
2024 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2025 &ClsExprs[0],
2026 ClsExprs.size());
2027 // To turn off a warning, type-cast to 'id'
Douglas Gregor49badde2008-10-27 19:41:14 +00002028 InitExprs.push_back( // set 'super class', using objc_getClass().
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002029 new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002030 Cls, Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002031 SourceLocation(), SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002032 // struct objc_super
2033 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00002034 Expr *SuperRep;
Steve Naroffc0a123c2008-03-11 17:37:02 +00002035
Steve Naroff23f41272008-03-11 18:14:26 +00002036 if (LangOpts.Microsoft) {
2037 SynthSuperContructorFunctionDecl();
2038 // Simulate a contructor call...
2039 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2040 superType, SourceLocation());
2041 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2042 superType, SourceLocation());
2043 } else {
2044 // (struct objc_super) { <exprs from above> }
2045 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2046 &InitExprs[0], InitExprs.size(),
Chris Lattner418f6c72008-10-26 23:43:26 +00002047 SourceLocation(), false);
2048 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE,
2049 false);
Steve Naroff23f41272008-03-11 18:14:26 +00002050 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002051 // struct objc_super *
2052 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2053 Context->getPointerType(SuperRep->getType()),
2054 SourceLocation());
2055 MsgExprs.push_back(Unop);
2056 } else {
2057 llvm::SmallVector<Expr*, 8> ClsExprs;
2058 QualType argType = Context->getPointerType(Context->CharTy);
2059 ClsExprs.push_back(new StringLiteral(clsName->getName(),
2060 clsName->getLength(),
2061 false, argType, SourceLocation(),
2062 SourceLocation()));
2063 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2064 &ClsExprs[0],
2065 ClsExprs.size());
2066 MsgExprs.push_back(Cls);
2067 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002068 } else { // instance message.
2069 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00002070
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002071 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00002072 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002073 if (MsgSendStretFlavor)
2074 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00002075 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2076
2077 llvm::SmallVector<Expr*, 4> InitExprs;
2078
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002079 InitExprs.push_back(
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002080 new CStyleCastExpr(Context->getObjCIdType(),
Steve Naroff54055232008-10-27 17:20:55 +00002081 new DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Narofff616ebb2008-07-16 22:35:27 +00002082 Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002083 SourceLocation()),
2084 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002085 SourceLocation(), SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00002086
2087 llvm::SmallVector<Expr*, 8> ClsExprs;
2088 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002089 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2090 SuperDecl->getIdentifier()->getLength(),
Steve Naroff874e2322007-11-15 10:28:18 +00002091 false, argType, SourceLocation(),
2092 SourceLocation()));
2093 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002094 &ClsExprs[0],
2095 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00002096 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002097 InitExprs.push_back(
Douglas Gregor49badde2008-10-27 19:41:14 +00002098 // set 'super class', using objc_getClass().
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002099 new CStyleCastExpr(Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002100 Cls, Context->getObjCIdType(), SourceLocation(), SourceLocation()));
Steve Naroff874e2322007-11-15 10:28:18 +00002101 // struct objc_super
2102 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00002103 Expr *SuperRep;
2104
2105 if (LangOpts.Microsoft) {
2106 SynthSuperContructorFunctionDecl();
2107 // Simulate a contructor call...
2108 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2109 superType, SourceLocation());
2110 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2111 superType, SourceLocation());
2112 } else {
2113 // (struct objc_super) { <exprs from above> }
2114 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2115 &InitExprs[0], InitExprs.size(),
Chris Lattner418f6c72008-10-26 23:43:26 +00002116 SourceLocation(), false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002117 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
2118 }
Steve Naroff874e2322007-11-15 10:28:18 +00002119 // struct objc_super *
2120 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2121 Context->getPointerType(SuperRep->getType()),
2122 SourceLocation());
2123 MsgExprs.push_back(Unop);
2124 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002125 // Remove all type-casts because it may contain objc-style types; e.g.
2126 // Foo<Proto> *.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002127 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002128 recExpr = CE->getSubExpr();
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002129 recExpr = new CStyleCastExpr(Context->getObjCIdType(), recExpr,
Douglas Gregor49badde2008-10-27 19:41:14 +00002130 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002131 SourceLocation(), SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00002132 MsgExprs.push_back(recExpr);
2133 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002134 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00002135 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002136 llvm::SmallVector<Expr*, 8> SelExprs;
2137 QualType argType = Context->getPointerType(Context->CharTy);
2138 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
2139 Exp->getSelector().getName().size(),
2140 false, argType, SourceLocation(),
2141 SourceLocation()));
2142 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2143 &SelExprs[0], SelExprs.size());
2144 MsgExprs.push_back(SelExp);
2145
2146 // Now push any user supplied arguments.
2147 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002148 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002149 // Make all implicit casts explicit...ICE comes in handy:-)
2150 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2151 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregor49badde2008-10-27 19:41:14 +00002152 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002153 ? Context->getObjCIdType()
Douglas Gregor49badde2008-10-27 19:41:14 +00002154 : ICE->getType();
Steve Naroffb2f9e512008-11-03 23:29:32 +00002155 userExpr = new CStyleCastExpr(type, userExpr, type, SourceLocation(), SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002156 }
2157 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002158 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002159 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002160 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002161 userExpr = CE->getSubExpr();
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002162 userExpr = new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002163 userExpr, Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002164 SourceLocation(), SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002165 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00002166 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002167 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00002168 // We've transferred the ownership to MsgExprs. Null out the argument in
2169 // the original expression, since we will delete it below.
2170 Exp->setArg(i, 0);
2171 }
Steve Naroffab972d32007-11-04 22:37:50 +00002172 // Generate the funky cast.
2173 CastExpr *cast;
2174 llvm::SmallVector<QualType, 8> ArgTypes;
2175 QualType returnType;
2176
2177 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002178 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2179 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2180 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002181 ArgTypes.push_back(Context->getObjCIdType());
2182 ArgTypes.push_back(Context->getObjCSelType());
2183 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002184 // Push any user argument types.
Chris Lattner58cce3b2008-03-16 01:07:14 +00002185 for (unsigned i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002186 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
2187 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002188 : mDecl->getParamDecl(i)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00002189 // Make sure we convert "t (^)(...)" to "t (*)(...)".
2190 if (isBlockPointerType(t)) {
2191 const BlockPointerType *BPT = t->getAsBlockPointerType();
2192 t = Context->getPointerType(BPT->getPointeeType());
2193 }
Steve Naroff352336b2007-11-05 14:36:37 +00002194 ArgTypes.push_back(t);
2195 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002196 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
2197 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00002198 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002199 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002200 }
2201 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002202 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00002203
2204 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002205 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
2206 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002207
2208 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2209 // If we don't do this cast, we get the following bizarre warning/note:
2210 // xx.m:13: warning: function called through a non-compatible type
2211 // xx.m:13: note: if this code is reached, the program will abort
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002212 cast = new CStyleCastExpr(Context->getPointerType(Context->VoidTy), DRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002213 Context->getPointerType(Context->VoidTy),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002214 SourceLocation(), SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00002215
Steve Naroffab972d32007-11-04 22:37:50 +00002216 // Now do the "normal" pointer to function cast.
2217 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002218 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00002219 // If we don't have a method decl, force a variadic cast.
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002220 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Naroffab972d32007-11-04 22:37:50 +00002221 castType = Context->getPointerType(castType);
Steve Naroffb2f9e512008-11-03 23:29:32 +00002222 cast = new CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002223
2224 // Don't forget the parens to enforce the proper binding.
2225 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2226
2227 const FunctionType *FT = msgSendType->getAsFunctionType();
2228 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2229 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002230 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002231 if (MsgSendStretFlavor) {
2232 // We have the method which returns a struct/union. Must also generate
2233 // call to objc_msgSend_stret and hang both varieties on a conditional
2234 // expression which dictate which one to envoke depending on size of
2235 // method's return type.
2236
2237 // Create a reference to the objc_msgSend_stret() declaration.
2238 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
2239 SourceLocation());
2240 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002241 cast = new CStyleCastExpr(Context->getPointerType(Context->VoidTy), STDRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002242 Context->getPointerType(Context->VoidTy),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002243 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002244 // Now do the "normal" pointer to function cast.
2245 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002246 &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002247 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002248 castType = Context->getPointerType(castType);
Steve Naroffb2f9e512008-11-03 23:29:32 +00002249 cast = new CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002250
2251 // Don't forget the parens to enforce the proper binding.
2252 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2253
2254 FT = msgSendType->getAsFunctionType();
2255 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2256 FT->getResultType(), SourceLocation());
2257
2258 // Build sizeof(returnType)
Sebastian Redl05189992008-11-11 17:56:53 +00002259 SizeOfAlignOfExpr *sizeofExpr = new SizeOfAlignOfExpr(true, true,
2260 returnType.getAsOpaquePtr(),
2261 Context->getSizeType(),
2262 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002263 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2264 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2265 // For X86 it is more complicated and some kind of target specific routine
2266 // is needed to decide what to do.
Chris Lattner98be4942008-03-05 18:54:05 +00002267 unsigned IntSize =
2268 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002269 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2270 Context->IntTy,
2271 SourceLocation());
2272 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2273 BinaryOperator::LE,
2274 Context->IntTy,
2275 SourceLocation());
2276 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2277 ConditionalOperator *CondExpr =
2278 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002279 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002280 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002281 return ReplacingStmt;
2282}
2283
Steve Naroffb29b4272008-04-14 22:03:09 +00002284Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002285 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff80c28552008-10-27 20:54:44 +00002286
Steve Naroff934f2762007-10-24 22:48:43 +00002287 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002288 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff934f2762007-10-24 22:48:43 +00002289
Chris Lattnere64b7772007-10-24 16:57:36 +00002290 delete Exp;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002291 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002292}
2293
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002294/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2295/// call to objc_getProtocol("proto-name").
Steve Naroffb29b4272008-04-14 22:03:09 +00002296Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002297 if (!GetProtocolFunctionDecl)
2298 SynthGetProtocolFunctionDecl();
2299 // Create a call to objc_getProtocol("ProtocolName").
2300 llvm::SmallVector<Expr*, 8> ProtoExprs;
2301 QualType argType = Context->getPointerType(Context->CharTy);
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002302 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getIdentifierName(),
2303 strlen(Exp->getProtocol()->getIdentifierName()),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002304 false, argType, SourceLocation(),
2305 SourceLocation()));
2306 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2307 &ProtoExprs[0],
2308 ProtoExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002309 ReplaceStmt(Exp, ProtoExp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002310 delete Exp;
2311 return ProtoExp;
2312
2313}
2314
Steve Naroffbaf58c32008-05-31 14:15:04 +00002315bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
2316 const char *endBuf) {
2317 while (startBuf < endBuf) {
2318 if (*startBuf == '#') {
2319 // Skip whitespace.
2320 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2321 ;
2322 if (!strncmp(startBuf, "if", strlen("if")) ||
2323 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2324 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2325 !strncmp(startBuf, "define", strlen("define")) ||
2326 !strncmp(startBuf, "undef", strlen("undef")) ||
2327 !strncmp(startBuf, "else", strlen("else")) ||
2328 !strncmp(startBuf, "elif", strlen("elif")) ||
2329 !strncmp(startBuf, "endif", strlen("endif")) ||
2330 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2331 !strncmp(startBuf, "include", strlen("include")) ||
2332 !strncmp(startBuf, "import", strlen("import")) ||
2333 !strncmp(startBuf, "include_next", strlen("include_next")))
2334 return true;
2335 }
2336 startBuf++;
2337 }
2338 return false;
2339}
2340
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002341/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002342/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00002343void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002344 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002345 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002346 assert(CDecl->getIdentifierName() &&
2347 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002348 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002349 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002350 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002351 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002352 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00002353 SourceLocation LocStart = CDecl->getLocStart();
2354 SourceLocation LocEnd = CDecl->getLocEnd();
2355
2356 const char *startBuf = SM->getCharacterData(LocStart);
2357 const char *endBuf = SM->getCharacterData(LocEnd);
Steve Naroffbaf58c32008-05-31 14:15:04 +00002358
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002359 // If no ivars and no root or if its root, directly or indirectly,
2360 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002361 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2362 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002363 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattneraadaf782008-01-31 19:51:04 +00002364 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002365 return;
2366 }
2367
2368 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002369 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002370 Result += "\nstruct ";
2371 Result += CDecl->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002372 if (LangOpts.Microsoft)
2373 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00002374
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002375 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002376 const char *cursor = strchr(startBuf, '{');
2377 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002378 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00002379 // If the buffer contains preprocessor directives, we do more fine-grained
2380 // rewrites. This is intended to fix code that looks like (which occurs in
2381 // NSURL.h, for example):
2382 //
2383 // #ifdef XYZ
2384 // @interface Foo : NSObject
2385 // #else
2386 // @interface FooBar : NSObject
2387 // #endif
2388 // {
2389 // int i;
2390 // }
2391 // @end
2392 //
2393 // This clause is segregated to avoid breaking the common case.
2394 if (BufferContainsPPDirectives(startBuf, cursor)) {
2395 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
2396 CDecl->getClassLoc();
2397 const char *endHeader = SM->getCharacterData(L);
2398 endHeader += Lexer::MeasureTokenLength(L, *SM);
2399
Chris Lattner3db6cae2008-07-21 18:19:38 +00002400 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00002401 // advance to the end of the referenced protocols.
2402 while (endHeader < cursor && *endHeader != '>') endHeader++;
2403 endHeader++;
2404 }
2405 // rewrite the original header
2406 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2407 } else {
2408 // rewrite the original header *without* disturbing the '{'
2409 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
2410 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002411 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002412 Result = "\n struct ";
2413 Result += RCDecl->getName();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002414 Result += "_IMPL ";
2415 Result += RCDecl->getName();
Steve Naroff819173c2008-03-12 21:22:52 +00002416 Result += "_IVARS;\n";
Steve Narofffea763e82007-11-14 19:25:57 +00002417
2418 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002419 SourceLocation OnePastCurly =
2420 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2421 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002422 }
2423 cursor++; // past '{'
2424
2425 // Now comment out any visibility specifiers.
2426 while (cursor < endBuf) {
2427 if (*cursor == '@') {
2428 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002429 // Skip whitespace.
2430 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2431 /*scan*/;
2432
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002433 // FIXME: presence of @public, etc. inside comment results in
2434 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002435 if (!strncmp(cursor, "public", strlen("public")) ||
2436 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00002437 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002438 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002439 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002440 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002441 // FIXME: If there are cases where '<' is used in ivar declaration part
2442 // of user code, then scan the ivar list and use needToScanForQualifiers
2443 // for type checking.
2444 else if (*cursor == '<') {
2445 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002446 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002447 cursor = strchr(cursor, '>');
2448 cursor++;
2449 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002450 InsertText(atLoc, " */", 3);
Steve Naroffced80a82008-10-30 12:09:33 +00002451 } else if (*cursor == '^') { // rewrite block specifier.
2452 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2453 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002454 }
Steve Narofffea763e82007-11-14 19:25:57 +00002455 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002456 }
Steve Narofffea763e82007-11-14 19:25:57 +00002457 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002458 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00002459 } else { // we don't have any instance variables - insert super struct.
2460 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2461 Result += " {\n struct ";
2462 Result += RCDecl->getName();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002463 Result += "_IMPL ";
2464 Result += RCDecl->getName();
Steve Naroff819173c2008-03-12 21:22:52 +00002465 Result += "_IVARS;\n};\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00002466 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002467 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002468 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002469 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00002470 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002471}
2472
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002473// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002474/// class methods.
Steve Naroffb29b4272008-04-14 22:03:09 +00002475void RewriteObjC::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002476 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002477 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002478 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002479 const char *ClassName,
2480 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002481 if (MethodBegin == MethodEnd) return;
2482
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002483 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002484 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002485 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002486 SEL _cmd;
2487 char *method_types;
2488 void *_imp;
2489 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002490 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002491 Result += "\nstruct _objc_method {\n";
2492 Result += "\tSEL _cmd;\n";
2493 Result += "\tchar *method_types;\n";
2494 Result += "\tvoid *_imp;\n";
2495 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002496
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002497 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002498 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002499
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002500 // Build _objc_method_list for class's methods if needed
Steve Naroff946a6932008-03-11 00:12:29 +00002501
2502 /* struct {
2503 struct _objc_method_list *next_method;
2504 int method_count;
2505 struct _objc_method method_list[];
2506 }
2507 */
2508 Result += "\nstatic struct {\n";
2509 Result += "\tstruct _objc_method_list *next_method;\n";
2510 Result += "\tint method_count;\n";
2511 Result += "\tstruct _objc_method method_list[";
2512 Result += utostr(MethodEnd-MethodBegin);
2513 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002514 Result += prefix;
2515 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2516 Result += "_METHODS_";
2517 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002518 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002519 Result += IsInstanceMethod ? "inst" : "cls";
2520 Result += "_meth\")))= ";
2521 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002522
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002523 Result += "\t,{{(SEL)\"";
2524 Result += (*MethodBegin)->getSelector().getName().c_str();
2525 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002526 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002527 Result += "\", \"";
2528 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002529 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002530 Result += MethodInternalNames[*MethodBegin];
2531 Result += "}\n";
2532 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2533 Result += "\t ,{(SEL)\"";
2534 Result += (*MethodBegin)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002535 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002536 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002537 Result += "\", \"";
2538 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002539 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002540 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002541 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002542 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002543 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002544}
2545
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002546/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00002547void RewriteObjC::
2548RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
2549 const char *prefix,
2550 const char *ClassName,
2551 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002552 static bool objc_protocol_methods = false;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002553 if (Protocols.empty()) return;
2554
2555 for (unsigned i = 0; i != Protocols.size(); i++) {
2556 ObjCProtocolDecl *PDecl = Protocols[i];
2557 // Output struct protocol_methods holder of method selector and type.
2558 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
2559 /* struct protocol_methods {
2560 SEL _cmd;
2561 char *method_types;
2562 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002563 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002564 Result += "\nstruct protocol_methods {\n";
2565 Result += "\tSEL _cmd;\n";
2566 Result += "\tchar *method_types;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002567 Result += "};\n";
Steve Narofffbfe8252008-05-06 18:26:51 +00002568
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002569 objc_protocol_methods = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002570 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002571 // Do not synthesize the protocol more than once.
2572 if (ObjCSynthesizedProtocols.count(PDecl))
2573 continue;
2574
2575 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2576 unsigned NumMethods = PDecl->getNumInstanceMethods();
2577 /* struct _objc_protocol_method_list {
2578 int protocol_method_count;
2579 struct protocol_methods protocols[];
2580 }
2581 */
2582 Result += "\nstatic struct {\n";
2583 Result += "\tint protocol_method_count;\n";
2584 Result += "\tstruct protocol_methods protocols[";
2585 Result += utostr(NumMethods);
2586 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
2587 Result += PDecl->getName();
2588 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
2589 "{\n\t" + utostr(NumMethods) + "\n";
2590
2591 // Output instance methods declared in this protocol.
2592 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
2593 E = PDecl->instmeth_end(); I != E; ++I) {
2594 if (I == PDecl->instmeth_begin())
2595 Result += "\t ,{{(SEL)\"";
2596 else
2597 Result += "\t ,{(SEL)\"";
2598 Result += (*I)->getSelector().getName().c_str();
2599 std::string MethodTypeString;
2600 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2601 Result += "\", \"";
2602 Result += MethodTypeString;
2603 Result += "\"}\n";
2604 }
2605 Result += "\t }\n};\n";
2606 }
2607
2608 // Output class methods declared in this protocol.
2609 int NumMethods = PDecl->getNumClassMethods();
2610 if (NumMethods > 0) {
2611 /* struct _objc_protocol_method_list {
2612 int protocol_method_count;
2613 struct protocol_methods protocols[];
2614 }
2615 */
2616 Result += "\nstatic struct {\n";
2617 Result += "\tint protocol_method_count;\n";
2618 Result += "\tstruct protocol_methods protocols[";
2619 Result += utostr(NumMethods);
2620 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
2621 Result += PDecl->getName();
2622 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2623 "{\n\t";
2624 Result += utostr(NumMethods);
2625 Result += "\n";
2626
2627 // Output instance methods declared in this protocol.
2628 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
2629 E = PDecl->classmeth_end(); I != E; ++I) {
2630 if (I == PDecl->classmeth_begin())
2631 Result += "\t ,{{(SEL)\"";
2632 else
2633 Result += "\t ,{(SEL)\"";
2634 Result += (*I)->getSelector().getName().c_str();
2635 std::string MethodTypeString;
2636 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2637 Result += "\", \"";
2638 Result += MethodTypeString;
2639 Result += "\"}\n";
2640 }
2641 Result += "\t }\n};\n";
2642 }
2643
2644 // Output:
2645 /* struct _objc_protocol {
2646 // Objective-C 1.0 extensions
2647 struct _objc_protocol_extension *isa;
2648 char *protocol_name;
2649 struct _objc_protocol **protocol_list;
2650 struct _objc_protocol_method_list *instance_methods;
2651 struct _objc_protocol_method_list *class_methods;
2652 };
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002653 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002654 static bool objc_protocol = false;
2655 if (!objc_protocol) {
2656 Result += "\nstruct _objc_protocol {\n";
2657 Result += "\tstruct _objc_protocol_extension *isa;\n";
2658 Result += "\tchar *protocol_name;\n";
2659 Result += "\tstruct _objc_protocol **protocol_list;\n";
2660 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2661 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2662 Result += "};\n";
2663
2664 objc_protocol = true;
2665 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002666
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002667 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2668 Result += PDecl->getName();
2669 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
2670 "{\n\t0, \"";
2671 Result += PDecl->getName();
2672 Result += "\", 0, ";
2673 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2674 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
2675 Result += PDecl->getName();
2676 Result += ", ";
2677 }
2678 else
2679 Result += "0, ";
2680 if (PDecl->getNumClassMethods() > 0) {
2681 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
2682 Result += PDecl->getName();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002683 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002684 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002685 else
2686 Result += "0\n";
2687 Result += "};\n";
2688
2689 // Mark this protocol as having been generated.
2690 if (!ObjCSynthesizedProtocols.insert(PDecl))
2691 assert(false && "protocol already synthesized");
2692 }
2693 // Output the top lovel protocol meta-data for the class.
2694 /* struct _objc_protocol_list {
2695 struct _objc_protocol_list *next;
2696 int protocol_count;
2697 struct _objc_protocol *class_protocols[];
2698 }
2699 */
2700 Result += "\nstatic struct {\n";
2701 Result += "\tstruct _objc_protocol_list *next;\n";
2702 Result += "\tint protocol_count;\n";
2703 Result += "\tstruct _objc_protocol *class_protocols[";
2704 Result += utostr(Protocols.size());
2705 Result += "];\n} _OBJC_";
2706 Result += prefix;
2707 Result += "_PROTOCOLS_";
2708 Result += ClassName;
2709 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2710 "{\n\t0, ";
2711 Result += utostr(Protocols.size());
2712 Result += "\n";
2713
2714 Result += "\t,{&_OBJC_PROTOCOL_";
2715 Result += Protocols[0]->getName();
2716 Result += " \n";
2717
2718 for (unsigned i = 1; i != Protocols.size(); i++) {
2719 Result += "\t ,&_OBJC_PROTOCOL_";
2720 Result += Protocols[i]->getName();
2721 Result += "\n";
2722 }
2723 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002724}
2725
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002726/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002727/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00002728void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002729 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002730 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002731 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002732 ObjCCategoryDecl *CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002733 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2734 CDecl = CDecl->getNextClassCategory())
2735 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2736 break;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002737
Chris Lattnereb44eee2007-12-23 01:40:15 +00002738 std::string FullCategoryName = ClassDecl->getName();
2739 FullCategoryName += '_';
2740 FullCategoryName += IDecl->getName();
2741
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002742 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002743 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002744 true, "CATEGORY_", FullCategoryName.c_str(),
2745 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002746
2747 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002748 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002749 false, "CATEGORY_", FullCategoryName.c_str(),
2750 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002751
2752 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002753 // Null CDecl is case of a category implementation with no category interface
2754 if (CDecl)
Chris Lattner780f3292008-07-21 21:32:27 +00002755 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Chris Lattnereb44eee2007-12-23 01:40:15 +00002756 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002757
2758 /* struct _objc_category {
2759 char *category_name;
2760 char *class_name;
2761 struct _objc_method_list *instance_methods;
2762 struct _objc_method_list *class_methods;
2763 struct _objc_protocol_list *protocols;
2764 // Objective-C 1.0 extensions
2765 uint32_t size; // sizeof (struct _objc_category)
2766 struct _objc_property_list *instance_properties; // category's own
2767 // @property decl.
2768 };
2769 */
2770
2771 static bool objc_category = false;
2772 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002773 Result += "\nstruct _objc_category {\n";
2774 Result += "\tchar *category_name;\n";
2775 Result += "\tchar *class_name;\n";
2776 Result += "\tstruct _objc_method_list *instance_methods;\n";
2777 Result += "\tstruct _objc_method_list *class_methods;\n";
2778 Result += "\tstruct _objc_protocol_list *protocols;\n";
2779 Result += "\tunsigned int size;\n";
2780 Result += "\tstruct _objc_property_list *instance_properties;\n";
2781 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002782 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002783 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002784 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2785 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002786 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002787 Result += IDecl->getName();
2788 Result += "\"\n\t, \"";
2789 Result += ClassDecl->getName();
2790 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002791
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002792 if (IDecl->getNumInstanceMethods() > 0) {
2793 Result += "\t, (struct _objc_method_list *)"
2794 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2795 Result += FullCategoryName;
2796 Result += "\n";
2797 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002798 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002799 Result += "\t, 0\n";
2800 if (IDecl->getNumClassMethods() > 0) {
2801 Result += "\t, (struct _objc_method_list *)"
2802 "&_OBJC_CATEGORY_CLASS_METHODS_";
2803 Result += FullCategoryName;
2804 Result += "\n";
2805 }
2806 else
2807 Result += "\t, 0\n";
2808
Chris Lattner780f3292008-07-21 21:32:27 +00002809 if (CDecl && !CDecl->getReferencedProtocols().empty()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002810 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2811 Result += FullCategoryName;
2812 Result += "\n";
2813 }
2814 else
2815 Result += "\t, 0\n";
2816 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002817}
2818
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002819/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2820/// ivar offset.
Steve Naroffb29b4272008-04-14 22:03:09 +00002821void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002822 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002823 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00002824 if (ivar->isBitField()) {
2825 // FIXME: The hack below doesn't work for bitfields. For now, we simply
2826 // place all bitfields at offset 0.
2827 Result += "0";
2828 } else {
2829 Result += "__OFFSETOFIVAR__(struct ";
2830 Result += IDecl->getName();
2831 if (LangOpts.Microsoft)
2832 Result += "_IMPL";
2833 Result += ", ";
2834 Result += ivar->getName();
2835 Result += ")";
2836 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002837}
2838
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002839//===----------------------------------------------------------------------===//
2840// Meta Data Emission
2841//===----------------------------------------------------------------------===//
2842
Steve Naroffb29b4272008-04-14 22:03:09 +00002843void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002844 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002845 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002846
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002847 // Explictly declared @interface's are already synthesized.
2848 if (CDecl->ImplicitInterfaceDecl()) {
2849 // FIXME: Implementation of a class with no @interface (legacy) doese not
2850 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002851 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002852 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002853
Chris Lattnerbe6df082007-12-12 07:56:42 +00002854 // Build _objc_ivar_list metadata for classes ivars if needed
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002855 unsigned NumIvars = !IDecl->ivar_empty()
2856 ? IDecl->ivar_size()
2857 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002858 if (NumIvars > 0) {
2859 static bool objc_ivar = false;
2860 if (!objc_ivar) {
2861 /* struct _objc_ivar {
2862 char *ivar_name;
2863 char *ivar_type;
2864 int ivar_offset;
2865 };
2866 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002867 Result += "\nstruct _objc_ivar {\n";
2868 Result += "\tchar *ivar_name;\n";
2869 Result += "\tchar *ivar_type;\n";
2870 Result += "\tint ivar_offset;\n";
2871 Result += "};\n";
2872
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002873 objc_ivar = true;
2874 }
2875
Steve Naroff946a6932008-03-11 00:12:29 +00002876 /* struct {
2877 int ivar_count;
2878 struct _objc_ivar ivar_list[nIvars];
2879 };
2880 */
2881 Result += "\nstatic struct {\n";
2882 Result += "\tint ivar_count;\n";
2883 Result += "\tstruct _objc_ivar ivar_list[";
2884 Result += utostr(NumIvars);
2885 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002886 Result += IDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002887 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002888 "{\n\t";
2889 Result += utostr(NumIvars);
2890 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002891
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002892 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002893 if (!IDecl->ivar_empty()) {
Chris Lattnerbe6df082007-12-12 07:56:42 +00002894 IVI = IDecl->ivar_begin();
2895 IVE = IDecl->ivar_end();
2896 } else {
2897 IVI = CDecl->ivar_begin();
2898 IVE = CDecl->ivar_end();
2899 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002900 Result += "\t,{{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002901 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002902 Result += "\", \"";
2903 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002904 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002905 Result += StrEncoding;
2906 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002907 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002908 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002909 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002910 Result += "\t ,{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002911 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002912 Result += "\", \"";
2913 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002914 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002915 Result += StrEncoding;
2916 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002917 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002918 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002919 }
2920
2921 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002922 }
2923
2924 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002925 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002926 true, "", IDecl->getIdentifierName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002927
2928 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002929 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002930 false, "", IDecl->getIdentifierName(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002931
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002932 // Protocols referenced in class declaration?
Chris Lattner780f3292008-07-21 21:32:27 +00002933 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002934 "CLASS", CDecl->getIdentifierName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002935
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002936
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002937 // Declaration of class/meta-class metadata
2938 /* struct _objc_class {
2939 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002940 const char *super_class_name;
2941 char *name;
2942 long version;
2943 long info;
2944 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002945 struct _objc_ivar_list *ivars;
2946 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002947 struct objc_cache *cache;
2948 struct objc_protocol_list *protocols;
2949 const char *ivar_layout;
2950 struct _objc_class_ext *ext;
2951 };
2952 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002953 static bool objc_class = false;
2954 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002955 Result += "\nstruct _objc_class {\n";
2956 Result += "\tstruct _objc_class *isa;\n";
2957 Result += "\tconst char *super_class_name;\n";
2958 Result += "\tchar *name;\n";
2959 Result += "\tlong version;\n";
2960 Result += "\tlong info;\n";
2961 Result += "\tlong instance_size;\n";
2962 Result += "\tstruct _objc_ivar_list *ivars;\n";
2963 Result += "\tstruct _objc_method_list *methods;\n";
2964 Result += "\tstruct objc_cache *cache;\n";
2965 Result += "\tstruct _objc_protocol_list *protocols;\n";
2966 Result += "\tconst char *ivar_layout;\n";
2967 Result += "\tstruct _objc_class_ext *ext;\n";
2968 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002969 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002970 }
2971
2972 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002973 ObjCInterfaceDecl *RootClass = 0;
2974 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002975 while (SuperClass) {
2976 RootClass = SuperClass;
2977 SuperClass = SuperClass->getSuperClass();
2978 }
2979 SuperClass = CDecl->getSuperClass();
2980
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002981 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2982 Result += CDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002983 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002984 "{\n\t(struct _objc_class *)\"";
2985 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2986 Result += "\"";
2987
2988 if (SuperClass) {
2989 Result += ", \"";
2990 Result += SuperClass->getName();
2991 Result += "\", \"";
2992 Result += CDecl->getName();
2993 Result += "\"";
2994 }
2995 else {
2996 Result += ", 0, \"";
2997 Result += CDecl->getName();
2998 Result += "\"";
2999 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003000 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003001 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003002 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffb26d7132007-12-05 21:49:40 +00003003 if (IDecl->getNumClassMethods() > 0) {
Steve Naroff23f41272008-03-11 18:14:26 +00003004 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Steve Naroffb26d7132007-12-05 21:49:40 +00003005 Result += IDecl->getName();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003006 Result += "\n";
3007 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003008 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003009 Result += ", 0\n";
Chris Lattner3db6cae2008-07-21 18:19:38 +00003010 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003011 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003012 Result += CDecl->getName();
3013 Result += ",0,0\n";
3014 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003015 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003016 Result += "\t,0,0,0,0\n";
3017 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003018
3019 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003020 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
3021 Result += CDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00003022 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003023 "{\n\t&_OBJC_METACLASS_";
3024 Result += CDecl->getName();
3025 if (SuperClass) {
3026 Result += ", \"";
3027 Result += SuperClass->getName();
3028 Result += "\", \"";
3029 Result += CDecl->getName();
3030 Result += "\"";
3031 }
3032 else {
3033 Result += ", 0, \"";
3034 Result += CDecl->getName();
3035 Result += "\"";
3036 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003037 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003038 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003039 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003040 Result += ",0";
3041 else {
3042 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003043 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003044 Result += CDecl->getName();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003045 if (LangOpts.Microsoft)
3046 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003047 Result += ")";
3048 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003049 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00003050 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003051 Result += CDecl->getName();
3052 Result += "\n\t";
3053 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003054 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003055 Result += ",0";
3056 if (IDecl->getNumInstanceMethods() > 0) {
Steve Naroff946a6932008-03-11 00:12:29 +00003057 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003058 Result += CDecl->getName();
3059 Result += ", 0\n\t";
3060 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003061 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003062 Result += ",0,0";
Chris Lattner3db6cae2008-07-21 18:19:38 +00003063 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003064 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003065 Result += CDecl->getName();
3066 Result += ", 0,0\n";
3067 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003068 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003069 Result += ",0,0,0\n";
3070 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003071}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003072
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003073/// RewriteImplementations - This routine rewrites all method implementations
3074/// and emits meta-data.
3075
Steve Narofface66252008-11-13 20:07:04 +00003076void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003077 int ClsDefCount = ClassImplementation.size();
3078 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003079
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003080 // Rewrite implemented methods
3081 for (int i = 0; i < ClsDefCount; i++)
3082 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003083
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003084 for (int i = 0; i < CatDefCount; i++)
3085 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00003086}
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003087
Steve Narofface66252008-11-13 20:07:04 +00003088void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3089 int ClsDefCount = ClassImplementation.size();
3090 int CatDefCount = CategoryImplementation.size();
3091
Steve Naroff5df5b762008-05-07 21:23:49 +00003092 // This is needed for determining instance variable offsets.
Steve Naroffa11440b2008-08-05 18:47:23 +00003093 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003094 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003095 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003096 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003097
3098 // For each implemented category, write out all its meta data.
3099 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003100 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003101
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003102 // Write objc_symtab metadata
3103 /*
3104 struct _objc_symtab
3105 {
3106 long sel_ref_cnt;
3107 SEL *refs;
3108 short cls_def_cnt;
3109 short cat_def_cnt;
3110 void *defs[cls_def_cnt + cat_def_cnt];
3111 };
3112 */
3113
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003114 Result += "\nstruct _objc_symtab {\n";
3115 Result += "\tlong sel_ref_cnt;\n";
3116 Result += "\tSEL *refs;\n";
3117 Result += "\tshort cls_def_cnt;\n";
3118 Result += "\tshort cat_def_cnt;\n";
3119 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3120 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003121
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003122 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00003123 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003124 Result += "\t0, 0, " + utostr(ClsDefCount)
3125 + ", " + utostr(CatDefCount) + "\n";
3126 for (int i = 0; i < ClsDefCount; i++) {
3127 Result += "\t,&_OBJC_CLASS_";
3128 Result += ClassImplementation[i]->getName();
3129 Result += "\n";
3130 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003131
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003132 for (int i = 0; i < CatDefCount; i++) {
3133 Result += "\t,&_OBJC_CATEGORY_";
3134 Result += CategoryImplementation[i]->getClassInterface()->getName();
3135 Result += "_";
3136 Result += CategoryImplementation[i]->getName();
3137 Result += "\n";
3138 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003139
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003140 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003141
3142 // Write objc_module metadata
3143
3144 /*
3145 struct _objc_module {
3146 long version;
3147 long size;
3148 const char *name;
3149 struct _objc_symtab *symtab;
3150 }
3151 */
3152
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003153 Result += "\nstruct _objc_module {\n";
3154 Result += "\tlong version;\n";
3155 Result += "\tlong size;\n";
3156 Result += "\tconst char *name;\n";
3157 Result += "\tstruct _objc_symtab *symtab;\n";
3158 Result += "};\n\n";
3159 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00003160 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003161 Result += "\t" + utostr(OBJC_ABI_VERSION) +
3162 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003163 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003164
3165 if (LangOpts.Microsoft) {
3166 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00003167 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003168 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3169 Result += "&_OBJC_MODULES;\n";
3170 Result += "#pragma data_seg(pop)\n\n";
3171 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003172}
Chris Lattner311ff022007-10-16 22:36:42 +00003173
Steve Naroff54055232008-10-27 17:20:55 +00003174std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3175 const char *funcName,
3176 std::string Tag) {
3177 const FunctionType *AFT = CE->getFunctionType();
3178 QualType RT = AFT->getResultType();
3179 std::string StructRef = "struct " + Tag;
3180 std::string S = "static " + RT.getAsString() + " __" +
3181 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003182
Steve Naroff54055232008-10-27 17:20:55 +00003183 BlockDecl *BD = CE->getBlockDecl();
3184
3185 if (isa<FunctionTypeNoProto>(AFT)) {
3186 S += "()";
3187 } else if (BD->param_empty()) {
3188 S += "(" + StructRef + " *__cself)";
3189 } else {
3190 const FunctionTypeProto *FT = cast<FunctionTypeProto>(AFT);
3191 assert(FT && "SynthesizeBlockFunc: No function proto");
3192 S += '(';
3193 // first add the implicit argument.
3194 S += StructRef + " *__cself, ";
3195 std::string ParamStr;
3196 for (BlockDecl::param_iterator AI = BD->param_begin(),
3197 E = BD->param_end(); AI != E; ++AI) {
3198 if (AI != BD->param_begin()) S += ", ";
3199 ParamStr = (*AI)->getName();
3200 (*AI)->getType().getAsStringInternal(ParamStr);
3201 S += ParamStr;
3202 }
3203 if (FT->isVariadic()) {
3204 if (!BD->param_empty()) S += ", ";
3205 S += "...";
3206 }
3207 S += ')';
3208 }
3209 S += " {\n";
3210
3211 // Create local declarations to avoid rewriting all closure decl ref exprs.
3212 // First, emit a declaration for all "by ref" decls.
3213 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3214 E = BlockByRefDecls.end(); I != E; ++I) {
3215 S += " ";
3216 std::string Name = (*I)->getName();
3217 Context->getPointerType((*I)->getType()).getAsStringInternal(Name);
3218 S += Name + " = __cself->" + (*I)->getName() + "; // bound by ref\n";
3219 }
3220 // Next, emit a declaration for all "by copy" declarations.
3221 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3222 E = BlockByCopyDecls.end(); I != E; ++I) {
3223 S += " ";
3224 std::string Name = (*I)->getName();
3225 // Handle nested closure invocation. For example:
3226 //
3227 // void (^myImportedClosure)(void);
3228 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3229 //
3230 // void (^anotherClosure)(void);
3231 // anotherClosure = ^(void) {
3232 // myImportedClosure(); // import and invoke the closure
3233 // };
3234 //
3235 if (isBlockPointerType((*I)->getType()))
3236 S += "struct __block_impl *";
3237 else
3238 (*I)->getType().getAsStringInternal(Name);
3239 S += Name + " = __cself->" + (*I)->getName() + "; // bound by copy\n";
3240 }
3241 std::string RewrittenStr = RewrittenBlockExprs[CE];
3242 const char *cstr = RewrittenStr.c_str();
3243 while (*cstr++ != '{') ;
3244 S += cstr;
3245 S += "\n";
3246 return S;
3247}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003248
Steve Naroff54055232008-10-27 17:20:55 +00003249std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3250 const char *funcName,
3251 std::string Tag) {
3252 std::string StructRef = "struct " + Tag;
3253 std::string S = "static void __";
3254
3255 S += funcName;
3256 S += "_block_copy_" + utostr(i);
3257 S += "(" + StructRef;
3258 S += "*dst, " + StructRef;
3259 S += "*src) {";
3260 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3261 E = ImportedBlockDecls.end(); I != E; ++I) {
3262 S += "_Block_copy_assign(&dst->";
3263 S += (*I)->getName();
3264 S += ", src->";
3265 S += (*I)->getName();
3266 S += ");}";
3267 }
3268 S += "\nstatic void __";
3269 S += funcName;
3270 S += "_block_dispose_" + utostr(i);
3271 S += "(" + StructRef;
3272 S += "*src) {";
3273 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3274 E = ImportedBlockDecls.end(); I != E; ++I) {
3275 S += "_Block_destroy(src->";
3276 S += (*I)->getName();
3277 S += ");";
3278 }
3279 S += "}\n";
3280 return S;
3281}
3282
3283std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3284 bool hasCopyDisposeHelpers) {
Steve Naroffced80a82008-10-30 12:09:33 +00003285 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00003286 std::string Constructor = " " + Tag;
3287
3288 S += " {\n struct __block_impl impl;\n";
3289
3290 if (hasCopyDisposeHelpers)
3291 S += " void *copy;\n void *dispose;\n";
3292
3293 Constructor += "(void *fp";
3294
3295 if (hasCopyDisposeHelpers)
3296 Constructor += ", void *copyHelp, void *disposeHelp";
3297
3298 if (BlockDeclRefs.size()) {
3299 // Output all "by copy" declarations.
3300 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3301 E = BlockByCopyDecls.end(); I != E; ++I) {
3302 S += " ";
3303 std::string FieldName = (*I)->getName();
3304 std::string ArgName = "_" + FieldName;
3305 // Handle nested closure invocation. For example:
3306 //
3307 // void (^myImportedBlock)(void);
3308 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3309 //
3310 // void (^anotherBlock)(void);
3311 // anotherBlock = ^(void) {
3312 // myImportedBlock(); // import and invoke the closure
3313 // };
3314 //
3315 if (isBlockPointerType((*I)->getType())) {
3316 S += "struct __block_impl *";
3317 Constructor += ", void *" + ArgName;
3318 } else {
3319 (*I)->getType().getAsStringInternal(FieldName);
3320 (*I)->getType().getAsStringInternal(ArgName);
3321 Constructor += ", " + ArgName;
3322 }
3323 S += FieldName + ";\n";
3324 }
3325 // Output all "by ref" declarations.
3326 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3327 E = BlockByRefDecls.end(); I != E; ++I) {
3328 S += " ";
3329 std::string FieldName = (*I)->getName();
3330 std::string ArgName = "_" + FieldName;
3331 // Handle nested closure invocation. For example:
3332 //
3333 // void (^myImportedBlock)(void);
3334 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3335 //
3336 // void (^anotherBlock)(void);
3337 // anotherBlock = ^(void) {
3338 // myImportedBlock(); // import and invoke the closure
3339 // };
3340 //
3341 if (isBlockPointerType((*I)->getType())) {
3342 S += "struct __block_impl *";
3343 Constructor += ", void *" + ArgName;
3344 } else {
3345 Context->getPointerType((*I)->getType()).getAsStringInternal(FieldName);
3346 Context->getPointerType((*I)->getType()).getAsStringInternal(ArgName);
3347 Constructor += ", " + ArgName;
3348 }
3349 S += FieldName + "; // by ref\n";
3350 }
3351 // Finish writing the constructor.
3352 // FIXME: handle NSConcreteGlobalBlock.
3353 Constructor += ", int flags=0) {\n";
3354 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3355 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3356
3357 if (hasCopyDisposeHelpers)
3358 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3359
3360 // Initialize all "by copy" arguments.
3361 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3362 E = BlockByCopyDecls.end(); I != E; ++I) {
3363 std::string Name = (*I)->getName();
3364 Constructor += " ";
3365 if (isBlockPointerType((*I)->getType()))
3366 Constructor += Name + " = (struct __block_impl *)_";
3367 else
3368 Constructor += Name + " = _";
3369 Constructor += Name + ";\n";
3370 }
3371 // Initialize all "by ref" arguments.
3372 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3373 E = BlockByRefDecls.end(); I != E; ++I) {
3374 std::string Name = (*I)->getName();
3375 Constructor += " ";
3376 if (isBlockPointerType((*I)->getType()))
3377 Constructor += Name + " = (struct __block_impl *)_";
3378 else
3379 Constructor += Name + " = _";
3380 Constructor += Name + ";\n";
3381 }
3382 } else {
3383 // Finish writing the constructor.
3384 // FIXME: handle NSConcreteGlobalBlock.
3385 Constructor += ", int flags=0) {\n";
3386 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3387 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3388 if (hasCopyDisposeHelpers)
3389 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3390 }
3391 Constructor += " ";
3392 Constructor += "}\n";
3393 S += Constructor;
3394 S += "};\n";
3395 return S;
3396}
3397
3398void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3399 const char *FunName) {
3400 // Insert closures that were part of the function.
3401 for (unsigned i = 0; i < Blocks.size(); i++) {
3402
3403 CollectBlockDeclRefInfo(Blocks[i]);
3404
3405 std::string Tag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
3406
3407 std::string CI = SynthesizeBlockImpl(Blocks[i], Tag,
3408 ImportedBlockDecls.size() > 0);
3409
3410 InsertText(FunLocStart, CI.c_str(), CI.size());
3411
3412 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, Tag);
3413
3414 InsertText(FunLocStart, CF.c_str(), CF.size());
3415
3416 if (ImportedBlockDecls.size()) {
3417 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, Tag);
3418 InsertText(FunLocStart, HF.c_str(), HF.size());
3419 }
3420
3421 BlockDeclRefs.clear();
3422 BlockByRefDecls.clear();
3423 BlockByCopyDecls.clear();
3424 BlockCallExprs.clear();
3425 ImportedBlockDecls.clear();
3426 }
3427 Blocks.clear();
3428 RewrittenBlockExprs.clear();
3429}
3430
3431void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3432 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003433 const char *FuncName = FD->getIdentifierName();
Steve Naroff54055232008-10-27 17:20:55 +00003434
3435 SynthesizeBlockLiterals(FunLocStart, FuncName);
3436}
3437
3438void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00003439 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3440 //SourceLocation FunLocStart = MD->getLocStart();
3441 // FIXME: This hack works around a bug in Rewrite.InsertText().
3442 SourceLocation FunLocStart = MD->getLocStart().getFileLocWithOffset(-1);
Steve Naroff54055232008-10-27 17:20:55 +00003443 std::string FuncName = std::string(MD->getSelector().getName());
3444 // Convert colons to underscores.
3445 std::string::size_type loc = 0;
3446 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3447 FuncName.replace(loc, 1, "_");
3448
3449 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
3450}
3451
3452void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
3453 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3454 CI != E; ++CI)
3455 if (*CI) {
3456 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3457 GetBlockDeclRefExprs(CBE->getBody());
3458 else
3459 GetBlockDeclRefExprs(*CI);
3460 }
3461 // Handle specific things.
3462 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
3463 // FIXME: Handle enums.
3464 if (!isa<FunctionDecl>(CDRE->getDecl()))
3465 BlockDeclRefs.push_back(CDRE);
3466 return;
3467}
3468
3469void RewriteObjC::GetBlockCallExprs(Stmt *S) {
3470 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3471 CI != E; ++CI)
3472 if (*CI) {
3473 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3474 GetBlockCallExprs(CBE->getBody());
3475 else
3476 GetBlockCallExprs(*CI);
3477 }
3478
3479 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
3480 if (CE->getCallee()->getType()->isBlockPointerType()) {
3481 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
3482 }
3483 }
3484 return;
3485}
3486
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003487Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00003488 // Navigate to relevant type information.
3489 const char *closureName = 0;
3490 const BlockPointerType *CPT = 0;
3491
3492 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp->getCallee())) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003493 closureName = DRE->getDecl()->getIdentifierName();
Steve Naroff54055232008-10-27 17:20:55 +00003494 CPT = DRE->getType()->getAsBlockPointerType();
3495 } else if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(Exp->getCallee())) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003496 closureName = CDRE->getDecl()->getIdentifierName();
Steve Naroff54055232008-10-27 17:20:55 +00003497 CPT = CDRE->getType()->getAsBlockPointerType();
3498 } else if (MemberExpr *MExpr = dyn_cast<MemberExpr>(Exp->getCallee())) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003499 closureName = MExpr->getMemberDecl()->getIdentifierName();
Steve Naroff54055232008-10-27 17:20:55 +00003500 CPT = MExpr->getType()->getAsBlockPointerType();
3501 } else {
3502 assert(1 && "RewriteBlockClass: Bad type");
3503 }
3504 assert(CPT && "RewriteBlockClass: Bad type");
3505 const FunctionType *FT = CPT->getPointeeType()->getAsFunctionType();
3506 assert(FT && "RewriteBlockClass: Bad type");
3507 const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(FT);
3508 // FTP will be null for closures that don't take arguments.
3509
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003510 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
3511 SourceLocation(),
3512 &Context->Idents.get("__block_impl"));
3513 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00003514
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003515 // Generate a funky cast.
3516 llvm::SmallVector<QualType, 8> ArgTypes;
3517
3518 // Push the block argument type.
3519 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00003520 if (FTP) {
3521 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003522 E = FTP->arg_type_end(); I && (I != E); ++I) {
3523 QualType t = *I;
3524 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3525 if (isBlockPointerType(t)) {
3526 const BlockPointerType *BPT = t->getAsBlockPointerType();
3527 t = Context->getPointerType(BPT->getPointeeType());
3528 }
3529 ArgTypes.push_back(t);
3530 }
Steve Naroff54055232008-10-27 17:20:55 +00003531 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003532 // Now do the pointer to function cast.
3533 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
3534 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
3535
3536 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Steve Naroff54055232008-10-27 17:20:55 +00003537
Steve Naroffb2f9e512008-11-03 23:29:32 +00003538 CastExpr *BlkCast = new CStyleCastExpr(PtrBlock, Exp->getCallee(), PtrBlock, SourceLocation(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003539 // Don't forget the parens to enforce the proper binding.
3540 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), BlkCast);
3541 //PE->dump();
Steve Naroff54055232008-10-27 17:20:55 +00003542
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003543 FieldDecl *FD = FieldDecl::Create(*Context, SourceLocation(),
3544 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy);
3545 MemberExpr *ME = new MemberExpr(PE, true, FD, SourceLocation(), FD->getType());
3546
Steve Naroffb2f9e512008-11-03 23:29:32 +00003547 CastExpr *FunkCast = new CStyleCastExpr(PtrToFuncCastType, ME, PtrToFuncCastType, SourceLocation(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003548 PE = new ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
3549
3550 llvm::SmallVector<Expr*, 8> BlkExprs;
3551 // Add the implicit argument.
3552 BlkExprs.push_back(BlkCast);
3553 // Add the user arguments.
Steve Naroff54055232008-10-27 17:20:55 +00003554 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3555 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003556 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00003557 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003558 CallExpr *CE = new CallExpr(PE, &BlkExprs[0], BlkExprs.size(), Exp->getType(), SourceLocation());
3559 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00003560}
3561
3562void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003563 Stmt *BlockCall = SynthesizeBlockCall(Exp);
3564 ReplaceStmt(Exp, BlockCall);
Steve Naroff54055232008-10-27 17:20:55 +00003565}
3566
3567void RewriteObjC::RewriteBlockDeclRefExpr(BlockDeclRefExpr *BDRE) {
3568 // FIXME: Add more elaborate code generation required by the ABI.
3569 InsertText(BDRE->getLocStart(), "*", 1);
3570}
3571
Steve Naroffb2f9e512008-11-03 23:29:32 +00003572void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3573 SourceLocation LocStart = CE->getLParenLoc();
3574 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00003575
3576 // Need to avoid trying to rewrite synthesized casts.
3577 if (LocStart.isInvalid())
3578 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00003579 // Need to avoid trying to rewrite casts contained in macros.
3580 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3581 return;
Steve Narofffa15fd92008-10-28 20:29:00 +00003582
Steve Naroff54055232008-10-27 17:20:55 +00003583 const char *startBuf = SM->getCharacterData(LocStart);
3584 const char *endBuf = SM->getCharacterData(LocEnd);
3585
3586 // advance the location to startArgList.
3587 const char *argPtr = startBuf;
3588
3589 while (*argPtr++ && (argPtr < endBuf)) {
3590 switch (*argPtr) {
3591 case '^':
3592 // Replace the '^' with '*'.
3593 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
3594 ReplaceText(LocStart, 1, "*", 1);
3595 break;
3596 }
3597 }
3598 return;
3599}
3600
3601void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
3602 SourceLocation DeclLoc = FD->getLocation();
3603 unsigned parenCount = 0;
3604
3605 // We have 1 or more arguments that have closure pointers.
3606 const char *startBuf = SM->getCharacterData(DeclLoc);
3607 const char *startArgList = strchr(startBuf, '(');
3608
3609 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
3610
3611 parenCount++;
3612 // advance the location to startArgList.
3613 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
3614 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
3615
3616 const char *argPtr = startArgList;
3617
3618 while (*argPtr++ && parenCount) {
3619 switch (*argPtr) {
3620 case '^':
3621 // Replace the '^' with '*'.
3622 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
3623 ReplaceText(DeclLoc, 1, "*", 1);
3624 break;
3625 case '(':
3626 parenCount++;
3627 break;
3628 case ')':
3629 parenCount--;
3630 break;
3631 }
3632 }
3633 return;
3634}
3635
3636bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
3637 const FunctionTypeProto *FTP;
3638 const PointerType *PT = QT->getAsPointerType();
3639 if (PT) {
3640 FTP = PT->getPointeeType()->getAsFunctionTypeProto();
3641 } else {
3642 const BlockPointerType *BPT = QT->getAsBlockPointerType();
3643 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
3644 FTP = BPT->getPointeeType()->getAsFunctionTypeProto();
3645 }
3646 if (FTP) {
3647 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
3648 E = FTP->arg_type_end(); I != E; ++I)
3649 if (isBlockPointerType(*I))
3650 return true;
3651 }
3652 return false;
3653}
3654
3655void RewriteObjC::GetExtentOfArgList(const char *Name,
3656 const char *&LParen, const char *&RParen) {
3657 const char *argPtr = strchr(Name, '(');
3658 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
3659
3660 LParen = argPtr; // output the start.
3661 argPtr++; // skip past the left paren.
3662 unsigned parenCount = 1;
3663
3664 while (*argPtr && parenCount) {
3665 switch (*argPtr) {
3666 case '(': parenCount++; break;
3667 case ')': parenCount--; break;
3668 default: break;
3669 }
3670 if (parenCount) argPtr++;
3671 }
3672 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
3673 RParen = argPtr; // output the end
3674}
3675
3676void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
3677 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3678 RewriteBlockPointerFunctionArgs(FD);
3679 return;
3680 }
3681 // Handle Variables and Typedefs.
3682 SourceLocation DeclLoc = ND->getLocation();
3683 QualType DeclT;
3684 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3685 DeclT = VD->getType();
3686 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
3687 DeclT = TDD->getUnderlyingType();
3688 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
3689 DeclT = FD->getType();
3690 else
3691 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
3692
3693 const char *startBuf = SM->getCharacterData(DeclLoc);
3694 const char *endBuf = startBuf;
3695 // scan backward (from the decl location) for the end of the previous decl.
3696 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
3697 startBuf--;
3698
3699 // *startBuf != '^' if we are dealing with a pointer to function that
3700 // may take block argument types (which will be handled below).
3701 if (*startBuf == '^') {
3702 // Replace the '^' with '*', computing a negative offset.
3703 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
3704 ReplaceText(DeclLoc, 1, "*", 1);
3705 }
3706 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
3707 // Replace the '^' with '*' for arguments.
3708 DeclLoc = ND->getLocation();
3709 startBuf = SM->getCharacterData(DeclLoc);
3710 const char *argListBegin, *argListEnd;
3711 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
3712 while (argListBegin < argListEnd) {
3713 if (*argListBegin == '^') {
3714 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
3715 ReplaceText(CaretLoc, 1, "*", 1);
3716 }
3717 argListBegin++;
3718 }
3719 }
3720 return;
3721}
3722
3723void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
3724 // Add initializers for any closure decl refs.
3725 GetBlockDeclRefExprs(Exp->getBody());
3726 if (BlockDeclRefs.size()) {
3727 // Unique all "by copy" declarations.
3728 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3729 if (!BlockDeclRefs[i]->isByRef())
3730 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
3731 // Unique all "by ref" declarations.
3732 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3733 if (BlockDeclRefs[i]->isByRef()) {
3734 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
3735 }
3736 // Find any imported blocks...they will need special attention.
3737 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3738 if (isBlockPointerType(BlockDeclRefs[i]->getType())) {
Steve Naroff00072682008-11-13 17:40:07 +00003739 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff54055232008-10-27 17:20:55 +00003740 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
3741 }
3742 }
3743}
3744
Steve Narofffa15fd92008-10-28 20:29:00 +00003745FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
3746 IdentifierInfo *ID = &Context->Idents.get(name);
3747 QualType FType = Context->getFunctionTypeNoProto(Context->VoidPtrTy);
3748 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
3749 ID, FType, FunctionDecl::Extern, false, 0);
3750}
3751
Steve Naroff8e2f57a2008-10-29 18:15:37 +00003752Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Narofffa15fd92008-10-28 20:29:00 +00003753 Blocks.push_back(Exp);
3754
3755 CollectBlockDeclRefInfo(Exp);
3756 std::string FuncName;
3757
3758 if (CurFunctionDef)
3759 FuncName = std::string(CurFunctionDef->getName());
3760 else if (CurMethodDef) {
3761 FuncName = std::string(CurMethodDef->getSelector().getName());
3762 // Convert colons to underscores.
3763 std::string::size_type loc = 0;
3764 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3765 FuncName.replace(loc, 1, "_");
Steve Naroff8e2f57a2008-10-29 18:15:37 +00003766 } else if (GlobalVarDecl)
3767 FuncName = std::string(GlobalVarDecl->getName());
Steve Narofffa15fd92008-10-28 20:29:00 +00003768
3769 std::string BlockNumber = utostr(Blocks.size()-1);
3770
3771 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
3772 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
3773
3774 // Get a pointer to the function type so we can cast appropriately.
3775 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
3776
3777 FunctionDecl *FD;
3778 Expr *NewRep;
3779
3780 // Simulate a contructor call...
3781 FD = SynthBlockInitFunctionDecl(Tag.c_str());
3782 DeclRefExpr *DRE = new DeclRefExpr(FD, FType, SourceLocation());
3783
3784 llvm::SmallVector<Expr*, 4> InitExprs;
3785
Steve Narofffdc03722008-10-29 21:23:59 +00003786 // Initialize the block function.
Steve Narofffa15fd92008-10-28 20:29:00 +00003787 FD = SynthBlockInitFunctionDecl(Func.c_str());
3788 DeclRefExpr *Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3789 CastExpr *castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00003790 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00003791 InitExprs.push_back(castExpr);
Steve Narofffa15fd92008-10-28 20:29:00 +00003792
3793 if (ImportedBlockDecls.size()) {
3794 std::string Buf = "__" + FuncName + "_block_copy_" + BlockNumber;
Steve Narofffdc03722008-10-29 21:23:59 +00003795 FD = SynthBlockInitFunctionDecl(Buf.c_str());
3796 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3797 castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00003798 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffdc03722008-10-29 21:23:59 +00003799 InitExprs.push_back(castExpr);
3800
Steve Narofffa15fd92008-10-28 20:29:00 +00003801 Buf = "__" + FuncName + "_block_dispose_" + BlockNumber;
Steve Narofffdc03722008-10-29 21:23:59 +00003802 FD = SynthBlockInitFunctionDecl(Buf.c_str());
3803 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3804 castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00003805 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffdc03722008-10-29 21:23:59 +00003806 InitExprs.push_back(castExpr);
Steve Narofffa15fd92008-10-28 20:29:00 +00003807 }
3808 // Add initializers for any closure decl refs.
3809 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00003810 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00003811 // Output all "by copy" declarations.
3812 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3813 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00003814 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00003815 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003816 FD = SynthBlockInitFunctionDecl((*I)->getIdentifierName());
Steve Narofffdc03722008-10-29 21:23:59 +00003817 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00003818 } else if (isBlockPointerType((*I)->getType())) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003819 FD = SynthBlockInitFunctionDecl((*I)->getIdentifierName());
Steve Narofffdc03722008-10-29 21:23:59 +00003820 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3821 Exp = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00003822 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00003823 } else {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003824 FD = SynthBlockInitFunctionDecl((*I)->getIdentifierName());
Steve Narofffdc03722008-10-29 21:23:59 +00003825 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00003826 }
Steve Narofffdc03722008-10-29 21:23:59 +00003827 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00003828 }
3829 // Output all "by ref" declarations.
3830 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3831 E = BlockByRefDecls.end(); I != E; ++I) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003832 FD = SynthBlockInitFunctionDecl((*I)->getIdentifierName());
Steve Narofffdc03722008-10-29 21:23:59 +00003833 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3834 Exp = new UnaryOperator(Exp, UnaryOperator::AddrOf,
3835 Context->getPointerType(Exp->getType()),
3836 SourceLocation());
Steve Naroff707b0fe2008-11-14 21:36:12 +00003837 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00003838 }
3839 }
Steve Narofffa15fd92008-10-28 20:29:00 +00003840 NewRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
3841 FType, SourceLocation());
3842 NewRep = new UnaryOperator(NewRep, UnaryOperator::AddrOf,
3843 Context->getPointerType(NewRep->getType()),
3844 SourceLocation());
Steve Naroffb2f9e512008-11-03 23:29:32 +00003845 NewRep = new CStyleCastExpr(FType, NewRep, FType, SourceLocation(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00003846 BlockDeclRefs.clear();
3847 BlockByRefDecls.clear();
3848 BlockByCopyDecls.clear();
3849 ImportedBlockDecls.clear();
3850 return NewRep;
3851}
3852
3853//===----------------------------------------------------------------------===//
3854// Function Body / Expression rewriting
3855//===----------------------------------------------------------------------===//
3856
3857Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
3858 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
3859 isa<DoStmt>(S) || isa<ForStmt>(S))
3860 Stmts.push_back(S);
3861 else if (isa<ObjCForCollectionStmt>(S)) {
3862 Stmts.push_back(S);
3863 ObjCBcLabelNo.push_back(++BcLabelCount);
3864 }
3865
3866 SourceRange OrigStmtRange = S->getSourceRange();
3867
3868 // Perform a bottom up rewrite of all children.
3869 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3870 CI != E; ++CI)
3871 if (*CI) {
3872 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
3873 if (newStmt)
3874 *CI = newStmt;
3875 }
3876
3877 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
3878 // Rewrite the block body in place.
3879 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
3880
3881 // Now we snarf the rewritten text and stash it away for later use.
Steve Naroff8e2f57a2008-10-29 18:15:37 +00003882 std::string Str = Rewrite.getRewritenText(BE->getSourceRange());
3883 RewrittenBlockExprs[BE] = Str;
Steve Narofffa15fd92008-10-28 20:29:00 +00003884
3885 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
3886 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00003887 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00003888 return blockTranscribed;
3889 }
3890 // Handle specific things.
3891 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
3892 return RewriteAtEncode(AtEncode);
3893
3894 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
3895 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
3896
3897 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
3898 return RewriteAtSelector(AtSelector);
3899
3900 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
3901 return RewriteObjCStringLiteral(AtString);
3902
3903 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
3904 // Before we rewrite it, put the original message expression in a comment.
3905 SourceLocation startLoc = MessExpr->getLocStart();
3906 SourceLocation endLoc = MessExpr->getLocEnd();
3907
3908 const char *startBuf = SM->getCharacterData(startLoc);
3909 const char *endBuf = SM->getCharacterData(endLoc);
3910
3911 std::string messString;
3912 messString += "// ";
3913 messString.append(startBuf, endBuf-startBuf+1);
3914 messString += "\n";
3915
3916 // FIXME: Missing definition of
3917 // InsertText(clang::SourceLocation, char const*, unsigned int).
3918 // InsertText(startLoc, messString.c_str(), messString.size());
3919 // Tried this, but it didn't work either...
3920 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
3921 return RewriteMessageExpr(MessExpr);
3922 }
3923
3924 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
3925 return RewriteObjCTryStmt(StmtTry);
3926
3927 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
3928 return RewriteObjCSynchronizedStmt(StmtTry);
3929
3930 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
3931 return RewriteObjCThrowStmt(StmtThrow);
3932
3933 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
3934 return RewriteObjCProtocolExpr(ProtocolExp);
3935
3936 if (ObjCForCollectionStmt *StmtForCollection =
3937 dyn_cast<ObjCForCollectionStmt>(S))
3938 return RewriteObjCForCollectionStmt(StmtForCollection,
3939 OrigStmtRange.getEnd());
3940 if (BreakStmt *StmtBreakStmt =
3941 dyn_cast<BreakStmt>(S))
3942 return RewriteBreakStmt(StmtBreakStmt);
3943 if (ContinueStmt *StmtContinueStmt =
3944 dyn_cast<ContinueStmt>(S))
3945 return RewriteContinueStmt(StmtContinueStmt);
3946
3947 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
3948 // and cast exprs.
3949 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
3950 // FIXME: What we're doing here is modifying the type-specifier that
3951 // precedes the first Decl. In the future the DeclGroup should have
3952 // a separate type-specifier that we can rewrite.
3953 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
3954
3955 // Blocks rewrite rules.
3956 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
3957 DI != DE; ++DI) {
Steve Narofffa15fd92008-10-28 20:29:00 +00003958 ScopedDecl *SD = *DI;
3959 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
3960 if (isBlockPointerType(ND->getType()))
3961 RewriteBlockPointerDecl(ND);
3962 else if (ND->getType()->isFunctionPointerType())
3963 CheckFunctionPointerDecl(ND->getType(), ND);
3964 }
3965 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
3966 if (isBlockPointerType(TD->getUnderlyingType()))
3967 RewriteBlockPointerDecl(TD);
3968 else if (TD->getUnderlyingType()->isFunctionPointerType())
3969 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
3970 }
3971 }
3972 }
3973
3974 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
3975 RewriteObjCQualifiedInterfaceTypes(CE);
3976
3977 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
3978 isa<DoStmt>(S) || isa<ForStmt>(S)) {
3979 assert(!Stmts.empty() && "Statement stack is empty");
3980 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
3981 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
3982 && "Statement stack mismatch");
3983 Stmts.pop_back();
3984 }
3985 // Handle blocks rewriting.
3986 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
3987 if (BDRE->isByRef())
3988 RewriteBlockDeclRefExpr(BDRE);
3989 }
3990 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003991 if (CE->getCallee()->getType()->isBlockPointerType()) {
3992 Stmt *BlockCall = SynthesizeBlockCall(CE);
3993 ReplaceStmt(S, BlockCall);
3994 return BlockCall;
3995 }
Steve Narofffa15fd92008-10-28 20:29:00 +00003996 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00003997 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00003998 RewriteCastExpr(CE);
3999 }
4000#if 0
4001 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
4002 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
4003 // Get the new text.
4004 std::string SStr;
4005 llvm::raw_string_ostream Buf(SStr);
4006 Replacement->printPretty(Buf);
4007 const std::string &Str = Buf.str();
4008
4009 printf("CAST = %s\n", &Str[0]);
4010 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4011 delete S;
4012 return Replacement;
4013 }
4014#endif
4015 // Return this stmt unmodified.
4016 return S;
4017}
4018
4019/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4020/// main file of the input.
4021void RewriteObjC::HandleDeclInMainFile(Decl *D) {
4022 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4023 // Since function prototypes don't have ParmDecl's, we check the function
4024 // prototype. This enables us to rewrite function declarations and
4025 // definitions using the same code.
4026 RewriteBlocksInFunctionTypeProto(FD->getType(), FD);
4027
4028 if (Stmt *Body = FD->getBody()) {
4029 CurFunctionDef = FD;
4030 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
4031 // This synthesizes and inserts the block "impl" struct, invoke function,
4032 // and any copy/dispose helper functions.
4033 InsertBlockLiteralsWithinFunction(FD);
4034 CurFunctionDef = 0;
4035 }
4036 return;
4037 }
4038 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4039 if (Stmt *Body = MD->getBody()) {
4040 //Body->dump();
4041 CurMethodDef = MD;
4042 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
4043 InsertBlockLiteralsWithinMethod(MD);
4044 CurMethodDef = 0;
4045 }
4046 }
4047 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
4048 ClassImplementation.push_back(CI);
4049 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
4050 CategoryImplementation.push_back(CI);
4051 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
4052 RewriteForwardClassDecl(CD);
4053 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4054 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004055 if (isBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004056 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004057 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004058 CheckFunctionPointerDecl(VD->getType(), VD);
4059 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00004060 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004061 RewriteCastExpr(CE);
4062 }
4063 }
4064 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004065 if (VD->getInit()) {
4066 GlobalVarDecl = VD;
4067 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Douglas Gregor2e1cd422008-11-17 14:58:09 +00004068 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
4069 VD->getIdentifierName());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004070 GlobalVarDecl = 0;
4071
4072 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00004073 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004074 RewriteCastExpr(CE);
4075 }
4076 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004077 return;
4078 }
4079 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
4080 if (isBlockPointerType(TD->getUnderlyingType()))
4081 RewriteBlockPointerDecl(TD);
4082 else if (TD->getUnderlyingType()->isFunctionPointerType())
4083 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4084 return;
4085 }
4086 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
4087 if (RD->isDefinition()) {
4088 for (RecordDecl::field_const_iterator i = RD->field_begin(),
4089 e = RD->field_end(); i != e; ++i) {
4090 FieldDecl *FD = *i;
4091 if (isBlockPointerType(FD->getType()))
4092 RewriteBlockPointerDecl(FD);
4093 }
4094 }
4095 return;
4096 }
4097 // Nothing yet.
4098}
4099
4100void RewriteObjC::HandleTranslationUnit(TranslationUnit& TU) {
4101 // Get the top-level buffer that this corresponds to.
4102
4103 // Rewrite tabs if we care.
4104 //RewriteTabs();
4105
4106 if (Diags.hasErrorOccurred())
4107 return;
4108
4109 // Create the output file.
4110
4111 llvm::OwningPtr<llvm::raw_ostream> OwnedStream;
4112 llvm::raw_ostream *OutFile;
4113 if (OutFileName == "-") {
4114 OutFile = &llvm::outs();
4115 } else if (!OutFileName.empty()) {
4116 std::string Err;
Daniel Dunbar26fb2722008-11-13 05:09:21 +00004117 OutFile = new llvm::raw_fd_ostream(OutFileName.c_str(), false, Err);
Steve Narofffa15fd92008-10-28 20:29:00 +00004118 OwnedStream.reset(OutFile);
4119 } else if (InFileName == "-") {
4120 OutFile = &llvm::outs();
4121 } else {
4122 llvm::sys::Path Path(InFileName);
4123 Path.eraseSuffix();
4124 Path.appendSuffix("cpp");
4125 std::string Err;
Daniel Dunbar26fb2722008-11-13 05:09:21 +00004126 OutFile = new llvm::raw_fd_ostream(Path.toString().c_str(), false, Err);
Steve Narofffa15fd92008-10-28 20:29:00 +00004127 OwnedStream.reset(OutFile);
4128 }
4129
4130 RewriteInclude();
4131
4132 InsertText(SourceLocation::getFileLoc(MainFileID, 0),
4133 Preamble.c_str(), Preamble.size(), false);
4134
Steve Naroff0aab7962008-11-14 14:10:01 +00004135 if (ClassImplementation.size() || CategoryImplementation.size())
4136 RewriteImplementations();
Steve Narofffa15fd92008-10-28 20:29:00 +00004137
4138 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
4139 // we are done.
4140 if (const RewriteBuffer *RewriteBuf =
4141 Rewrite.getRewriteBufferFor(MainFileID)) {
4142 //printf("Changed:\n");
4143 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4144 } else {
4145 fprintf(stderr, "No changes\n");
4146 }
Steve Narofface66252008-11-13 20:07:04 +00004147
Steve Naroff0aab7962008-11-14 14:10:01 +00004148 if (ClassImplementation.size() || CategoryImplementation.size()) {
4149 // Rewrite Objective-c meta data*
4150 std::string ResultStr;
4151 SynthesizeMetaDataIntoBuffer(ResultStr);
4152 // Emit metadata.
4153 *OutFile << ResultStr;
4154 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004155 OutFile->flush();
4156}
4157