blob: 2903f998a05c5ad83733cf4c3aa73f3a29c9b4e1 [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>
509 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
510 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 += " ";
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001091 elementName = D->getName();
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());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001097 elementName = DR->getDecl()->getName();
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>
Steve Naroffbeaf2992007-11-03 11:27:19 +00001697 if (strcmp(FD->getName(), "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);
2302 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
2303 strlen(Exp->getProtocol()->getName()),
2304 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");
2346 assert(CDecl->getName() && "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002347 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002348 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002349 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002350 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002351 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00002352 SourceLocation LocStart = CDecl->getLocStart();
2353 SourceLocation LocEnd = CDecl->getLocEnd();
2354
2355 const char *startBuf = SM->getCharacterData(LocStart);
2356 const char *endBuf = SM->getCharacterData(LocEnd);
Steve Naroffbaf58c32008-05-31 14:15:04 +00002357
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002358 // If no ivars and no root or if its root, directly or indirectly,
2359 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002360 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2361 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002362 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattneraadaf782008-01-31 19:51:04 +00002363 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002364 return;
2365 }
2366
2367 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002368 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002369 Result += "\nstruct ";
2370 Result += CDecl->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002371 if (LangOpts.Microsoft)
2372 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00002373
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002374 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002375 const char *cursor = strchr(startBuf, '{');
2376 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002377 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00002378 // If the buffer contains preprocessor directives, we do more fine-grained
2379 // rewrites. This is intended to fix code that looks like (which occurs in
2380 // NSURL.h, for example):
2381 //
2382 // #ifdef XYZ
2383 // @interface Foo : NSObject
2384 // #else
2385 // @interface FooBar : NSObject
2386 // #endif
2387 // {
2388 // int i;
2389 // }
2390 // @end
2391 //
2392 // This clause is segregated to avoid breaking the common case.
2393 if (BufferContainsPPDirectives(startBuf, cursor)) {
2394 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
2395 CDecl->getClassLoc();
2396 const char *endHeader = SM->getCharacterData(L);
2397 endHeader += Lexer::MeasureTokenLength(L, *SM);
2398
Chris Lattner3db6cae2008-07-21 18:19:38 +00002399 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00002400 // advance to the end of the referenced protocols.
2401 while (endHeader < cursor && *endHeader != '>') endHeader++;
2402 endHeader++;
2403 }
2404 // rewrite the original header
2405 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2406 } else {
2407 // rewrite the original header *without* disturbing the '{'
2408 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
2409 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002410 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002411 Result = "\n struct ";
2412 Result += RCDecl->getName();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002413 Result += "_IMPL ";
2414 Result += RCDecl->getName();
Steve Naroff819173c2008-03-12 21:22:52 +00002415 Result += "_IVARS;\n";
Steve Narofffea763e82007-11-14 19:25:57 +00002416
2417 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002418 SourceLocation OnePastCurly =
2419 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2420 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002421 }
2422 cursor++; // past '{'
2423
2424 // Now comment out any visibility specifiers.
2425 while (cursor < endBuf) {
2426 if (*cursor == '@') {
2427 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002428 // Skip whitespace.
2429 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2430 /*scan*/;
2431
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002432 // FIXME: presence of @public, etc. inside comment results in
2433 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002434 if (!strncmp(cursor, "public", strlen("public")) ||
2435 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00002436 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002437 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002438 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002439 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002440 // FIXME: If there are cases where '<' is used in ivar declaration part
2441 // of user code, then scan the ivar list and use needToScanForQualifiers
2442 // for type checking.
2443 else if (*cursor == '<') {
2444 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002445 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002446 cursor = strchr(cursor, '>');
2447 cursor++;
2448 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002449 InsertText(atLoc, " */", 3);
Steve Naroffced80a82008-10-30 12:09:33 +00002450 } else if (*cursor == '^') { // rewrite block specifier.
2451 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2452 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002453 }
Steve Narofffea763e82007-11-14 19:25:57 +00002454 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002455 }
Steve Narofffea763e82007-11-14 19:25:57 +00002456 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002457 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00002458 } else { // we don't have any instance variables - insert super struct.
2459 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2460 Result += " {\n struct ";
2461 Result += RCDecl->getName();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002462 Result += "_IMPL ";
2463 Result += RCDecl->getName();
Steve Naroff819173c2008-03-12 21:22:52 +00002464 Result += "_IVARS;\n};\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00002465 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002466 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002467 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002468 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00002469 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002470}
2471
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002472// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002473/// class methods.
Steve Naroffb29b4272008-04-14 22:03:09 +00002474void RewriteObjC::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002475 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002476 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002477 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002478 const char *ClassName,
2479 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002480 if (MethodBegin == MethodEnd) return;
2481
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002482 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002483 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002484 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002485 SEL _cmd;
2486 char *method_types;
2487 void *_imp;
2488 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002489 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002490 Result += "\nstruct _objc_method {\n";
2491 Result += "\tSEL _cmd;\n";
2492 Result += "\tchar *method_types;\n";
2493 Result += "\tvoid *_imp;\n";
2494 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002495
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002496 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002497 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002498
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002499 // Build _objc_method_list for class's methods if needed
Steve Naroff946a6932008-03-11 00:12:29 +00002500
2501 /* struct {
2502 struct _objc_method_list *next_method;
2503 int method_count;
2504 struct _objc_method method_list[];
2505 }
2506 */
2507 Result += "\nstatic struct {\n";
2508 Result += "\tstruct _objc_method_list *next_method;\n";
2509 Result += "\tint method_count;\n";
2510 Result += "\tstruct _objc_method method_list[";
2511 Result += utostr(MethodEnd-MethodBegin);
2512 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002513 Result += prefix;
2514 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2515 Result += "_METHODS_";
2516 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002517 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002518 Result += IsInstanceMethod ? "inst" : "cls";
2519 Result += "_meth\")))= ";
2520 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002521
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002522 Result += "\t,{{(SEL)\"";
2523 Result += (*MethodBegin)->getSelector().getName().c_str();
2524 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002525 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002526 Result += "\", \"";
2527 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002528 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002529 Result += MethodInternalNames[*MethodBegin];
2530 Result += "}\n";
2531 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2532 Result += "\t ,{(SEL)\"";
2533 Result += (*MethodBegin)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002534 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002535 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002536 Result += "\", \"";
2537 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002538 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002539 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002540 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002541 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002542 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002543}
2544
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002545/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00002546void RewriteObjC::
2547RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
2548 const char *prefix,
2549 const char *ClassName,
2550 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002551 static bool objc_protocol_methods = false;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002552 if (Protocols.empty()) return;
2553
2554 for (unsigned i = 0; i != Protocols.size(); i++) {
2555 ObjCProtocolDecl *PDecl = Protocols[i];
2556 // Output struct protocol_methods holder of method selector and type.
2557 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
2558 /* struct protocol_methods {
2559 SEL _cmd;
2560 char *method_types;
2561 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002562 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002563 Result += "\nstruct protocol_methods {\n";
2564 Result += "\tSEL _cmd;\n";
2565 Result += "\tchar *method_types;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002566 Result += "};\n";
Steve Narofffbfe8252008-05-06 18:26:51 +00002567
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002568 objc_protocol_methods = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002569 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002570 // Do not synthesize the protocol more than once.
2571 if (ObjCSynthesizedProtocols.count(PDecl))
2572 continue;
2573
2574 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2575 unsigned NumMethods = PDecl->getNumInstanceMethods();
2576 /* struct _objc_protocol_method_list {
2577 int protocol_method_count;
2578 struct protocol_methods protocols[];
2579 }
2580 */
2581 Result += "\nstatic struct {\n";
2582 Result += "\tint protocol_method_count;\n";
2583 Result += "\tstruct protocol_methods protocols[";
2584 Result += utostr(NumMethods);
2585 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
2586 Result += PDecl->getName();
2587 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
2588 "{\n\t" + utostr(NumMethods) + "\n";
2589
2590 // Output instance methods declared in this protocol.
2591 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
2592 E = PDecl->instmeth_end(); I != E; ++I) {
2593 if (I == PDecl->instmeth_begin())
2594 Result += "\t ,{{(SEL)\"";
2595 else
2596 Result += "\t ,{(SEL)\"";
2597 Result += (*I)->getSelector().getName().c_str();
2598 std::string MethodTypeString;
2599 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2600 Result += "\", \"";
2601 Result += MethodTypeString;
2602 Result += "\"}\n";
2603 }
2604 Result += "\t }\n};\n";
2605 }
2606
2607 // Output class methods declared in this protocol.
2608 int NumMethods = PDecl->getNumClassMethods();
2609 if (NumMethods > 0) {
2610 /* struct _objc_protocol_method_list {
2611 int protocol_method_count;
2612 struct protocol_methods protocols[];
2613 }
2614 */
2615 Result += "\nstatic struct {\n";
2616 Result += "\tint protocol_method_count;\n";
2617 Result += "\tstruct protocol_methods protocols[";
2618 Result += utostr(NumMethods);
2619 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
2620 Result += PDecl->getName();
2621 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2622 "{\n\t";
2623 Result += utostr(NumMethods);
2624 Result += "\n";
2625
2626 // Output instance methods declared in this protocol.
2627 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
2628 E = PDecl->classmeth_end(); I != E; ++I) {
2629 if (I == PDecl->classmeth_begin())
2630 Result += "\t ,{{(SEL)\"";
2631 else
2632 Result += "\t ,{(SEL)\"";
2633 Result += (*I)->getSelector().getName().c_str();
2634 std::string MethodTypeString;
2635 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2636 Result += "\", \"";
2637 Result += MethodTypeString;
2638 Result += "\"}\n";
2639 }
2640 Result += "\t }\n};\n";
2641 }
2642
2643 // Output:
2644 /* struct _objc_protocol {
2645 // Objective-C 1.0 extensions
2646 struct _objc_protocol_extension *isa;
2647 char *protocol_name;
2648 struct _objc_protocol **protocol_list;
2649 struct _objc_protocol_method_list *instance_methods;
2650 struct _objc_protocol_method_list *class_methods;
2651 };
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002652 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002653 static bool objc_protocol = false;
2654 if (!objc_protocol) {
2655 Result += "\nstruct _objc_protocol {\n";
2656 Result += "\tstruct _objc_protocol_extension *isa;\n";
2657 Result += "\tchar *protocol_name;\n";
2658 Result += "\tstruct _objc_protocol **protocol_list;\n";
2659 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2660 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2661 Result += "};\n";
2662
2663 objc_protocol = true;
2664 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002665
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002666 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2667 Result += PDecl->getName();
2668 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
2669 "{\n\t0, \"";
2670 Result += PDecl->getName();
2671 Result += "\", 0, ";
2672 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2673 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
2674 Result += PDecl->getName();
2675 Result += ", ";
2676 }
2677 else
2678 Result += "0, ";
2679 if (PDecl->getNumClassMethods() > 0) {
2680 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
2681 Result += PDecl->getName();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002682 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002683 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002684 else
2685 Result += "0\n";
2686 Result += "};\n";
2687
2688 // Mark this protocol as having been generated.
2689 if (!ObjCSynthesizedProtocols.insert(PDecl))
2690 assert(false && "protocol already synthesized");
2691 }
2692 // Output the top lovel protocol meta-data for the class.
2693 /* struct _objc_protocol_list {
2694 struct _objc_protocol_list *next;
2695 int protocol_count;
2696 struct _objc_protocol *class_protocols[];
2697 }
2698 */
2699 Result += "\nstatic struct {\n";
2700 Result += "\tstruct _objc_protocol_list *next;\n";
2701 Result += "\tint protocol_count;\n";
2702 Result += "\tstruct _objc_protocol *class_protocols[";
2703 Result += utostr(Protocols.size());
2704 Result += "];\n} _OBJC_";
2705 Result += prefix;
2706 Result += "_PROTOCOLS_";
2707 Result += ClassName;
2708 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2709 "{\n\t0, ";
2710 Result += utostr(Protocols.size());
2711 Result += "\n";
2712
2713 Result += "\t,{&_OBJC_PROTOCOL_";
2714 Result += Protocols[0]->getName();
2715 Result += " \n";
2716
2717 for (unsigned i = 1; i != Protocols.size(); i++) {
2718 Result += "\t ,&_OBJC_PROTOCOL_";
2719 Result += Protocols[i]->getName();
2720 Result += "\n";
2721 }
2722 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002723}
2724
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002725/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002726/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00002727void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002728 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002729 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002730 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002731 ObjCCategoryDecl *CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002732 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2733 CDecl = CDecl->getNextClassCategory())
2734 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2735 break;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002736
Chris Lattnereb44eee2007-12-23 01:40:15 +00002737 std::string FullCategoryName = ClassDecl->getName();
2738 FullCategoryName += '_';
2739 FullCategoryName += IDecl->getName();
2740
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002741 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002742 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002743 true, "CATEGORY_", FullCategoryName.c_str(),
2744 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002745
2746 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002747 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002748 false, "CATEGORY_", FullCategoryName.c_str(),
2749 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002750
2751 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002752 // Null CDecl is case of a category implementation with no category interface
2753 if (CDecl)
Chris Lattner780f3292008-07-21 21:32:27 +00002754 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Chris Lattnereb44eee2007-12-23 01:40:15 +00002755 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002756
2757 /* struct _objc_category {
2758 char *category_name;
2759 char *class_name;
2760 struct _objc_method_list *instance_methods;
2761 struct _objc_method_list *class_methods;
2762 struct _objc_protocol_list *protocols;
2763 // Objective-C 1.0 extensions
2764 uint32_t size; // sizeof (struct _objc_category)
2765 struct _objc_property_list *instance_properties; // category's own
2766 // @property decl.
2767 };
2768 */
2769
2770 static bool objc_category = false;
2771 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002772 Result += "\nstruct _objc_category {\n";
2773 Result += "\tchar *category_name;\n";
2774 Result += "\tchar *class_name;\n";
2775 Result += "\tstruct _objc_method_list *instance_methods;\n";
2776 Result += "\tstruct _objc_method_list *class_methods;\n";
2777 Result += "\tstruct _objc_protocol_list *protocols;\n";
2778 Result += "\tunsigned int size;\n";
2779 Result += "\tstruct _objc_property_list *instance_properties;\n";
2780 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002781 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002782 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002783 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2784 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002785 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002786 Result += IDecl->getName();
2787 Result += "\"\n\t, \"";
2788 Result += ClassDecl->getName();
2789 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002790
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002791 if (IDecl->getNumInstanceMethods() > 0) {
2792 Result += "\t, (struct _objc_method_list *)"
2793 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2794 Result += FullCategoryName;
2795 Result += "\n";
2796 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002797 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002798 Result += "\t, 0\n";
2799 if (IDecl->getNumClassMethods() > 0) {
2800 Result += "\t, (struct _objc_method_list *)"
2801 "&_OBJC_CATEGORY_CLASS_METHODS_";
2802 Result += FullCategoryName;
2803 Result += "\n";
2804 }
2805 else
2806 Result += "\t, 0\n";
2807
Chris Lattner780f3292008-07-21 21:32:27 +00002808 if (CDecl && !CDecl->getReferencedProtocols().empty()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002809 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2810 Result += FullCategoryName;
2811 Result += "\n";
2812 }
2813 else
2814 Result += "\t, 0\n";
2815 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002816}
2817
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002818/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2819/// ivar offset.
Steve Naroffb29b4272008-04-14 22:03:09 +00002820void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002821 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002822 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00002823 if (ivar->isBitField()) {
2824 // FIXME: The hack below doesn't work for bitfields. For now, we simply
2825 // place all bitfields at offset 0.
2826 Result += "0";
2827 } else {
2828 Result += "__OFFSETOFIVAR__(struct ";
2829 Result += IDecl->getName();
2830 if (LangOpts.Microsoft)
2831 Result += "_IMPL";
2832 Result += ", ";
2833 Result += ivar->getName();
2834 Result += ")";
2835 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002836}
2837
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002838//===----------------------------------------------------------------------===//
2839// Meta Data Emission
2840//===----------------------------------------------------------------------===//
2841
Steve Naroffb29b4272008-04-14 22:03:09 +00002842void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002843 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002844 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002845
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002846 // Explictly declared @interface's are already synthesized.
2847 if (CDecl->ImplicitInterfaceDecl()) {
2848 // FIXME: Implementation of a class with no @interface (legacy) doese not
2849 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002850 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002851 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002852
Chris Lattnerbe6df082007-12-12 07:56:42 +00002853 // Build _objc_ivar_list metadata for classes ivars if needed
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002854 unsigned NumIvars = !IDecl->ivar_empty()
2855 ? IDecl->ivar_size()
2856 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002857 if (NumIvars > 0) {
2858 static bool objc_ivar = false;
2859 if (!objc_ivar) {
2860 /* struct _objc_ivar {
2861 char *ivar_name;
2862 char *ivar_type;
2863 int ivar_offset;
2864 };
2865 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002866 Result += "\nstruct _objc_ivar {\n";
2867 Result += "\tchar *ivar_name;\n";
2868 Result += "\tchar *ivar_type;\n";
2869 Result += "\tint ivar_offset;\n";
2870 Result += "};\n";
2871
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002872 objc_ivar = true;
2873 }
2874
Steve Naroff946a6932008-03-11 00:12:29 +00002875 /* struct {
2876 int ivar_count;
2877 struct _objc_ivar ivar_list[nIvars];
2878 };
2879 */
2880 Result += "\nstatic struct {\n";
2881 Result += "\tint ivar_count;\n";
2882 Result += "\tstruct _objc_ivar ivar_list[";
2883 Result += utostr(NumIvars);
2884 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002885 Result += IDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002886 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002887 "{\n\t";
2888 Result += utostr(NumIvars);
2889 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002890
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002891 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002892 if (!IDecl->ivar_empty()) {
Chris Lattnerbe6df082007-12-12 07:56:42 +00002893 IVI = IDecl->ivar_begin();
2894 IVE = IDecl->ivar_end();
2895 } else {
2896 IVI = CDecl->ivar_begin();
2897 IVE = CDecl->ivar_end();
2898 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002899 Result += "\t,{{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002900 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002901 Result += "\", \"";
2902 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002903 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002904 Result += StrEncoding;
2905 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002906 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002907 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002908 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002909 Result += "\t ,{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002910 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002911 Result += "\", \"";
2912 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002913 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002914 Result += StrEncoding;
2915 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002916 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002917 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002918 }
2919
2920 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002921 }
2922
2923 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002924 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002925 true, "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002926
2927 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002928 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002929 false, "", IDecl->getName(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002930
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002931 // Protocols referenced in class declaration?
Chris Lattner780f3292008-07-21 21:32:27 +00002932 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002933 "CLASS", CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002934
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002935
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002936 // Declaration of class/meta-class metadata
2937 /* struct _objc_class {
2938 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002939 const char *super_class_name;
2940 char *name;
2941 long version;
2942 long info;
2943 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002944 struct _objc_ivar_list *ivars;
2945 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002946 struct objc_cache *cache;
2947 struct objc_protocol_list *protocols;
2948 const char *ivar_layout;
2949 struct _objc_class_ext *ext;
2950 };
2951 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002952 static bool objc_class = false;
2953 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002954 Result += "\nstruct _objc_class {\n";
2955 Result += "\tstruct _objc_class *isa;\n";
2956 Result += "\tconst char *super_class_name;\n";
2957 Result += "\tchar *name;\n";
2958 Result += "\tlong version;\n";
2959 Result += "\tlong info;\n";
2960 Result += "\tlong instance_size;\n";
2961 Result += "\tstruct _objc_ivar_list *ivars;\n";
2962 Result += "\tstruct _objc_method_list *methods;\n";
2963 Result += "\tstruct objc_cache *cache;\n";
2964 Result += "\tstruct _objc_protocol_list *protocols;\n";
2965 Result += "\tconst char *ivar_layout;\n";
2966 Result += "\tstruct _objc_class_ext *ext;\n";
2967 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002968 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002969 }
2970
2971 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002972 ObjCInterfaceDecl *RootClass = 0;
2973 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002974 while (SuperClass) {
2975 RootClass = SuperClass;
2976 SuperClass = SuperClass->getSuperClass();
2977 }
2978 SuperClass = CDecl->getSuperClass();
2979
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002980 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2981 Result += CDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002982 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002983 "{\n\t(struct _objc_class *)\"";
2984 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2985 Result += "\"";
2986
2987 if (SuperClass) {
2988 Result += ", \"";
2989 Result += SuperClass->getName();
2990 Result += "\", \"";
2991 Result += CDecl->getName();
2992 Result += "\"";
2993 }
2994 else {
2995 Result += ", 0, \"";
2996 Result += CDecl->getName();
2997 Result += "\"";
2998 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002999 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003000 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003001 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffb26d7132007-12-05 21:49:40 +00003002 if (IDecl->getNumClassMethods() > 0) {
Steve Naroff23f41272008-03-11 18:14:26 +00003003 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Steve Naroffb26d7132007-12-05 21:49:40 +00003004 Result += IDecl->getName();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003005 Result += "\n";
3006 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003007 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003008 Result += ", 0\n";
Chris Lattner3db6cae2008-07-21 18:19:38 +00003009 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003010 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003011 Result += CDecl->getName();
3012 Result += ",0,0\n";
3013 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003014 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003015 Result += "\t,0,0,0,0\n";
3016 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003017
3018 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003019 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
3020 Result += CDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00003021 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003022 "{\n\t&_OBJC_METACLASS_";
3023 Result += CDecl->getName();
3024 if (SuperClass) {
3025 Result += ", \"";
3026 Result += SuperClass->getName();
3027 Result += "\", \"";
3028 Result += CDecl->getName();
3029 Result += "\"";
3030 }
3031 else {
3032 Result += ", 0, \"";
3033 Result += CDecl->getName();
3034 Result += "\"";
3035 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003036 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003037 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003038 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003039 Result += ",0";
3040 else {
3041 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003042 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003043 Result += CDecl->getName();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003044 if (LangOpts.Microsoft)
3045 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003046 Result += ")";
3047 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003048 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00003049 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003050 Result += CDecl->getName();
3051 Result += "\n\t";
3052 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003053 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003054 Result += ",0";
3055 if (IDecl->getNumInstanceMethods() > 0) {
Steve Naroff946a6932008-03-11 00:12:29 +00003056 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003057 Result += CDecl->getName();
3058 Result += ", 0\n\t";
3059 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003060 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003061 Result += ",0,0";
Chris Lattner3db6cae2008-07-21 18:19:38 +00003062 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003063 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003064 Result += CDecl->getName();
3065 Result += ", 0,0\n";
3066 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003067 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003068 Result += ",0,0,0\n";
3069 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003070}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003071
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003072/// RewriteImplementations - This routine rewrites all method implementations
3073/// and emits meta-data.
3074
Steve Narofface66252008-11-13 20:07:04 +00003075void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003076 int ClsDefCount = ClassImplementation.size();
3077 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003078
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003079 // Rewrite implemented methods
3080 for (int i = 0; i < ClsDefCount; i++)
3081 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003082
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003083 for (int i = 0; i < CatDefCount; i++)
3084 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00003085}
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003086
Steve Narofface66252008-11-13 20:07:04 +00003087void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3088 int ClsDefCount = ClassImplementation.size();
3089 int CatDefCount = CategoryImplementation.size();
3090
Steve Naroff5df5b762008-05-07 21:23:49 +00003091 // This is needed for determining instance variable offsets.
Steve Naroffa11440b2008-08-05 18:47:23 +00003092 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003093 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003094 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003095 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003096
3097 // For each implemented category, write out all its meta data.
3098 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003099 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003100
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003101 // Write objc_symtab metadata
3102 /*
3103 struct _objc_symtab
3104 {
3105 long sel_ref_cnt;
3106 SEL *refs;
3107 short cls_def_cnt;
3108 short cat_def_cnt;
3109 void *defs[cls_def_cnt + cat_def_cnt];
3110 };
3111 */
3112
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003113 Result += "\nstruct _objc_symtab {\n";
3114 Result += "\tlong sel_ref_cnt;\n";
3115 Result += "\tSEL *refs;\n";
3116 Result += "\tshort cls_def_cnt;\n";
3117 Result += "\tshort cat_def_cnt;\n";
3118 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3119 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003120
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003121 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00003122 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003123 Result += "\t0, 0, " + utostr(ClsDefCount)
3124 + ", " + utostr(CatDefCount) + "\n";
3125 for (int i = 0; i < ClsDefCount; i++) {
3126 Result += "\t,&_OBJC_CLASS_";
3127 Result += ClassImplementation[i]->getName();
3128 Result += "\n";
3129 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003130
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003131 for (int i = 0; i < CatDefCount; i++) {
3132 Result += "\t,&_OBJC_CATEGORY_";
3133 Result += CategoryImplementation[i]->getClassInterface()->getName();
3134 Result += "_";
3135 Result += CategoryImplementation[i]->getName();
3136 Result += "\n";
3137 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003138
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003139 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003140
3141 // Write objc_module metadata
3142
3143 /*
3144 struct _objc_module {
3145 long version;
3146 long size;
3147 const char *name;
3148 struct _objc_symtab *symtab;
3149 }
3150 */
3151
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003152 Result += "\nstruct _objc_module {\n";
3153 Result += "\tlong version;\n";
3154 Result += "\tlong size;\n";
3155 Result += "\tconst char *name;\n";
3156 Result += "\tstruct _objc_symtab *symtab;\n";
3157 Result += "};\n\n";
3158 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00003159 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003160 Result += "\t" + utostr(OBJC_ABI_VERSION) +
3161 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003162 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003163
3164 if (LangOpts.Microsoft) {
3165 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00003166 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003167 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3168 Result += "&_OBJC_MODULES;\n";
3169 Result += "#pragma data_seg(pop)\n\n";
3170 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003171}
Chris Lattner311ff022007-10-16 22:36:42 +00003172
Steve Naroff54055232008-10-27 17:20:55 +00003173std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3174 const char *funcName,
3175 std::string Tag) {
3176 const FunctionType *AFT = CE->getFunctionType();
3177 QualType RT = AFT->getResultType();
3178 std::string StructRef = "struct " + Tag;
3179 std::string S = "static " + RT.getAsString() + " __" +
3180 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003181
Steve Naroff54055232008-10-27 17:20:55 +00003182 BlockDecl *BD = CE->getBlockDecl();
3183
3184 if (isa<FunctionTypeNoProto>(AFT)) {
3185 S += "()";
3186 } else if (BD->param_empty()) {
3187 S += "(" + StructRef + " *__cself)";
3188 } else {
3189 const FunctionTypeProto *FT = cast<FunctionTypeProto>(AFT);
3190 assert(FT && "SynthesizeBlockFunc: No function proto");
3191 S += '(';
3192 // first add the implicit argument.
3193 S += StructRef + " *__cself, ";
3194 std::string ParamStr;
3195 for (BlockDecl::param_iterator AI = BD->param_begin(),
3196 E = BD->param_end(); AI != E; ++AI) {
3197 if (AI != BD->param_begin()) S += ", ";
3198 ParamStr = (*AI)->getName();
3199 (*AI)->getType().getAsStringInternal(ParamStr);
3200 S += ParamStr;
3201 }
3202 if (FT->isVariadic()) {
3203 if (!BD->param_empty()) S += ", ";
3204 S += "...";
3205 }
3206 S += ')';
3207 }
3208 S += " {\n";
3209
3210 // Create local declarations to avoid rewriting all closure decl ref exprs.
3211 // First, emit a declaration for all "by ref" decls.
3212 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3213 E = BlockByRefDecls.end(); I != E; ++I) {
3214 S += " ";
3215 std::string Name = (*I)->getName();
3216 Context->getPointerType((*I)->getType()).getAsStringInternal(Name);
3217 S += Name + " = __cself->" + (*I)->getName() + "; // bound by ref\n";
3218 }
3219 // Next, emit a declaration for all "by copy" declarations.
3220 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3221 E = BlockByCopyDecls.end(); I != E; ++I) {
3222 S += " ";
3223 std::string Name = (*I)->getName();
3224 // Handle nested closure invocation. For example:
3225 //
3226 // void (^myImportedClosure)(void);
3227 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3228 //
3229 // void (^anotherClosure)(void);
3230 // anotherClosure = ^(void) {
3231 // myImportedClosure(); // import and invoke the closure
3232 // };
3233 //
3234 if (isBlockPointerType((*I)->getType()))
3235 S += "struct __block_impl *";
3236 else
3237 (*I)->getType().getAsStringInternal(Name);
3238 S += Name + " = __cself->" + (*I)->getName() + "; // bound by copy\n";
3239 }
3240 std::string RewrittenStr = RewrittenBlockExprs[CE];
3241 const char *cstr = RewrittenStr.c_str();
3242 while (*cstr++ != '{') ;
3243 S += cstr;
3244 S += "\n";
3245 return S;
3246}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003247
Steve Naroff54055232008-10-27 17:20:55 +00003248std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3249 const char *funcName,
3250 std::string Tag) {
3251 std::string StructRef = "struct " + Tag;
3252 std::string S = "static void __";
3253
3254 S += funcName;
3255 S += "_block_copy_" + utostr(i);
3256 S += "(" + StructRef;
3257 S += "*dst, " + StructRef;
3258 S += "*src) {";
3259 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3260 E = ImportedBlockDecls.end(); I != E; ++I) {
3261 S += "_Block_copy_assign(&dst->";
3262 S += (*I)->getName();
3263 S += ", src->";
3264 S += (*I)->getName();
3265 S += ");}";
3266 }
3267 S += "\nstatic void __";
3268 S += funcName;
3269 S += "_block_dispose_" + utostr(i);
3270 S += "(" + StructRef;
3271 S += "*src) {";
3272 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3273 E = ImportedBlockDecls.end(); I != E; ++I) {
3274 S += "_Block_destroy(src->";
3275 S += (*I)->getName();
3276 S += ");";
3277 }
3278 S += "}\n";
3279 return S;
3280}
3281
3282std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3283 bool hasCopyDisposeHelpers) {
Steve Naroffced80a82008-10-30 12:09:33 +00003284 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00003285 std::string Constructor = " " + Tag;
3286
3287 S += " {\n struct __block_impl impl;\n";
3288
3289 if (hasCopyDisposeHelpers)
3290 S += " void *copy;\n void *dispose;\n";
3291
3292 Constructor += "(void *fp";
3293
3294 if (hasCopyDisposeHelpers)
3295 Constructor += ", void *copyHelp, void *disposeHelp";
3296
3297 if (BlockDeclRefs.size()) {
3298 // Output all "by copy" declarations.
3299 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3300 E = BlockByCopyDecls.end(); I != E; ++I) {
3301 S += " ";
3302 std::string FieldName = (*I)->getName();
3303 std::string ArgName = "_" + FieldName;
3304 // Handle nested closure invocation. For example:
3305 //
3306 // void (^myImportedBlock)(void);
3307 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3308 //
3309 // void (^anotherBlock)(void);
3310 // anotherBlock = ^(void) {
3311 // myImportedBlock(); // import and invoke the closure
3312 // };
3313 //
3314 if (isBlockPointerType((*I)->getType())) {
3315 S += "struct __block_impl *";
3316 Constructor += ", void *" + ArgName;
3317 } else {
3318 (*I)->getType().getAsStringInternal(FieldName);
3319 (*I)->getType().getAsStringInternal(ArgName);
3320 Constructor += ", " + ArgName;
3321 }
3322 S += FieldName + ";\n";
3323 }
3324 // Output all "by ref" declarations.
3325 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3326 E = BlockByRefDecls.end(); I != E; ++I) {
3327 S += " ";
3328 std::string FieldName = (*I)->getName();
3329 std::string ArgName = "_" + FieldName;
3330 // Handle nested closure invocation. For example:
3331 //
3332 // void (^myImportedBlock)(void);
3333 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3334 //
3335 // void (^anotherBlock)(void);
3336 // anotherBlock = ^(void) {
3337 // myImportedBlock(); // import and invoke the closure
3338 // };
3339 //
3340 if (isBlockPointerType((*I)->getType())) {
3341 S += "struct __block_impl *";
3342 Constructor += ", void *" + ArgName;
3343 } else {
3344 Context->getPointerType((*I)->getType()).getAsStringInternal(FieldName);
3345 Context->getPointerType((*I)->getType()).getAsStringInternal(ArgName);
3346 Constructor += ", " + ArgName;
3347 }
3348 S += FieldName + "; // by ref\n";
3349 }
3350 // Finish writing the constructor.
3351 // FIXME: handle NSConcreteGlobalBlock.
3352 Constructor += ", int flags=0) {\n";
3353 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3354 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3355
3356 if (hasCopyDisposeHelpers)
3357 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3358
3359 // Initialize all "by copy" arguments.
3360 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3361 E = BlockByCopyDecls.end(); I != E; ++I) {
3362 std::string Name = (*I)->getName();
3363 Constructor += " ";
3364 if (isBlockPointerType((*I)->getType()))
3365 Constructor += Name + " = (struct __block_impl *)_";
3366 else
3367 Constructor += Name + " = _";
3368 Constructor += Name + ";\n";
3369 }
3370 // Initialize all "by ref" arguments.
3371 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3372 E = BlockByRefDecls.end(); I != E; ++I) {
3373 std::string Name = (*I)->getName();
3374 Constructor += " ";
3375 if (isBlockPointerType((*I)->getType()))
3376 Constructor += Name + " = (struct __block_impl *)_";
3377 else
3378 Constructor += Name + " = _";
3379 Constructor += Name + ";\n";
3380 }
3381 } else {
3382 // Finish writing the constructor.
3383 // FIXME: handle NSConcreteGlobalBlock.
3384 Constructor += ", int flags=0) {\n";
3385 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3386 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3387 if (hasCopyDisposeHelpers)
3388 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3389 }
3390 Constructor += " ";
3391 Constructor += "}\n";
3392 S += Constructor;
3393 S += "};\n";
3394 return S;
3395}
3396
3397void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3398 const char *FunName) {
3399 // Insert closures that were part of the function.
3400 for (unsigned i = 0; i < Blocks.size(); i++) {
3401
3402 CollectBlockDeclRefInfo(Blocks[i]);
3403
3404 std::string Tag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
3405
3406 std::string CI = SynthesizeBlockImpl(Blocks[i], Tag,
3407 ImportedBlockDecls.size() > 0);
3408
3409 InsertText(FunLocStart, CI.c_str(), CI.size());
3410
3411 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, Tag);
3412
3413 InsertText(FunLocStart, CF.c_str(), CF.size());
3414
3415 if (ImportedBlockDecls.size()) {
3416 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, Tag);
3417 InsertText(FunLocStart, HF.c_str(), HF.size());
3418 }
3419
3420 BlockDeclRefs.clear();
3421 BlockByRefDecls.clear();
3422 BlockByCopyDecls.clear();
3423 BlockCallExprs.clear();
3424 ImportedBlockDecls.clear();
3425 }
3426 Blocks.clear();
3427 RewrittenBlockExprs.clear();
3428}
3429
3430void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3431 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
3432 const char *FuncName = FD->getName();
3433
3434 SynthesizeBlockLiterals(FunLocStart, FuncName);
3435}
3436
3437void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00003438 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3439 //SourceLocation FunLocStart = MD->getLocStart();
3440 // FIXME: This hack works around a bug in Rewrite.InsertText().
3441 SourceLocation FunLocStart = MD->getLocStart().getFileLocWithOffset(-1);
Steve Naroff54055232008-10-27 17:20:55 +00003442 std::string FuncName = std::string(MD->getSelector().getName());
3443 // Convert colons to underscores.
3444 std::string::size_type loc = 0;
3445 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3446 FuncName.replace(loc, 1, "_");
3447
3448 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
3449}
3450
3451void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
3452 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3453 CI != E; ++CI)
3454 if (*CI) {
3455 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3456 GetBlockDeclRefExprs(CBE->getBody());
3457 else
3458 GetBlockDeclRefExprs(*CI);
3459 }
3460 // Handle specific things.
3461 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
3462 // FIXME: Handle enums.
3463 if (!isa<FunctionDecl>(CDRE->getDecl()))
3464 BlockDeclRefs.push_back(CDRE);
3465 return;
3466}
3467
3468void RewriteObjC::GetBlockCallExprs(Stmt *S) {
3469 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3470 CI != E; ++CI)
3471 if (*CI) {
3472 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3473 GetBlockCallExprs(CBE->getBody());
3474 else
3475 GetBlockCallExprs(*CI);
3476 }
3477
3478 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
3479 if (CE->getCallee()->getType()->isBlockPointerType()) {
3480 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
3481 }
3482 }
3483 return;
3484}
3485
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003486Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00003487 // Navigate to relevant type information.
3488 const char *closureName = 0;
3489 const BlockPointerType *CPT = 0;
3490
3491 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp->getCallee())) {
3492 closureName = DRE->getDecl()->getName();
3493 CPT = DRE->getType()->getAsBlockPointerType();
3494 } else if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(Exp->getCallee())) {
3495 closureName = CDRE->getDecl()->getName();
3496 CPT = CDRE->getType()->getAsBlockPointerType();
3497 } else if (MemberExpr *MExpr = dyn_cast<MemberExpr>(Exp->getCallee())) {
3498 closureName = MExpr->getMemberDecl()->getName();
3499 CPT = MExpr->getType()->getAsBlockPointerType();
3500 } else {
3501 assert(1 && "RewriteBlockClass: Bad type");
3502 }
3503 assert(CPT && "RewriteBlockClass: Bad type");
3504 const FunctionType *FT = CPT->getPointeeType()->getAsFunctionType();
3505 assert(FT && "RewriteBlockClass: Bad type");
3506 const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(FT);
3507 // FTP will be null for closures that don't take arguments.
3508
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003509 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
3510 SourceLocation(),
3511 &Context->Idents.get("__block_impl"));
3512 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00003513
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003514 // Generate a funky cast.
3515 llvm::SmallVector<QualType, 8> ArgTypes;
3516
3517 // Push the block argument type.
3518 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00003519 if (FTP) {
3520 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003521 E = FTP->arg_type_end(); I && (I != E); ++I) {
3522 QualType t = *I;
3523 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3524 if (isBlockPointerType(t)) {
3525 const BlockPointerType *BPT = t->getAsBlockPointerType();
3526 t = Context->getPointerType(BPT->getPointeeType());
3527 }
3528 ArgTypes.push_back(t);
3529 }
Steve Naroff54055232008-10-27 17:20:55 +00003530 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003531 // Now do the pointer to function cast.
3532 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
3533 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
3534
3535 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Steve Naroff54055232008-10-27 17:20:55 +00003536
Steve Naroffb2f9e512008-11-03 23:29:32 +00003537 CastExpr *BlkCast = new CStyleCastExpr(PtrBlock, Exp->getCallee(), PtrBlock, SourceLocation(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003538 // Don't forget the parens to enforce the proper binding.
3539 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), BlkCast);
3540 //PE->dump();
Steve Naroff54055232008-10-27 17:20:55 +00003541
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003542 FieldDecl *FD = FieldDecl::Create(*Context, SourceLocation(),
3543 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy);
3544 MemberExpr *ME = new MemberExpr(PE, true, FD, SourceLocation(), FD->getType());
3545
Steve Naroffb2f9e512008-11-03 23:29:32 +00003546 CastExpr *FunkCast = new CStyleCastExpr(PtrToFuncCastType, ME, PtrToFuncCastType, SourceLocation(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003547 PE = new ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
3548
3549 llvm::SmallVector<Expr*, 8> BlkExprs;
3550 // Add the implicit argument.
3551 BlkExprs.push_back(BlkCast);
3552 // Add the user arguments.
Steve Naroff54055232008-10-27 17:20:55 +00003553 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3554 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003555 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00003556 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003557 CallExpr *CE = new CallExpr(PE, &BlkExprs[0], BlkExprs.size(), Exp->getType(), SourceLocation());
3558 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00003559}
3560
3561void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003562 Stmt *BlockCall = SynthesizeBlockCall(Exp);
3563 ReplaceStmt(Exp, BlockCall);
Steve Naroff54055232008-10-27 17:20:55 +00003564}
3565
3566void RewriteObjC::RewriteBlockDeclRefExpr(BlockDeclRefExpr *BDRE) {
3567 // FIXME: Add more elaborate code generation required by the ABI.
3568 InsertText(BDRE->getLocStart(), "*", 1);
3569}
3570
Steve Naroffb2f9e512008-11-03 23:29:32 +00003571void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3572 SourceLocation LocStart = CE->getLParenLoc();
3573 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00003574
3575 // Need to avoid trying to rewrite synthesized casts.
3576 if (LocStart.isInvalid())
3577 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00003578 // Need to avoid trying to rewrite casts contained in macros.
3579 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3580 return;
Steve Narofffa15fd92008-10-28 20:29:00 +00003581
Steve Naroff54055232008-10-27 17:20:55 +00003582 const char *startBuf = SM->getCharacterData(LocStart);
3583 const char *endBuf = SM->getCharacterData(LocEnd);
3584
3585 // advance the location to startArgList.
3586 const char *argPtr = startBuf;
3587
3588 while (*argPtr++ && (argPtr < endBuf)) {
3589 switch (*argPtr) {
3590 case '^':
3591 // Replace the '^' with '*'.
3592 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
3593 ReplaceText(LocStart, 1, "*", 1);
3594 break;
3595 }
3596 }
3597 return;
3598}
3599
3600void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
3601 SourceLocation DeclLoc = FD->getLocation();
3602 unsigned parenCount = 0;
3603
3604 // We have 1 or more arguments that have closure pointers.
3605 const char *startBuf = SM->getCharacterData(DeclLoc);
3606 const char *startArgList = strchr(startBuf, '(');
3607
3608 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
3609
3610 parenCount++;
3611 // advance the location to startArgList.
3612 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
3613 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
3614
3615 const char *argPtr = startArgList;
3616
3617 while (*argPtr++ && parenCount) {
3618 switch (*argPtr) {
3619 case '^':
3620 // Replace the '^' with '*'.
3621 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
3622 ReplaceText(DeclLoc, 1, "*", 1);
3623 break;
3624 case '(':
3625 parenCount++;
3626 break;
3627 case ')':
3628 parenCount--;
3629 break;
3630 }
3631 }
3632 return;
3633}
3634
3635bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
3636 const FunctionTypeProto *FTP;
3637 const PointerType *PT = QT->getAsPointerType();
3638 if (PT) {
3639 FTP = PT->getPointeeType()->getAsFunctionTypeProto();
3640 } else {
3641 const BlockPointerType *BPT = QT->getAsBlockPointerType();
3642 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
3643 FTP = BPT->getPointeeType()->getAsFunctionTypeProto();
3644 }
3645 if (FTP) {
3646 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
3647 E = FTP->arg_type_end(); I != E; ++I)
3648 if (isBlockPointerType(*I))
3649 return true;
3650 }
3651 return false;
3652}
3653
3654void RewriteObjC::GetExtentOfArgList(const char *Name,
3655 const char *&LParen, const char *&RParen) {
3656 const char *argPtr = strchr(Name, '(');
3657 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
3658
3659 LParen = argPtr; // output the start.
3660 argPtr++; // skip past the left paren.
3661 unsigned parenCount = 1;
3662
3663 while (*argPtr && parenCount) {
3664 switch (*argPtr) {
3665 case '(': parenCount++; break;
3666 case ')': parenCount--; break;
3667 default: break;
3668 }
3669 if (parenCount) argPtr++;
3670 }
3671 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
3672 RParen = argPtr; // output the end
3673}
3674
3675void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
3676 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3677 RewriteBlockPointerFunctionArgs(FD);
3678 return;
3679 }
3680 // Handle Variables and Typedefs.
3681 SourceLocation DeclLoc = ND->getLocation();
3682 QualType DeclT;
3683 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3684 DeclT = VD->getType();
3685 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
3686 DeclT = TDD->getUnderlyingType();
3687 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
3688 DeclT = FD->getType();
3689 else
3690 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
3691
3692 const char *startBuf = SM->getCharacterData(DeclLoc);
3693 const char *endBuf = startBuf;
3694 // scan backward (from the decl location) for the end of the previous decl.
3695 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
3696 startBuf--;
3697
3698 // *startBuf != '^' if we are dealing with a pointer to function that
3699 // may take block argument types (which will be handled below).
3700 if (*startBuf == '^') {
3701 // Replace the '^' with '*', computing a negative offset.
3702 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
3703 ReplaceText(DeclLoc, 1, "*", 1);
3704 }
3705 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
3706 // Replace the '^' with '*' for arguments.
3707 DeclLoc = ND->getLocation();
3708 startBuf = SM->getCharacterData(DeclLoc);
3709 const char *argListBegin, *argListEnd;
3710 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
3711 while (argListBegin < argListEnd) {
3712 if (*argListBegin == '^') {
3713 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
3714 ReplaceText(CaretLoc, 1, "*", 1);
3715 }
3716 argListBegin++;
3717 }
3718 }
3719 return;
3720}
3721
3722void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
3723 // Add initializers for any closure decl refs.
3724 GetBlockDeclRefExprs(Exp->getBody());
3725 if (BlockDeclRefs.size()) {
3726 // Unique all "by copy" declarations.
3727 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3728 if (!BlockDeclRefs[i]->isByRef())
3729 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
3730 // Unique all "by ref" declarations.
3731 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3732 if (BlockDeclRefs[i]->isByRef()) {
3733 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
3734 }
3735 // Find any imported blocks...they will need special attention.
3736 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3737 if (isBlockPointerType(BlockDeclRefs[i]->getType())) {
Steve Naroff00072682008-11-13 17:40:07 +00003738 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff54055232008-10-27 17:20:55 +00003739 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
3740 }
3741 }
3742}
3743
Steve Narofffa15fd92008-10-28 20:29:00 +00003744FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
3745 IdentifierInfo *ID = &Context->Idents.get(name);
3746 QualType FType = Context->getFunctionTypeNoProto(Context->VoidPtrTy);
3747 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
3748 ID, FType, FunctionDecl::Extern, false, 0);
3749}
3750
Steve Naroff8e2f57a2008-10-29 18:15:37 +00003751Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Narofffa15fd92008-10-28 20:29:00 +00003752 Blocks.push_back(Exp);
3753
3754 CollectBlockDeclRefInfo(Exp);
3755 std::string FuncName;
3756
3757 if (CurFunctionDef)
3758 FuncName = std::string(CurFunctionDef->getName());
3759 else if (CurMethodDef) {
3760 FuncName = std::string(CurMethodDef->getSelector().getName());
3761 // Convert colons to underscores.
3762 std::string::size_type loc = 0;
3763 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3764 FuncName.replace(loc, 1, "_");
Steve Naroff8e2f57a2008-10-29 18:15:37 +00003765 } else if (GlobalVarDecl)
3766 FuncName = std::string(GlobalVarDecl->getName());
Steve Narofffa15fd92008-10-28 20:29:00 +00003767
3768 std::string BlockNumber = utostr(Blocks.size()-1);
3769
3770 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
3771 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
3772
3773 // Get a pointer to the function type so we can cast appropriately.
3774 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
3775
3776 FunctionDecl *FD;
3777 Expr *NewRep;
3778
3779 // Simulate a contructor call...
3780 FD = SynthBlockInitFunctionDecl(Tag.c_str());
3781 DeclRefExpr *DRE = new DeclRefExpr(FD, FType, SourceLocation());
3782
3783 llvm::SmallVector<Expr*, 4> InitExprs;
3784
Steve Narofffdc03722008-10-29 21:23:59 +00003785 // Initialize the block function.
Steve Narofffa15fd92008-10-28 20:29:00 +00003786 FD = SynthBlockInitFunctionDecl(Func.c_str());
3787 DeclRefExpr *Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3788 CastExpr *castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00003789 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00003790 InitExprs.push_back(castExpr);
Steve Narofffa15fd92008-10-28 20:29:00 +00003791
3792 if (ImportedBlockDecls.size()) {
3793 std::string Buf = "__" + FuncName + "_block_copy_" + BlockNumber;
Steve Narofffdc03722008-10-29 21:23:59 +00003794 FD = SynthBlockInitFunctionDecl(Buf.c_str());
3795 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3796 castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00003797 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffdc03722008-10-29 21:23:59 +00003798 InitExprs.push_back(castExpr);
3799
Steve Narofffa15fd92008-10-28 20:29:00 +00003800 Buf = "__" + FuncName + "_block_dispose_" + BlockNumber;
Steve Narofffdc03722008-10-29 21:23:59 +00003801 FD = SynthBlockInitFunctionDecl(Buf.c_str());
3802 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3803 castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00003804 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffdc03722008-10-29 21:23:59 +00003805 InitExprs.push_back(castExpr);
Steve Narofffa15fd92008-10-28 20:29:00 +00003806 }
3807 // Add initializers for any closure decl refs.
3808 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00003809 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00003810 // Output all "by copy" declarations.
3811 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3812 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00003813 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00003814 // FIXME: Conform to ABI ([[obj retain] autorelease]).
3815 FD = SynthBlockInitFunctionDecl((*I)->getName());
3816 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00003817 } else if (isBlockPointerType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00003818 FD = SynthBlockInitFunctionDecl((*I)->getName());
3819 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3820 Exp = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00003821 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00003822 } else {
Steve Narofffdc03722008-10-29 21:23:59 +00003823 FD = SynthBlockInitFunctionDecl((*I)->getName());
3824 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00003825 }
Steve Narofffdc03722008-10-29 21:23:59 +00003826 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00003827 }
3828 // Output all "by ref" declarations.
3829 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3830 E = BlockByRefDecls.end(); I != E; ++I) {
Steve Narofffdc03722008-10-29 21:23:59 +00003831 FD = SynthBlockInitFunctionDecl((*I)->getName());
3832 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3833 Exp = new UnaryOperator(Exp, UnaryOperator::AddrOf,
3834 Context->getPointerType(Exp->getType()),
3835 SourceLocation());
Steve Naroff707b0fe2008-11-14 21:36:12 +00003836 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00003837 }
3838 }
Steve Narofffa15fd92008-10-28 20:29:00 +00003839 NewRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
3840 FType, SourceLocation());
3841 NewRep = new UnaryOperator(NewRep, UnaryOperator::AddrOf,
3842 Context->getPointerType(NewRep->getType()),
3843 SourceLocation());
Steve Naroffb2f9e512008-11-03 23:29:32 +00003844 NewRep = new CStyleCastExpr(FType, NewRep, FType, SourceLocation(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00003845 BlockDeclRefs.clear();
3846 BlockByRefDecls.clear();
3847 BlockByCopyDecls.clear();
3848 ImportedBlockDecls.clear();
3849 return NewRep;
3850}
3851
3852//===----------------------------------------------------------------------===//
3853// Function Body / Expression rewriting
3854//===----------------------------------------------------------------------===//
3855
3856Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
3857 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
3858 isa<DoStmt>(S) || isa<ForStmt>(S))
3859 Stmts.push_back(S);
3860 else if (isa<ObjCForCollectionStmt>(S)) {
3861 Stmts.push_back(S);
3862 ObjCBcLabelNo.push_back(++BcLabelCount);
3863 }
3864
3865 SourceRange OrigStmtRange = S->getSourceRange();
3866
3867 // Perform a bottom up rewrite of all children.
3868 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3869 CI != E; ++CI)
3870 if (*CI) {
3871 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
3872 if (newStmt)
3873 *CI = newStmt;
3874 }
3875
3876 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
3877 // Rewrite the block body in place.
3878 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
3879
3880 // Now we snarf the rewritten text and stash it away for later use.
Steve Naroff8e2f57a2008-10-29 18:15:37 +00003881 std::string Str = Rewrite.getRewritenText(BE->getSourceRange());
3882 RewrittenBlockExprs[BE] = Str;
Steve Narofffa15fd92008-10-28 20:29:00 +00003883
3884 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
3885 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00003886 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00003887 return blockTranscribed;
3888 }
3889 // Handle specific things.
3890 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
3891 return RewriteAtEncode(AtEncode);
3892
3893 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
3894 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
3895
3896 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
3897 return RewriteAtSelector(AtSelector);
3898
3899 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
3900 return RewriteObjCStringLiteral(AtString);
3901
3902 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
3903 // Before we rewrite it, put the original message expression in a comment.
3904 SourceLocation startLoc = MessExpr->getLocStart();
3905 SourceLocation endLoc = MessExpr->getLocEnd();
3906
3907 const char *startBuf = SM->getCharacterData(startLoc);
3908 const char *endBuf = SM->getCharacterData(endLoc);
3909
3910 std::string messString;
3911 messString += "// ";
3912 messString.append(startBuf, endBuf-startBuf+1);
3913 messString += "\n";
3914
3915 // FIXME: Missing definition of
3916 // InsertText(clang::SourceLocation, char const*, unsigned int).
3917 // InsertText(startLoc, messString.c_str(), messString.size());
3918 // Tried this, but it didn't work either...
3919 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
3920 return RewriteMessageExpr(MessExpr);
3921 }
3922
3923 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
3924 return RewriteObjCTryStmt(StmtTry);
3925
3926 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
3927 return RewriteObjCSynchronizedStmt(StmtTry);
3928
3929 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
3930 return RewriteObjCThrowStmt(StmtThrow);
3931
3932 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
3933 return RewriteObjCProtocolExpr(ProtocolExp);
3934
3935 if (ObjCForCollectionStmt *StmtForCollection =
3936 dyn_cast<ObjCForCollectionStmt>(S))
3937 return RewriteObjCForCollectionStmt(StmtForCollection,
3938 OrigStmtRange.getEnd());
3939 if (BreakStmt *StmtBreakStmt =
3940 dyn_cast<BreakStmt>(S))
3941 return RewriteBreakStmt(StmtBreakStmt);
3942 if (ContinueStmt *StmtContinueStmt =
3943 dyn_cast<ContinueStmt>(S))
3944 return RewriteContinueStmt(StmtContinueStmt);
3945
3946 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
3947 // and cast exprs.
3948 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
3949 // FIXME: What we're doing here is modifying the type-specifier that
3950 // precedes the first Decl. In the future the DeclGroup should have
3951 // a separate type-specifier that we can rewrite.
3952 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
3953
3954 // Blocks rewrite rules.
3955 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
3956 DI != DE; ++DI) {
Steve Narofffa15fd92008-10-28 20:29:00 +00003957 ScopedDecl *SD = *DI;
3958 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
3959 if (isBlockPointerType(ND->getType()))
3960 RewriteBlockPointerDecl(ND);
3961 else if (ND->getType()->isFunctionPointerType())
3962 CheckFunctionPointerDecl(ND->getType(), ND);
3963 }
3964 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
3965 if (isBlockPointerType(TD->getUnderlyingType()))
3966 RewriteBlockPointerDecl(TD);
3967 else if (TD->getUnderlyingType()->isFunctionPointerType())
3968 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
3969 }
3970 }
3971 }
3972
3973 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
3974 RewriteObjCQualifiedInterfaceTypes(CE);
3975
3976 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
3977 isa<DoStmt>(S) || isa<ForStmt>(S)) {
3978 assert(!Stmts.empty() && "Statement stack is empty");
3979 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
3980 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
3981 && "Statement stack mismatch");
3982 Stmts.pop_back();
3983 }
3984 // Handle blocks rewriting.
3985 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
3986 if (BDRE->isByRef())
3987 RewriteBlockDeclRefExpr(BDRE);
3988 }
3989 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003990 if (CE->getCallee()->getType()->isBlockPointerType()) {
3991 Stmt *BlockCall = SynthesizeBlockCall(CE);
3992 ReplaceStmt(S, BlockCall);
3993 return BlockCall;
3994 }
Steve Narofffa15fd92008-10-28 20:29:00 +00003995 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00003996 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00003997 RewriteCastExpr(CE);
3998 }
3999#if 0
4000 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
4001 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
4002 // Get the new text.
4003 std::string SStr;
4004 llvm::raw_string_ostream Buf(SStr);
4005 Replacement->printPretty(Buf);
4006 const std::string &Str = Buf.str();
4007
4008 printf("CAST = %s\n", &Str[0]);
4009 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4010 delete S;
4011 return Replacement;
4012 }
4013#endif
4014 // Return this stmt unmodified.
4015 return S;
4016}
4017
4018/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4019/// main file of the input.
4020void RewriteObjC::HandleDeclInMainFile(Decl *D) {
4021 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4022 // Since function prototypes don't have ParmDecl's, we check the function
4023 // prototype. This enables us to rewrite function declarations and
4024 // definitions using the same code.
4025 RewriteBlocksInFunctionTypeProto(FD->getType(), FD);
4026
4027 if (Stmt *Body = FD->getBody()) {
4028 CurFunctionDef = FD;
4029 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
4030 // This synthesizes and inserts the block "impl" struct, invoke function,
4031 // and any copy/dispose helper functions.
4032 InsertBlockLiteralsWithinFunction(FD);
4033 CurFunctionDef = 0;
4034 }
4035 return;
4036 }
4037 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4038 if (Stmt *Body = MD->getBody()) {
4039 //Body->dump();
4040 CurMethodDef = MD;
4041 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
4042 InsertBlockLiteralsWithinMethod(MD);
4043 CurMethodDef = 0;
4044 }
4045 }
4046 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
4047 ClassImplementation.push_back(CI);
4048 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
4049 CategoryImplementation.push_back(CI);
4050 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
4051 RewriteForwardClassDecl(CD);
4052 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4053 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004054 if (isBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004055 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004056 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004057 CheckFunctionPointerDecl(VD->getType(), VD);
4058 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00004059 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004060 RewriteCastExpr(CE);
4061 }
4062 }
4063 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004064 if (VD->getInit()) {
4065 GlobalVarDecl = VD;
4066 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
4067 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
4068 GlobalVarDecl = 0;
4069
4070 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00004071 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004072 RewriteCastExpr(CE);
4073 }
4074 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004075 return;
4076 }
4077 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
4078 if (isBlockPointerType(TD->getUnderlyingType()))
4079 RewriteBlockPointerDecl(TD);
4080 else if (TD->getUnderlyingType()->isFunctionPointerType())
4081 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4082 return;
4083 }
4084 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
4085 if (RD->isDefinition()) {
4086 for (RecordDecl::field_const_iterator i = RD->field_begin(),
4087 e = RD->field_end(); i != e; ++i) {
4088 FieldDecl *FD = *i;
4089 if (isBlockPointerType(FD->getType()))
4090 RewriteBlockPointerDecl(FD);
4091 }
4092 }
4093 return;
4094 }
4095 // Nothing yet.
4096}
4097
4098void RewriteObjC::HandleTranslationUnit(TranslationUnit& TU) {
4099 // Get the top-level buffer that this corresponds to.
4100
4101 // Rewrite tabs if we care.
4102 //RewriteTabs();
4103
4104 if (Diags.hasErrorOccurred())
4105 return;
4106
4107 // Create the output file.
4108
4109 llvm::OwningPtr<llvm::raw_ostream> OwnedStream;
4110 llvm::raw_ostream *OutFile;
4111 if (OutFileName == "-") {
4112 OutFile = &llvm::outs();
4113 } else if (!OutFileName.empty()) {
4114 std::string Err;
Daniel Dunbar26fb2722008-11-13 05:09:21 +00004115 OutFile = new llvm::raw_fd_ostream(OutFileName.c_str(), false, Err);
Steve Narofffa15fd92008-10-28 20:29:00 +00004116 OwnedStream.reset(OutFile);
4117 } else if (InFileName == "-") {
4118 OutFile = &llvm::outs();
4119 } else {
4120 llvm::sys::Path Path(InFileName);
4121 Path.eraseSuffix();
4122 Path.appendSuffix("cpp");
4123 std::string Err;
Daniel Dunbar26fb2722008-11-13 05:09:21 +00004124 OutFile = new llvm::raw_fd_ostream(Path.toString().c_str(), false, Err);
Steve Narofffa15fd92008-10-28 20:29:00 +00004125 OwnedStream.reset(OutFile);
4126 }
4127
4128 RewriteInclude();
4129
4130 InsertText(SourceLocation::getFileLoc(MainFileID, 0),
4131 Preamble.c_str(), Preamble.size(), false);
4132
Steve Naroff0aab7962008-11-14 14:10:01 +00004133 if (ClassImplementation.size() || CategoryImplementation.size())
4134 RewriteImplementations();
Steve Narofffa15fd92008-10-28 20:29:00 +00004135
4136 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
4137 // we are done.
4138 if (const RewriteBuffer *RewriteBuf =
4139 Rewrite.getRewriteBufferFor(MainFileID)) {
4140 //printf("Changed:\n");
4141 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4142 } else {
4143 fprintf(stderr, "No changes\n");
4144 }
Steve Narofface66252008-11-13 20:07:04 +00004145
Steve Naroff0aab7962008-11-14 14:10:01 +00004146 if (ClassImplementation.size() || CategoryImplementation.size()) {
4147 // Rewrite Objective-c meta data*
4148 std::string ResultStr;
4149 SynthesizeMetaDataIntoBuffer(ResultStr);
4150 // Emit metadata.
4151 *OutFile << ResultStr;
4152 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004153 OutFile->flush();
4154}
4155