blob: 1c20ef1b891aa271b7382432fa93579f13880ebe [file] [log] [blame]
Steve Naroffb29b4272008-04-14 22:03:09 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
Chris Lattner77cd2a02007-10-11 00:43:27 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner77cd2a02007-10-11 00:43:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
14#include "ASTConsumers.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Ted Kremeneke3a61982008-05-31 20:11:04 +000018#include "clang/AST/TranslationUnit.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000019#include "clang/Basic/SourceManager.h"
Steve Naroffebf2b562007-10-23 23:50:29 +000020#include "clang/Basic/IdentifierTable.h"
Chris Lattner07506182007-11-30 22:53:43 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattner26de4652007-12-02 01:13:47 +000022#include "clang/Lex/Lexer.h"
Chris Lattner158ecb92007-10-25 17:07:24 +000023#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000024#include "llvm/ADT/SmallPtrSet.h"
Ted Kremeneka95d3752008-09-13 05:16:45 +000025#include "llvm/ADT/OwningPtr.h"
Chris Lattner26de4652007-12-02 01:13:47 +000026#include "llvm/Support/MemoryBuffer.h"
Steve Naroff0113c9d2008-01-28 21:34:52 +000027#include "llvm/Support/CommandLine.h"
Dan Gohman63e2dcc2008-05-21 20:19:16 +000028#include "llvm/Support/Streams.h"
Ted Kremeneka95d3752008-09-13 05:16:45 +000029#include "llvm/Support/raw_ostream.h"
Chris Lattnerc68ab772008-03-22 00:08:40 +000030#include "llvm/System/Path.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000031using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000032using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000033
Steve Naroff0113c9d2008-01-28 21:34:52 +000034static llvm::cl::opt<bool>
35SilenceRewriteMacroWarning("Wno-rewrite-macros", llvm::cl::init(false),
36 llvm::cl::desc("Silence ObjC rewriting warnings"));
37
Chris Lattner77cd2a02007-10-11 00:43:27 +000038namespace {
Steve Naroffb29b4272008-04-14 22:03:09 +000039 class RewriteObjC : public ASTConsumer {
Chris Lattner2c64b7b2007-10-16 21:07:07 +000040 Rewriter Rewrite;
Chris Lattnere365c502007-11-30 22:25:36 +000041 Diagnostic &Diags;
Steve Naroff4f943c22008-03-10 20:43:59 +000042 const LangOptions &LangOpts;
Steve Narofff69cc5d2008-01-30 19:17:43 +000043 unsigned RewriteFailedDiag;
44
Chris Lattner01c57482007-10-17 22:35:30 +000045 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000046 SourceManager *SM;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000047 TranslationUnitDecl *TUDecl;
Chris Lattner8a12c272007-10-11 18:38:32 +000048 unsigned MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000049 const char *MainFileStart, *MainFileEnd;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000050 SourceLocation LastIncLoc;
Steve Naroffba92b2e2008-03-27 22:29:16 +000051
Ted Kremeneka526c5c2008-01-07 19:49:32 +000052 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
53 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
54 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Narofffbfe8252008-05-06 18:26:51 +000055 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000056 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
57 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000058 llvm::SmallVector<Stmt *, 32> Stmts;
59 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroffebf2b562007-10-23 23:50:29 +000060
Steve Naroffd82a9ab2008-03-15 00:55:56 +000061 unsigned NumObjCStringLiterals;
62
Steve Naroffebf2b562007-10-23 23:50:29 +000063 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000064 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000065 FunctionDecl *MsgSendStretFunctionDecl;
66 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000067 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000068 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000069 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000070 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000071 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +000072 FunctionDecl *GetProtocolFunctionDecl;
Steve Naroffc0a123c2008-03-11 17:37:02 +000073 FunctionDecl *SuperContructorFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000074
Steve Naroffbeaf2992007-11-03 11:27:19 +000075 // ObjC string constant support.
Steve Naroff248a7532008-04-15 22:42:06 +000076 VarDecl *ConstantStringClassReference;
Steve Naroffbeaf2992007-11-03 11:27:19 +000077 RecordDecl *NSStringRecord;
Steve Naroffab972d32007-11-04 22:37:50 +000078
Fariborz Jahanianb586cce2008-01-16 00:09:11 +000079 // ObjC foreach break/continue generation support.
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000080 int BcLabelCount;
81
Steve Naroff874e2322007-11-15 10:28:18 +000082 // Needed for super.
Steve Naroff54055232008-10-27 17:20:55 +000083 ObjCMethodDecl *CurMethodDef;
Steve Naroff874e2322007-11-15 10:28:18 +000084 RecordDecl *SuperStructDecl;
Steve Naroffd82a9ab2008-03-15 00:55:56 +000085 RecordDecl *ConstantStringDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000086
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +000087 // Needed for header files being rewritten
88 bool IsHeader;
89
Steve Naroffa7b402d2008-03-28 22:26:09 +000090 std::string InFileName;
91 std::string OutFileName;
92
Steve Naroffba92b2e2008-03-27 22:29:16 +000093 std::string Preamble;
Steve Naroff54055232008-10-27 17:20:55 +000094
95 // Block expressions.
96 llvm::SmallVector<BlockExpr *, 32> Blocks;
97 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
98 llvm::DenseMap<BlockDeclRefExpr *, CallExpr *> BlockCallExprs;
Steve Naroffba92b2e2008-03-27 22:29:16 +000099
Steve Naroff54055232008-10-27 17:20:55 +0000100 // Block related declarations.
101 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDecls;
102 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDecls;
103 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
104
105 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
106
107 FunctionDecl *CurFunctionDef;
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000108 VarDecl *GlobalVarDecl;
109
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000110 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +0000111 public:
Ted Kremeneke3a61982008-05-31 20:11:04 +0000112 virtual void Initialize(ASTContext &context);
113
114 virtual void InitializeTU(TranslationUnit &TU) {
115 TU.SetOwnsDecls(false);
116 Initialize(TU.getContext());
117 }
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000118
Chris Lattner8a12c272007-10-11 18:38:32 +0000119
Chris Lattnerf04da132007-10-24 17:06:59 +0000120 // Top Level Driver code.
121 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000122 void HandleDeclInMainFile(Decl *D);
Steve Naroffb29b4272008-04-14 22:03:09 +0000123 RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000124 Diagnostic &D, const LangOptions &LOpts);
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000125
126 ~RewriteObjC() {}
127
128 virtual void HandleTranslationUnit(TranslationUnit& TU);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000129
130 void ReplaceStmt(Stmt *Old, Stmt *New) {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000131 // If replacement succeeded or warning disabled return with no warning.
132 if (!Rewrite.ReplaceStmt(Old, New) || SilenceRewriteMacroWarning)
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000133 return;
134
Chris Lattner0a14eee2008-11-18 07:04:44 +0000135 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
136 << Old->getSourceRange();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000137 }
138
Steve Naroffba92b2e2008-03-27 22:29:16 +0000139 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
140 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000141 // If insertion succeeded or warning disabled return with no warning.
Steve Naroffba92b2e2008-03-27 22:29:16 +0000142 if (!Rewrite.InsertText(Loc, StrData, StrLen, InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000143 SilenceRewriteMacroWarning)
144 return;
145
146 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
147 }
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000148
Chris Lattneraadaf782008-01-31 19:51:04 +0000149 void RemoveText(SourceLocation Loc, unsigned StrLen) {
150 // If removal succeeded or warning disabled return with no warning.
151 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
152 return;
153
154 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
155 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000156
Chris Lattneraadaf782008-01-31 19:51:04 +0000157 void ReplaceText(SourceLocation Start, unsigned OrigLength,
158 const char *NewStr, unsigned NewLength) {
159 // If removal succeeded or warning disabled return with no warning.
160 if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength) ||
161 SilenceRewriteMacroWarning)
162 return;
163
164 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
165 }
166
Chris Lattnerf04da132007-10-24 17:06:59 +0000167 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000168 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000169 void RewriteInclude();
Chris Lattnerf04da132007-10-24 17:06:59 +0000170 void RewriteTabs();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000171 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
172 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000173 void RewriteImplementationDecl(NamedDecl *Dcl);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000174 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
175 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
176 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
177 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
178 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Chris Lattner55d13b42008-03-16 21:23:50 +0000179 void RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +0000180 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000181 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroff4f95b752008-07-29 18:15:38 +0000182 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffd5255f52007-11-01 13:24:47 +0000183 bool needToScanForQualifiers(QualType T);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000184 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000185 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000186 QualType getConstantStringStructType();
Steve Naroffbaf58c32008-05-31 14:15:04 +0000187 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Chris Lattner311ff022007-10-16 22:36:42 +0000188
Chris Lattnerf04da132007-10-24 17:06:59 +0000189 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000190 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000191 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000192 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart);
Steve Naroffb42f8412007-11-05 14:50:49 +0000193 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000194 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000195 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000196 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000197 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000198 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000199 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
200 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
201 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000202 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
203 SourceLocation OrigEnd);
Steve Naroff934f2762007-10-24 22:48:43 +0000204 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
205 Expr **args, unsigned nargs);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000206 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000207 Stmt *RewriteBreakStmt(BreakStmt *S);
208 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000209 void SynthCountByEnumWithState(std::string &buf);
210
Steve Naroff09b266e2007-10-30 23:14:51 +0000211 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000212 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000213 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000214 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000215 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000216 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000217 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000218 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000219 void SynthGetProtocolFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000220 void SynthSuperContructorFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000221
Chris Lattnerf04da132007-10-24 17:06:59 +0000222 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000223 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000224 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000225
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000226 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000227 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000228
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000229 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
230 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000231 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000232 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000233 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000234 const char *ClassName,
235 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000236
Chris Lattner780f3292008-07-21 21:32:27 +0000237 void RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl>
238 &Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000239 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000240 const char *ClassName,
241 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000242 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000243 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000244 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
245 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000246 std::string &Result);
Steve Narofface66252008-11-13 20:07:04 +0000247 void RewriteImplementations();
248 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Steve Naroff54055232008-10-27 17:20:55 +0000249
250 // Block rewriting.
251 void RewriteBlocksInFunctionTypeProto(QualType funcType, NamedDecl *D);
252 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
253
254 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
255 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
256
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000257 // Block specific rewrite rules.
Steve Naroff54055232008-10-27 17:20:55 +0000258 void RewriteBlockCall(CallExpr *Exp);
259 void RewriteBlockPointerDecl(NamedDecl *VD);
260 void RewriteBlockDeclRefExpr(BlockDeclRefExpr *VD);
261 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
262
263 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
264 const char *funcName, std::string Tag);
265 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
266 const char *funcName, std::string Tag);
267 std::string SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
268 bool hasCopyDisposeHelpers);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +0000269 Stmt *SynthesizeBlockCall(CallExpr *Exp);
Steve Naroff54055232008-10-27 17:20:55 +0000270 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
271 const char *FunName);
272
273 void CollectBlockDeclRefInfo(BlockExpr *Exp);
274 void GetBlockCallExprs(Stmt *S);
275 void GetBlockDeclRefExprs(Stmt *S);
276
277 // We avoid calling Type::isBlockPointerType(), since it operates on the
278 // canonical type. We only care if the top-level type is a closure pointer.
279 bool isBlockPointerType(QualType T) { return isa<BlockPointerType>(T); }
280
281 // FIXME: This predicate seems like it would be useful to add to ASTContext.
282 bool isObjCType(QualType T) {
283 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
284 return false;
285
286 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
287
288 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
289 OCT == Context->getCanonicalType(Context->getObjCClassType()))
290 return true;
291
292 if (const PointerType *PT = OCT->getAsPointerType()) {
293 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
294 isa<ObjCQualifiedIdType>(PT->getPointeeType()))
295 return true;
296 }
297 return false;
298 }
299 bool PointerTypeTakesAnyBlockArguments(QualType QT);
300 void GetExtentOfArgList(const char *Name, const char *&LParen, const char *&RParen);
Steve Naroffb2f9e512008-11-03 23:29:32 +0000301 void RewriteCastExpr(CStyleCastExpr *CE);
Steve Narofffa15fd92008-10-28 20:29:00 +0000302
303 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000304 Stmt *SynthBlockInitExpr(BlockExpr *Exp);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000305 };
306}
307
Steve Naroff54055232008-10-27 17:20:55 +0000308void RewriteObjC::RewriteBlocksInFunctionTypeProto(QualType funcType,
309 NamedDecl *D) {
310 if (FunctionTypeProto *fproto = dyn_cast<FunctionTypeProto>(funcType)) {
311 for (FunctionTypeProto::arg_type_iterator I = fproto->arg_type_begin(),
312 E = fproto->arg_type_end(); I && (I != E); ++I)
313 if (isBlockPointerType(*I)) {
314 // All the args are checked/rewritten. Don't call twice!
315 RewriteBlockPointerDecl(D);
316 break;
317 }
318 }
319}
320
321void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
322 const PointerType *PT = funcType->getAsPointerType();
323 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
324 RewriteBlocksInFunctionTypeProto(PT->getPointeeType(), ND);
325}
326
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000327static bool IsHeaderFile(const std::string &Filename) {
328 std::string::size_type DotPos = Filename.rfind('.');
329
330 if (DotPos == std::string::npos) {
331 // no file extension
332 return false;
333 }
334
335 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
336 // C header: .h
337 // C++ header: .hh or .H;
338 return Ext == "h" || Ext == "hh" || Ext == "H";
339}
340
Steve Naroffb29b4272008-04-14 22:03:09 +0000341RewriteObjC::RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000342 Diagnostic &D, const LangOptions &LOpts)
343 : Diags(D), LangOpts(LOpts) {
344 IsHeader = IsHeaderFile(inFile);
345 InFileName = inFile;
346 OutFileName = outFile;
347 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
348 "rewriting sub-expression within a macro (may not be correct)");
349}
350
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000351ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
Chris Lattnerc68ab772008-03-22 00:08:40 +0000352 const std::string& OutFile,
Steve Naroff4f943c22008-03-10 20:43:59 +0000353 Diagnostic &Diags,
354 const LangOptions &LOpts) {
Steve Naroffb29b4272008-04-14 22:03:09 +0000355 return new RewriteObjC(InFile, OutFile, Diags, LOpts);
Chris Lattnere365c502007-11-30 22:25:36 +0000356}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000357
Steve Naroffb29b4272008-04-14 22:03:09 +0000358void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000359 Context = &context;
360 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000361 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000362 MsgSendFunctionDecl = 0;
363 MsgSendSuperFunctionDecl = 0;
364 MsgSendStretFunctionDecl = 0;
365 MsgSendSuperStretFunctionDecl = 0;
366 MsgSendFpretFunctionDecl = 0;
367 GetClassFunctionDecl = 0;
368 GetMetaClassFunctionDecl = 0;
369 SelGetUidFunctionDecl = 0;
370 CFStringFunctionDecl = 0;
371 GetProtocolFunctionDecl = 0;
372 ConstantStringClassReference = 0;
373 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000374 CurMethodDef = 0;
375 CurFunctionDef = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000376 SuperStructDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000377 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000378 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000379 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000380 NumObjCStringLiterals = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000381
382 // Get the ID and start/end of the main file.
383 MainFileID = SM->getMainFileID();
384 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
385 MainFileStart = MainBuf->getBufferStart();
386 MainFileEnd = MainBuf->getBufferEnd();
Steve Naroffba92b2e2008-03-27 22:29:16 +0000387
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000388 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000389
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000390 // declaring objc_selector outside the parameter list removes a silly
391 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000392 if (IsHeader)
393 Preamble = "#pragma once\n";
394 Preamble += "struct objc_selector; struct objc_class;\n";
395 Preamble += "#ifndef OBJC_SUPER\n";
396 Preamble += "struct objc_super { struct objc_object *object; ";
397 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000398 if (LangOpts.Microsoft) {
399 // Add a constructor for creating temporary objects.
Steve Naroffba92b2e2008-03-27 22:29:16 +0000400 Preamble += "objc_super(struct objc_object *o, struct objc_object *s) : ";
401 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000402 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000403 Preamble += "};\n";
404 Preamble += "#define OBJC_SUPER\n";
405 Preamble += "#endif\n";
406 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
407 Preamble += "typedef struct objc_object Protocol;\n";
408 Preamble += "#define _REWRITER_typedef_Protocol\n";
409 Preamble += "#endif\n";
Steve Naroff3c64d9e2008-03-12 13:19:12 +0000410 if (LangOpts.Microsoft)
Steve Naroff69c827f2008-05-06 22:45:19 +0000411 Preamble += "#define __OBJC_RW_EXTERN extern \"C\" __declspec(dllimport)\n";
412 else
413 Preamble += "#define __OBJC_RW_EXTERN extern\n";
414 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000415 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000416 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000417 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000418 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000419 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000420 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000421 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff1284db82008-05-08 22:02:18 +0000422 Preamble += "__OBJC_RW_EXTERN double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000423 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff0757612008-05-08 17:52:16 +0000424 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000425 Preamble += "(const char *);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000426 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000427 Preamble += "(const char *);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000428 Preamble += "__OBJC_RW_EXTERN void objc_exception_throw(struct objc_object *);\n";
429 Preamble += "__OBJC_RW_EXTERN void objc_exception_try_enter(void *);\n";
430 Preamble += "__OBJC_RW_EXTERN void objc_exception_try_exit(void *);\n";
431 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_exception_extract(void *);\n";
432 Preamble += "__OBJC_RW_EXTERN int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000433 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000434 // @synchronized hooks.
435 Preamble += "__OBJC_RW_EXTERN void objc_sync_enter(struct objc_object *);\n";
436 Preamble += "__OBJC_RW_EXTERN void objc_sync_exit(struct objc_object *);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000437 Preamble += "__OBJC_RW_EXTERN Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000438 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
439 Preamble += "struct __objcFastEnumerationState {\n\t";
440 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000441 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000442 Preamble += "unsigned long *mutationsPtr;\n\t";
443 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff73ebd6d2008-06-02 20:23:21 +0000444 Preamble += "__OBJC_RW_EXTERN void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000445 Preamble += "#define __FASTENUMERATIONSTATE\n";
446 Preamble += "#endif\n";
447 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
448 Preamble += "struct __NSConstantStringImpl {\n";
449 Preamble += " int *isa;\n";
450 Preamble += " int flags;\n";
451 Preamble += " char *str;\n";
452 Preamble += " long length;\n";
453 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000454 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
455 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
456 Preamble += "#else\n";
Steve Naroff73b17cd2008-05-15 21:12:10 +0000457 Preamble += "__OBJC_RW_EXTERN int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000458 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000459 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
460 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000461 // Blocks preamble.
462 Preamble += "#ifndef BLOCK_IMPL\n";
463 Preamble += "#define BLOCK_IMPL\n";
464 Preamble += "struct __block_impl {\n";
465 Preamble += " void *isa;\n";
466 Preamble += " int Flags;\n";
467 Preamble += " int Size;\n";
468 Preamble += " void *FuncPtr;\n";
469 Preamble += "};\n";
470 Preamble += "enum {\n";
471 Preamble += " BLOCK_HAS_COPY_DISPOSE = (1<<25),\n";
472 Preamble += " BLOCK_IS_GLOBAL = (1<<28)\n";
473 Preamble += "};\n";
Steve Naroff54055232008-10-27 17:20:55 +0000474 Preamble += "// Runtime copy/destroy helper functions\n";
475 Preamble += "__OBJC_RW_EXTERN void _Block_copy_assign(void *, void *);\n";
476 Preamble += "__OBJC_RW_EXTERN void _Block_byref_assign_copy(void *, void *);\n";
477 Preamble += "__OBJC_RW_EXTERN void _Block_destroy(void *);\n";
478 Preamble += "__OBJC_RW_EXTERN void _Block_byref_release(void *);\n";
479 Preamble += "__OBJC_RW_EXTERN void *_NSConcreteGlobalBlock;\n";
480 Preamble += "__OBJC_RW_EXTERN void *_NSConcreteStackBlock;\n";
481 Preamble += "#endif\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000482 if (LangOpts.Microsoft) {
483 Preamble += "#undef __OBJC_RW_EXTERN\n";
484 Preamble += "#define __attribute__(X)\n";
485 }
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000486}
487
488
Chris Lattnerf04da132007-10-24 17:06:59 +0000489//===----------------------------------------------------------------------===//
490// Top Level Driver Code
491//===----------------------------------------------------------------------===//
492
Steve Naroffb29b4272008-04-14 22:03:09 +0000493void RewriteObjC::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000494 // Two cases: either the decl could be in the main file, or it could be in a
495 // #included file. If the former, rewrite it now. If the later, check to see
496 // if we rewrote the #include/#import.
497 SourceLocation Loc = D->getLocation();
498 Loc = SM->getLogicalLoc(Loc);
499
500 // If this is for a builtin, ignore it.
501 if (Loc.isInvalid()) return;
502
Steve Naroffebf2b562007-10-23 23:50:29 +0000503 // Look for built-in declarations that we need to refer during the rewrite.
504 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000505 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000506 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000507 // declared in <Foundation/NSString.h>
Chris Lattner8ec03f52008-11-24 03:54:41 +0000508 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000509 ConstantStringClassReference = FVD;
510 return;
511 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000512 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000513 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000514 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000515 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000516 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000517 RewriteProtocolDecl(PD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000518 } else if (ObjCForwardProtocolDecl *FP =
519 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000520 RewriteForwardProtocolDecl(FP);
Steve Naroffebf2b562007-10-23 23:50:29 +0000521 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000522 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000523 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000524 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000525}
526
Chris Lattnerf04da132007-10-24 17:06:59 +0000527//===----------------------------------------------------------------------===//
528// Syntactic (non-AST) Rewriting Code
529//===----------------------------------------------------------------------===//
530
Steve Naroffb29b4272008-04-14 22:03:09 +0000531void RewriteObjC::RewriteInclude() {
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000532 SourceLocation LocStart = SourceLocation::getFileLoc(MainFileID, 0);
533 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
534 const char *MainBufStart = MainBuf.first;
535 const char *MainBufEnd = MainBuf.second;
536 size_t ImportLen = strlen("import");
537 size_t IncludeLen = strlen("include");
538
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000539 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000540 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
541 if (*BufPtr == '#') {
542 if (++BufPtr == MainBufEnd)
543 return;
544 while (*BufPtr == ' ' || *BufPtr == '\t')
545 if (++BufPtr == MainBufEnd)
546 return;
547 if (!strncmp(BufPtr, "import", ImportLen)) {
548 // replace import with include
549 SourceLocation ImportLoc =
550 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattneraadaf782008-01-31 19:51:04 +0000551 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000552 BufPtr += ImportLen;
553 }
554 }
555 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000556}
557
Steve Naroffb29b4272008-04-14 22:03:09 +0000558void RewriteObjC::RewriteTabs() {
Chris Lattnerf04da132007-10-24 17:06:59 +0000559 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
560 const char *MainBufStart = MainBuf.first;
561 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000562
Chris Lattnerf04da132007-10-24 17:06:59 +0000563 // Loop over the whole file, looking for tabs.
564 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
565 if (*BufPtr != '\t')
566 continue;
567
568 // Okay, we found a tab. This tab will turn into at least one character,
569 // but it depends on which 'virtual column' it is in. Compute that now.
570 unsigned VCol = 0;
571 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
572 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
573 ++VCol;
574
575 // Okay, now that we know the virtual column, we know how many spaces to
576 // insert. We assume 8-character tab-stops.
577 unsigned Spaces = 8-(VCol & 7);
578
579 // Get the location of the tab.
580 SourceLocation TabLoc =
581 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
582
583 // Rewrite the single tab character into a sequence of spaces.
Chris Lattneraadaf782008-01-31 19:51:04 +0000584 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerf04da132007-10-24 17:06:59 +0000585 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000586}
587
588
Steve Naroffb29b4272008-04-14 22:03:09 +0000589void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000590 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000591 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerf04da132007-10-24 17:06:59 +0000592
593 // Get the start location and compute the semi location.
594 SourceLocation startLoc = ClassDecl->getLocation();
595 const char *startBuf = SM->getCharacterData(startLoc);
596 const char *semiPtr = strchr(startBuf, ';');
597
598 // Translate to typedef's that forward reference structs with the same name
599 // as the class. As a convenience, we include the original declaration
600 // as a comment.
601 std::string typedefString;
602 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000603 typedefString.append(startBuf, semiPtr-startBuf+1);
604 typedefString += "\n";
605 for (int i = 0; i < numDecls; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000606 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000607 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000608 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000609 typedefString += "\n";
610 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000611 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000612 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000613 typedefString += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000614 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000615 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000616 }
617
618 // Replace the @class with typedefs corresponding to the classes.
Chris Lattneraadaf782008-01-31 19:51:04 +0000619 ReplaceText(startLoc, semiPtr-startBuf+1,
620 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000621}
622
Steve Naroffb29b4272008-04-14 22:03:09 +0000623void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000624 SourceLocation LocStart = Method->getLocStart();
625 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000626
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000627 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
Steve Naroff94ac21e2008-10-21 13:37:27 +0000628 InsertText(LocStart, "#if 0\n", 6);
629 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000630 } else {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000631 InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000632 }
633}
634
Steve Naroffb29b4272008-04-14 22:03:09 +0000635void RewriteObjC::RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000636{
Chris Lattner55d13b42008-03-16 21:23:50 +0000637 for (unsigned i = 0; i < nProperties; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000638 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000639 SourceLocation Loc = Property->getLocation();
640
Chris Lattneraadaf782008-01-31 19:51:04 +0000641 ReplaceText(Loc, 0, "// ", 3);
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000642
643 // FIXME: handle properties that are declared across multiple lines.
644 }
645}
646
Steve Naroffb29b4272008-04-14 22:03:09 +0000647void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000648 SourceLocation LocStart = CatDecl->getLocStart();
649
650 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000651 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000652
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000653 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000654 E = CatDecl->instmeth_end(); I != E; ++I)
655 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000656 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000657 E = CatDecl->classmeth_end(); I != E; ++I)
658 RewriteMethodDeclaration(*I);
659
Steve Naroff423cb562007-10-30 13:30:57 +0000660 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000661 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000662}
663
Steve Naroffb29b4272008-04-14 22:03:09 +0000664void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000665 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000666
Steve Naroff752d6ef2007-10-30 16:42:30 +0000667 SourceLocation LocStart = PDecl->getLocStart();
668
669 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000670 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000671
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000672 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000673 E = PDecl->instmeth_end(); I != E; ++I)
674 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000675 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000676 E = PDecl->classmeth_end(); I != E; ++I)
677 RewriteMethodDeclaration(*I);
678
Steve Naroff752d6ef2007-10-30 16:42:30 +0000679 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000680 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattneraadaf782008-01-31 19:51:04 +0000681 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000682
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000683 // Must comment out @optional/@required
684 const char *startBuf = SM->getCharacterData(LocStart);
685 const char *endBuf = SM->getCharacterData(LocEnd);
686 for (const char *p = startBuf; p < endBuf; p++) {
687 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
688 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000689 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000690 ReplaceText(OptionalLoc, strlen("@optional"),
691 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000692
693 }
694 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
695 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000696 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000697 ReplaceText(OptionalLoc, strlen("@required"),
698 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000699
700 }
701 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000702}
703
Steve Naroffb29b4272008-04-14 22:03:09 +0000704void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000705 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000706 if (LocStart.isInvalid())
707 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000708 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000709 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000710}
711
Steve Naroffb29b4272008-04-14 22:03:09 +0000712void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000713 std::string &ResultStr) {
Steve Naroffced80a82008-10-30 12:09:33 +0000714 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroff76e429d2008-07-16 14:40:40 +0000715 const FunctionType *FPRetType = 0;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000716 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000717 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000718 ResultStr += "id";
Steve Naroff76e429d2008-07-16 14:40:40 +0000719 else if (OMD->getResultType()->isFunctionPointerType()) {
720 // needs special handling, since pointer-to-functions have special
721 // syntax (where a decaration models use).
722 QualType retType = OMD->getResultType();
723 if (const PointerType* PT = retType->getAsPointerType()) {
724 QualType PointeeTy = PT->getPointeeType();
725 if ((FPRetType = PointeeTy->getAsFunctionType())) {
726 ResultStr += FPRetType->getResultType().getAsString();
727 ResultStr += "(*";
728 }
729 }
730 } else
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000731 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000732 ResultStr += " ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000733
734 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000735 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000736
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000737 if (OMD->isInstance())
738 NameStr += "_I_";
739 else
740 NameStr += "_C_";
741
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000742 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000743 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000744
745 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000746 if (ObjCCategoryImplDecl *CID =
747 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000748 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000749 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000750 }
Steve Naroff563b8282008-04-04 22:23:44 +0000751 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +0000752 {
753 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000754 int len = selString.size();
755 for (int i = 0; i < len; i++)
756 if (selString[i] == ':')
757 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000758 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000759 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000760 // Remember this name for metadata emission
761 MethodInternalNames[OMD] = NameStr;
762 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000763
764 // Rewrite arguments
765 ResultStr += "(";
766
767 // invisible arguments
768 if (OMD->isInstance()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000769 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000770 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +0000771 if (!LangOpts.Microsoft) {
772 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
773 ResultStr += "struct ";
774 }
775 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000776 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000777 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000778 }
779 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000780 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000781
782 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000783 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000784 ResultStr += " _cmd";
785
786 // Method arguments.
Chris Lattner58cce3b2008-03-16 01:07:14 +0000787 for (unsigned i = 0; i < OMD->getNumParams(); i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000788 ParmVarDecl *PDecl = OMD->getParamDecl(i);
789 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +0000790 if (PDecl->getType()->isObjCQualifiedIdType()) {
791 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000792 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +0000793 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000794 std::string Name = PDecl->getNameAsString();
Steve Naroffc8ad87b2008-10-30 14:45:29 +0000795 if (isBlockPointerType(PDecl->getType())) {
796 // Make sure we convert "t (^)(...)" to "t (*)(...)".
797 const BlockPointerType *BPT = PDecl->getType()->getAsBlockPointerType();
798 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name);
799 } else
800 PDecl->getType().getAsStringInternal(Name);
Steve Naroff543409e2008-04-18 21:13:19 +0000801 ResultStr += Name;
802 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000803 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +0000804 if (OMD->isVariadic())
805 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000806 ResultStr += ") ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000807
Steve Naroff76e429d2008-07-16 14:40:40 +0000808 if (FPRetType) {
809 ResultStr += ")"; // close the precedence "scope" for "*".
810
811 // Now, emit the argument types (if any).
812 if (const FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(FPRetType)) {
813 ResultStr += "(";
814 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
815 if (i) ResultStr += ", ";
816 std::string ParamStr = FT->getArgType(i).getAsString();
817 ResultStr += ParamStr;
818 }
819 if (FT->isVariadic()) {
820 if (FT->getNumArgs()) ResultStr += ", ";
821 ResultStr += "...";
822 }
823 ResultStr += ")";
824 } else {
825 ResultStr += "()";
826 }
827 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000828}
Steve Naroffb29b4272008-04-14 22:03:09 +0000829void RewriteObjC::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000830 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
831 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000832
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000833 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000834 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000835 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000836 InsertText(CID->getLocStart(), "// ", 3);
Steve Narofface66252008-11-13 20:07:04 +0000837
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000838 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000839 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
840 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000841 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000842 ObjCMethodDecl *OMD = *I;
843 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000844 SourceLocation LocStart = OMD->getLocStart();
845 SourceLocation LocEnd = OMD->getBody()->getLocStart();
846
847 const char *startBuf = SM->getCharacterData(LocStart);
848 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000849 ReplaceText(LocStart, endBuf-startBuf,
850 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000851 }
852
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000853 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000854 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
855 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000856 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000857 ObjCMethodDecl *OMD = *I;
858 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000859 SourceLocation LocStart = OMD->getLocStart();
860 SourceLocation LocEnd = OMD->getBody()->getLocStart();
861
862 const char *startBuf = SM->getCharacterData(LocStart);
863 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000864 ReplaceText(LocStart, endBuf-startBuf,
865 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000866 }
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000867 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000868 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000869 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000870 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000871}
872
Steve Naroffb29b4272008-04-14 22:03:09 +0000873void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000874 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000875 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000876 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +0000877 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000878 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000879 ResultStr += "\n";
880 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000881 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000882 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000883 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000884 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000885 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000886 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000887 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000888 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000889 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Narofff908a872007-10-30 02:23:23 +0000890
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000891 RewriteProperties(ClassDecl->getNumPropertyDecl(),
892 ClassDecl->getPropertyDecl());
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000893 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000894 E = ClassDecl->instmeth_end(); I != E; ++I)
895 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000896 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000897 E = ClassDecl->classmeth_end(); I != E; ++I)
898 RewriteMethodDeclaration(*I);
899
Steve Naroff2feac5e2007-10-30 03:43:13 +0000900 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000901 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000902}
903
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000904Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
905 SourceLocation OrigStart) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000906 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff54055232008-10-27 17:20:55 +0000907 if (CurMethodDef) {
Steve Naroff05b8c782008-03-12 00:25:36 +0000908 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +0000909 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
910 // lookup which class implements the instance variable.
911 ObjCInterfaceDecl *clsDeclared = 0;
912 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
913 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
914
915 // Synthesize an explicit cast to gain access to the ivar.
916 std::string RecName = clsDeclared->getIdentifier()->getName();
917 RecName += "_IMPL";
918 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000919 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +0000920 SourceLocation(), II);
Steve Narofff0757612008-05-08 17:52:16 +0000921 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
922 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Douglas Gregor6eec8e82008-10-28 15:36:24 +0000923 CastExpr *castExpr = new CStyleCastExpr(castT, IV->getBase(), castT,
Steve Naroffb2f9e512008-11-03 23:29:32 +0000924 SourceLocation(), SourceLocation());
Steve Narofff0757612008-05-08 17:52:16 +0000925 // Don't forget the parens to enforce the proper binding.
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000926 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
927 IV->getBase()->getLocEnd(),
928 castExpr);
Steve Narofff0757612008-05-08 17:52:16 +0000929 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +0000930 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000931 MemberExpr *ME = new MemberExpr(PE, true, D, IV->getLocation(),
932 D->getType());
Steve Narofff0757612008-05-08 17:52:16 +0000933 ReplaceStmt(IV, ME);
934 delete IV;
935 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000936 }
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000937
938 ReplaceStmt(IV->getBase(), PE);
939 // Cannot delete IV->getBase(), since PE points to it.
940 // Replace the old base with the cast. This is important when doing
941 // embedded rewrites. For example, [newInv->_container addObject:0].
942 IV->setBase(PE);
943 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000944 }
Steve Naroff84472a82008-04-18 21:55:08 +0000945 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +0000946 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
947
948 // Explicit ivar refs need to have a cast inserted.
949 // FIXME: consider sharing some of this code with the code above.
950 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +0000951 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +0000952 // lookup which class implements the instance variable.
953 ObjCInterfaceDecl *clsDeclared = 0;
Steve Narofff0757612008-05-08 17:52:16 +0000954 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +0000955 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
956
957 // Synthesize an explicit cast to gain access to the ivar.
958 std::string RecName = clsDeclared->getIdentifier()->getName();
959 RecName += "_IMPL";
960 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000961 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +0000962 SourceLocation(), II);
Steve Naroff9f525972008-05-06 23:20:07 +0000963 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
964 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Douglas Gregor6eec8e82008-10-28 15:36:24 +0000965 CastExpr *castExpr = new CStyleCastExpr(castT, IV->getBase(), castT,
Steve Naroffb2f9e512008-11-03 23:29:32 +0000966 SourceLocation(), SourceLocation());
Steve Naroff9f525972008-05-06 23:20:07 +0000967 // Don't forget the parens to enforce the proper binding.
Chris Lattner8d366162008-05-28 16:38:23 +0000968 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
969 IV->getBase()->getLocEnd(), castExpr);
Steve Naroff9f525972008-05-06 23:20:07 +0000970 ReplaceStmt(IV->getBase(), PE);
971 // Cannot delete IV->getBase(), since PE points to it.
972 // Replace the old base with the cast. This is important when doing
973 // embedded rewrites. For example, [newInv->_container addObject:0].
974 IV->setBase(PE);
975 return IV;
976 }
Steve Naroffc2a689b2007-11-15 11:33:00 +0000977 }
Steve Naroff84472a82008-04-18 21:55:08 +0000978 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +0000979}
980
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000981/// SynthCountByEnumWithState - To print:
982/// ((unsigned int (*)
983/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
984/// (void *)objc_msgSend)((id)l_collection,
985/// sel_registerName(
986/// "countByEnumeratingWithState:objects:count:"),
987/// &enumState,
988/// (id *)items, (unsigned int)16)
989///
Steve Naroffb29b4272008-04-14 22:03:09 +0000990void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000991 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
992 "id *, unsigned int))(void *)objc_msgSend)";
993 buf += "\n\t\t";
994 buf += "((id)l_collection,\n\t\t";
995 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
996 buf += "\n\t\t";
997 buf += "&enumState, "
998 "(id *)items, (unsigned int)16)";
999}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001000
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001001/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1002/// statement to exit to its outer synthesized loop.
1003///
Steve Naroffb29b4272008-04-14 22:03:09 +00001004Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001005 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1006 return S;
1007 // replace break with goto __break_label
1008 std::string buf;
1009
1010 SourceLocation startLoc = S->getLocStart();
1011 buf = "goto __break_label_";
1012 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001013 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001014
1015 return 0;
1016}
1017
1018/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1019/// statement to continue with its inner synthesized loop.
1020///
Steve Naroffb29b4272008-04-14 22:03:09 +00001021Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001022 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1023 return S;
1024 // replace continue with goto __continue_label
1025 std::string buf;
1026
1027 SourceLocation startLoc = S->getLocStart();
1028 buf = "goto __continue_label_";
1029 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001030 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001031
1032 return 0;
1033}
1034
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001035/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001036/// It rewrites:
1037/// for ( type elem in collection) { stmts; }
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001038
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001039/// Into:
1040/// {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001041/// type elem;
1042/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001043/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001044/// id l_collection = (id)collection;
1045/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1046/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001047/// if (limit) {
1048/// unsigned long startMutations = *enumState.mutationsPtr;
1049/// do {
1050/// unsigned long counter = 0;
1051/// do {
1052/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001053/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001054/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001055/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001056/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001057/// } while (counter < limit);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001058/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1059/// objects:items count:16]);
1060/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001061/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001062/// }
1063/// else
1064/// elem = nil;
1065/// }
1066///
Steve Naroffb29b4272008-04-14 22:03:09 +00001067Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001068 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001069 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1070 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1071 "ObjCForCollectionStmt Statement stack mismatch");
1072 assert(!ObjCBcLabelNo.empty() &&
1073 "ObjCForCollectionStmt - Label No stack empty");
1074
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001075 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001076 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001077 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001078 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001079 std::string buf;
1080 buf = "\n{\n\t";
1081 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1082 // type elem;
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001083 ScopedDecl* D = DS->getSolitaryDecl();
1084 QualType ElementType = cast<ValueDecl>(D)->getType();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001085 elementTypeAsString = ElementType.getAsString();
1086 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001087 buf += " ";
Chris Lattner8ec03f52008-11-24 03:54:41 +00001088 elementName = D->getNameAsCString();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001089 buf += elementName;
1090 buf += ";\n\t";
1091 }
Chris Lattner06767512008-04-08 05:52:18 +00001092 else {
1093 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner8ec03f52008-11-24 03:54:41 +00001094 elementName = DR->getDecl()->getNameAsCString();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001095 elementTypeAsString
1096 = cast<ValueDecl>(DR->getDecl())->getType().getAsString();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001097 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001098
1099 // struct __objcFastEnumerationState enumState = { 0 };
1100 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1101 // id items[16];
1102 buf += "id items[16];\n\t";
1103 // id l_collection = (id)
1104 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001105 // Find start location of 'collection' the hard way!
1106 const char *startCollectionBuf = startBuf;
1107 startCollectionBuf += 3; // skip 'for'
1108 startCollectionBuf = strchr(startCollectionBuf, '(');
1109 startCollectionBuf++; // skip '('
1110 // find 'in' and skip it.
1111 while (*startCollectionBuf != ' ' ||
1112 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1113 (*(startCollectionBuf+3) != ' ' &&
1114 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1115 startCollectionBuf++;
1116 startCollectionBuf += 3;
1117
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001118 // Replace: "for (type element in" with string constructed thus far.
Chris Lattneraadaf782008-01-31 19:51:04 +00001119 ReplaceText(startLoc, startCollectionBuf - startBuf,
1120 buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001121 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001122 SourceLocation rightParenLoc = S->getRParenLoc();
1123 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1124 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001125 buf = ";\n\t";
1126
1127 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1128 // objects:items count:16];
1129 // which is synthesized into:
1130 // unsigned int limit =
1131 // ((unsigned int (*)
1132 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1133 // (void *)objc_msgSend)((id)l_collection,
1134 // sel_registerName(
1135 // "countByEnumeratingWithState:objects:count:"),
1136 // (struct __objcFastEnumerationState *)&state,
1137 // (id *)items, (unsigned int)16);
1138 buf += "unsigned long limit =\n\t\t";
1139 SynthCountByEnumWithState(buf);
1140 buf += ";\n\t";
1141 /// if (limit) {
1142 /// unsigned long startMutations = *enumState.mutationsPtr;
1143 /// do {
1144 /// unsigned long counter = 0;
1145 /// do {
1146 /// if (startMutations != *enumState.mutationsPtr)
1147 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001148 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001149 buf += "if (limit) {\n\t";
1150 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1151 buf += "do {\n\t\t";
1152 buf += "unsigned long counter = 0;\n\t\t";
1153 buf += "do {\n\t\t\t";
1154 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1155 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1156 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001157 buf += " = (";
1158 buf += elementTypeAsString;
1159 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001160 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattneraadaf782008-01-31 19:51:04 +00001161 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001162
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001163 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001164 /// } while (counter < limit);
1165 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1166 /// objects:items count:16]);
1167 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001168 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001169 /// }
1170 /// else
1171 /// elem = nil;
1172 /// }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001173 ///
1174 buf = ";\n\t";
1175 buf += "__continue_label_";
1176 buf += utostr(ObjCBcLabelNo.back());
1177 buf += ": ;";
1178 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001179 buf += "} while (counter < limit);\n\t";
1180 buf += "} while (limit = ";
1181 SynthCountByEnumWithState(buf);
1182 buf += ");\n\t";
1183 buf += elementName;
1184 buf += " = nil;\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001185 buf += "__break_label_";
1186 buf += utostr(ObjCBcLabelNo.back());
1187 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001188 buf += "}\n\t";
1189 buf += "else\n\t\t";
1190 buf += elementName;
1191 buf += " = nil;\n";
1192 buf += "}\n";
Steve Naroff600e4e82008-07-21 18:26:02 +00001193
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001194 // Insert all these *after* the statement body.
Steve Naroff600e4e82008-07-21 18:26:02 +00001195 if (isa<CompoundStmt>(S->getBody())) {
1196 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1197 InsertText(endBodyLoc, buf.c_str(), buf.size());
1198 } else {
1199 /* Need to treat single statements specially. For example:
1200 *
1201 * for (A *a in b) if (stuff()) break;
1202 * for (A *a in b) xxxyy;
1203 *
1204 * The following code simply scans ahead to the semi to find the actual end.
1205 */
1206 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1207 const char *semiBuf = strchr(stmtBuf, ';');
1208 assert(semiBuf && "Can't find ';'");
1209 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1210 InsertText(endBodyLoc, buf.c_str(), buf.size());
1211 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001212 Stmts.pop_back();
1213 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001214 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001215}
1216
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001217/// RewriteObjCSynchronizedStmt -
1218/// This routine rewrites @synchronized(expr) stmt;
1219/// into:
1220/// objc_sync_enter(expr);
1221/// @try stmt @finally { objc_sync_exit(expr); }
1222///
Steve Naroffb29b4272008-04-14 22:03:09 +00001223Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001224 // Get the start location and compute the semi location.
1225 SourceLocation startLoc = S->getLocStart();
1226 const char *startBuf = SM->getCharacterData(startLoc);
1227
1228 assert((*startBuf == '@') && "bogus @synchronized location");
1229
1230 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001231 buf = "objc_sync_enter((id)";
1232 const char *lparenBuf = startBuf;
1233 while (*lparenBuf != '(') lparenBuf++;
1234 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Steve Naroffc7089f12008-08-19 13:04:19 +00001235 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1236 // the sync expression is typically a message expression that's already
1237 // been rewritten! (which implies the SourceLocation's are invalid).
1238 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001239 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001240 while (*endBuf != ')') endBuf--;
1241 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001242 buf = ");\n";
1243 // declare a new scope with two variables, _stack and _rethrow.
1244 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1245 buf += "int buf[18/*32-bit i386*/];\n";
1246 buf += "char *pointers[4];} _stack;\n";
1247 buf += "id volatile _rethrow = 0;\n";
1248 buf += "objc_exception_try_enter(&_stack);\n";
1249 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00001250 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001251 startLoc = S->getSynchBody()->getLocEnd();
1252 startBuf = SM->getCharacterData(startLoc);
1253
Steve Naroffc7089f12008-08-19 13:04:19 +00001254 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001255 SourceLocation lastCurlyLoc = startLoc;
1256 buf = "}\nelse {\n";
1257 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1258 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb2a39452008-07-16 19:47:39 +00001259 buf += " objc_sync_exit(";
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001260 Expr *syncExpr = new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00001261 S->getSynchExpr(),
1262 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00001263 SourceLocation(), SourceLocation());
Ted Kremeneka95d3752008-09-13 05:16:45 +00001264 std::string syncExprBufS;
1265 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Steve Naroff3498cc92008-08-21 13:03:03 +00001266 syncExpr->printPretty(syncExprBuf);
Steve Naroffb2a39452008-07-16 19:47:39 +00001267 buf += syncExprBuf.str();
1268 buf += ");\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001269 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1270 buf += "}\n";
1271 buf += "}";
1272
Chris Lattneraadaf782008-01-31 19:51:04 +00001273 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001274 return 0;
1275}
1276
Steve Naroffb29b4272008-04-14 22:03:09 +00001277Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001278 // Get the start location and compute the semi location.
1279 SourceLocation startLoc = S->getLocStart();
1280 const char *startBuf = SM->getCharacterData(startLoc);
1281
1282 assert((*startBuf == '@') && "bogus @try location");
1283
1284 std::string buf;
1285 // declare a new scope with two variables, _stack and _rethrow.
1286 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1287 buf += "int buf[18/*32-bit i386*/];\n";
1288 buf += "char *pointers[4];} _stack;\n";
1289 buf += "id volatile _rethrow = 0;\n";
1290 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001291 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001292
Chris Lattneraadaf782008-01-31 19:51:04 +00001293 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001294
1295 startLoc = S->getTryBody()->getLocEnd();
1296 startBuf = SM->getCharacterData(startLoc);
1297
1298 assert((*startBuf == '}') && "bogus @try block");
Steve Naroffc9ba1722008-07-16 15:31:30 +00001299
Steve Naroff75730982007-11-07 04:08:17 +00001300 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffc9ba1722008-07-16 15:31:30 +00001301 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1302 if (catchList) {
1303 startLoc = startLoc.getFileLocWithOffset(1);
1304 buf = " /* @catch begin */ else {\n";
1305 buf += " id _caught = objc_exception_extract(&_stack);\n";
1306 buf += " objc_exception_try_enter (&_stack);\n";
1307 buf += " if (_setjmp(_stack.buf))\n";
1308 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1309 buf += " else { /* @catch continue */";
1310
1311 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001312 } else { /* no catch list */
1313 buf = "}\nelse {\n";
1314 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1315 buf += "}";
1316 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffc9ba1722008-07-16 15:31:30 +00001317 }
Steve Naroff75730982007-11-07 04:08:17 +00001318 bool sawIdTypedCatch = false;
1319 Stmt *lastCatchBody = 0;
Steve Naroff75730982007-11-07 04:08:17 +00001320 while (catchList) {
1321 Stmt *catchStmt = catchList->getCatchParamStmt();
1322
1323 if (catchList == S->getCatchStmts())
1324 buf = "if ("; // we are generating code for the first catch clause
1325 else
1326 buf = "else if (";
1327 startLoc = catchList->getLocStart();
1328 startBuf = SM->getCharacterData(startLoc);
1329
1330 assert((*startBuf == '@') && "bogus @catch location");
1331
1332 const char *lParenLoc = strchr(startBuf, '(');
1333
Steve Naroffbe4b3332008-02-01 22:08:12 +00001334 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001335 // Now rewrite the body...
1336 lastCatchBody = catchList->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001337 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1338 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner06767512008-04-08 05:52:18 +00001339 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1340 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001341 assert((*bodyBuf == '{') && "bogus @catch body location");
1342
1343 buf += "1) { id _tmp = _caught;";
1344 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1345 buf.c_str(), buf.size());
1346 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Ted Kremenek50a25e22008-10-06 22:39:38 +00001347 QualType t = dyn_cast<ValueDecl>(declStmt->getSolitaryDecl())->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001348 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001349 buf += "1) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001350 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001351 sawIdTypedCatch = true;
1352 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001353 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroff75730982007-11-07 04:08:17 +00001354
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001355 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001356 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001357 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001358 buf += cls->getDecl()->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001359 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001360 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001361 }
1362 }
1363 // Now rewrite the body...
1364 lastCatchBody = catchList->getCatchBody();
1365 SourceLocation rParenLoc = catchList->getRParenLoc();
1366 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1367 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1368 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1369 assert((*rParenBuf == ')') && "bogus @catch paren location");
1370 assert((*bodyBuf == '{') && "bogus @catch body location");
1371
1372 buf = " = _caught;";
1373 // Here we replace ") {" with "= _caught;" (which initializes and
1374 // declares the @catch parameter).
Chris Lattneraadaf782008-01-31 19:51:04 +00001375 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001376 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001377 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001378 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001379 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001380 catchList = catchList->getNextCatchStmt();
1381 }
1382 // Complete the catch list...
1383 if (lastCatchBody) {
1384 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001385 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1386 "bogus @catch body location");
Steve Naroff75730982007-11-07 04:08:17 +00001387
Steve Naroff378f47a2008-09-11 15:29:03 +00001388 // Insert the last (implicit) else clause *before* the right curly brace.
1389 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1390 buf = "} /* last catch end */\n";
1391 buf += "else {\n";
1392 buf += " _rethrow = _caught;\n";
1393 buf += " objc_exception_try_exit(&_stack);\n";
1394 buf += "} } /* @catch end */\n";
1395 if (!S->getFinallyStmt())
1396 buf += "}\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001397 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001398
1399 // Set lastCurlyLoc
1400 lastCurlyLoc = lastCatchBody->getLocEnd();
1401 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001402 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001403 startLoc = finalStmt->getLocStart();
1404 startBuf = SM->getCharacterData(startLoc);
1405 assert((*startBuf == '@') && "bogus @finally start");
1406
1407 buf = "/* @finally */";
Chris Lattneraadaf782008-01-31 19:51:04 +00001408 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001409
1410 Stmt *body = finalStmt->getFinallyBody();
1411 SourceLocation startLoc = body->getLocStart();
1412 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001413 assert(*SM->getCharacterData(startLoc) == '{' &&
1414 "bogus @finally body location");
1415 assert(*SM->getCharacterData(endLoc) == '}' &&
1416 "bogus @finally body location");
Steve Naroff75730982007-11-07 04:08:17 +00001417
1418 startLoc = startLoc.getFileLocWithOffset(1);
1419 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001420 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001421 endLoc = endLoc.getFileLocWithOffset(-1);
1422 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001423 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001424
1425 // Set lastCurlyLoc
1426 lastCurlyLoc = body->getLocEnd();
Steve Naroff378f47a2008-09-11 15:29:03 +00001427 } else { /* no finally clause - make sure we synthesize an implicit one */
1428 buf = "{ /* implicit finally clause */\n";
1429 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1430 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1431 buf += "}";
1432 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001433 }
1434 // Now emit the final closing curly brace...
1435 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1436 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001437 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001438 return 0;
1439}
1440
Steve Naroffb29b4272008-04-14 22:03:09 +00001441Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001442 return 0;
1443}
1444
Steve Naroffb29b4272008-04-14 22:03:09 +00001445Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001446 return 0;
1447}
1448
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001449// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff2bd03922007-11-07 15:32:26 +00001450// the throw expression is typically a message expression that's already
1451// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001452Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001453 // Get the start location and compute the semi location.
1454 SourceLocation startLoc = S->getLocStart();
1455 const char *startBuf = SM->getCharacterData(startLoc);
1456
1457 assert((*startBuf == '@') && "bogus @throw location");
1458
1459 std::string buf;
1460 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001461 if (S->getThrowExpr())
1462 buf = "objc_exception_throw(";
1463 else // add an implicit argument
1464 buf = "objc_exception_throw(_caught";
Steve Naroff4ba0acb2008-07-25 15:41:30 +00001465
1466 // handle "@ throw" correctly.
1467 const char *wBuf = strchr(startBuf, 'w');
1468 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1469 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
1470
Steve Naroff2bd03922007-11-07 15:32:26 +00001471 const char *semiBuf = strchr(startBuf, ';');
1472 assert((*semiBuf == ';') && "@throw: can't find ';'");
1473 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1474 buf = ");";
Chris Lattneraadaf782008-01-31 19:51:04 +00001475 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001476 return 0;
1477}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001478
Steve Naroffb29b4272008-04-14 22:03:09 +00001479Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001480 // Create a new string expression.
1481 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001482 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001483 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001484 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1485 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +00001486 SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001487 ReplaceStmt(Exp, Replacement);
Chris Lattnere365c502007-11-30 22:25:36 +00001488
Chris Lattner07506182007-11-30 22:53:43 +00001489 // Replace this subexpr in the parent.
Chris Lattnere64b7772007-10-24 16:57:36 +00001490 delete Exp;
1491 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001492}
1493
Steve Naroffb29b4272008-04-14 22:03:09 +00001494Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroffb42f8412007-11-05 14:50:49 +00001495 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1496 // Create a call to sel_registerName("selName").
1497 llvm::SmallVector<Expr*, 8> SelExprs;
1498 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner077bf5e2008-11-24 03:33:13 +00001499 SelExprs.push_back(new StringLiteral(Exp->getSelector().getAsString().c_str(),
1500 Exp->getSelector().getAsString().size(),
Steve Naroffb42f8412007-11-05 14:50:49 +00001501 false, argType, SourceLocation(),
1502 SourceLocation()));
1503 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1504 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001505 ReplaceStmt(Exp, SelExp);
Steve Naroffb42f8412007-11-05 14:50:49 +00001506 delete Exp;
1507 return SelExp;
1508}
1509
Steve Naroffb29b4272008-04-14 22:03:09 +00001510CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff934f2762007-10-24 22:48:43 +00001511 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001512 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001513 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +00001514
1515 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +00001516 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +00001517
1518 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001519 QualType pToFunc = Context->getPointerType(msgSendType);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001520 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE,
1521 /*isLvalue=*/false);
Steve Naroffebf2b562007-10-23 23:50:29 +00001522
1523 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +00001524
Steve Naroff934f2762007-10-24 22:48:43 +00001525 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1526}
1527
Steve Naroffd5255f52007-11-01 13:24:47 +00001528static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1529 const char *&startRef, const char *&endRef) {
1530 while (startBuf < endBuf) {
1531 if (*startBuf == '<')
1532 startRef = startBuf; // mark the start.
1533 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001534 if (startRef && *startRef == '<') {
1535 endRef = startBuf; // mark the end.
1536 return true;
1537 }
1538 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001539 }
1540 startBuf++;
1541 }
1542 return false;
1543}
1544
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001545static void scanToNextArgument(const char *&argRef) {
1546 int angle = 0;
1547 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1548 if (*argRef == '<')
1549 angle++;
1550 else if (*argRef == '>')
1551 angle--;
1552 argRef++;
1553 }
1554 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1555}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001556
Steve Naroffb29b4272008-04-14 22:03:09 +00001557bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001558
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001559 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001560 return true;
1561
Steve Naroffd5255f52007-11-01 13:24:47 +00001562 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +00001563 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001564 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff9165ad32007-10-31 04:38:33 +00001565 return true; // we have "Class <Protocol> *".
1566 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001567 return false;
1568}
1569
Steve Naroff4f95b752008-07-29 18:15:38 +00001570void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1571 QualType Type = E->getType();
1572 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00001573 SourceLocation Loc, EndLoc;
1574
1575 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
1576 Loc = ECE->getLParenLoc();
1577 EndLoc = ECE->getRParenLoc();
1578 } else {
1579 Loc = E->getLocStart();
1580 EndLoc = E->getLocEnd();
1581 }
1582 // This will defend against trying to rewrite synthesized expressions.
1583 if (Loc.isInvalid() || EndLoc.isInvalid())
1584 return;
1585
Steve Naroff4f95b752008-07-29 18:15:38 +00001586 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00001587 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00001588 const char *startRef = 0, *endRef = 0;
1589 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1590 // Get the locations of the startRef, endRef.
1591 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1592 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1593 // Comment out the protocol references.
1594 InsertText(LessLoc, "/*", 2);
1595 InsertText(GreaterLoc, "*/", 2);
1596 }
1597 }
1598}
1599
Steve Naroffb29b4272008-04-14 22:03:09 +00001600void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001601 SourceLocation Loc;
1602 QualType Type;
1603 const FunctionTypeProto *proto = 0;
1604 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1605 Loc = VD->getLocation();
1606 Type = VD->getType();
1607 }
1608 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1609 Loc = FD->getLocation();
1610 // Check for ObjC 'id' and class types that have been adorned with protocol
1611 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1612 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1613 assert(funcType && "missing function type");
1614 proto = dyn_cast<FunctionTypeProto>(funcType);
1615 if (!proto)
1616 return;
1617 Type = proto->getResultType();
1618 }
1619 else
1620 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001621
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001622 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001623 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001624
1625 const char *endBuf = SM->getCharacterData(Loc);
1626 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00001627 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001628 startBuf--; // scan backward (from the decl location) for return type.
1629 const char *startRef = 0, *endRef = 0;
1630 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1631 // Get the locations of the startRef, endRef.
1632 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1633 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1634 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001635 InsertText(LessLoc, "/*", 2);
1636 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001637 }
1638 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001639 if (!proto)
1640 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001641 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001642 const char *startBuf = SM->getCharacterData(Loc);
1643 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001644 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1645 if (needToScanForQualifiers(proto->getArgType(i))) {
1646 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001647
Steve Naroffd5255f52007-11-01 13:24:47 +00001648 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001649 // scan forward (from the decl location) for argument types.
1650 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001651 const char *startRef = 0, *endRef = 0;
1652 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1653 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001654 SourceLocation LessLoc =
1655 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1656 SourceLocation GreaterLoc =
1657 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001658 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001659 InsertText(LessLoc, "/*", 2);
1660 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001661 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001662 startBuf = ++endBuf;
1663 }
1664 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00001665 // If the function name is derived from a macro expansion, then the
1666 // argument buffer will not follow the name. Need to speak with Chris.
1667 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001668 startBuf++; // scan forward (from the decl location) for argument types.
1669 startBuf++;
1670 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001671 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001672}
1673
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001674// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00001675void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001676 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1677 llvm::SmallVector<QualType, 16> ArgTys;
1678 ArgTys.push_back(Context->getPointerType(
1679 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001680 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001681 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001682 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001683 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001684 SourceLocation(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001685 SelGetUidIdent, getFuncType,
1686 FunctionDecl::Extern, false, 0);
1687}
1688
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001689// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
Steve Naroffb29b4272008-04-14 22:03:09 +00001690void RewriteObjC::SynthGetProtocolFunctionDecl() {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001691 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1692 llvm::SmallVector<QualType, 16> ArgTys;
1693 ArgTys.push_back(Context->getPointerType(
1694 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001695 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001696 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001697 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001698 GetProtocolFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001699 SourceLocation(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001700 SelGetProtoIdent, getFuncType,
1701 FunctionDecl::Extern, false, 0);
1702}
1703
Steve Naroffb29b4272008-04-14 22:03:09 +00001704void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001705 // declared in <objc/objc.h>
Chris Lattner8ec03f52008-11-24 03:54:41 +00001706 if (strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001707 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001708 return;
1709 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001710 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001711}
1712
Steve Naroffc0a123c2008-03-11 17:37:02 +00001713// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00001714void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00001715 if (SuperContructorFunctionDecl)
1716 return;
1717 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_super");
1718 llvm::SmallVector<QualType, 16> ArgTys;
1719 QualType argT = Context->getObjCIdType();
1720 assert(!argT.isNull() && "Can't find 'id' type");
1721 ArgTys.push_back(argT);
1722 ArgTys.push_back(argT);
1723 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1724 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001725 false, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001726 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001727 SourceLocation(),
Steve Naroffc0a123c2008-03-11 17:37:02 +00001728 msgSendIdent, msgSendType,
1729 FunctionDecl::Extern, false, 0);
1730}
1731
Steve Naroff09b266e2007-10-30 23:14:51 +00001732// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001733void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00001734 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1735 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001736 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001737 assert(!argT.isNull() && "Can't find 'id' type");
1738 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001739 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001740 assert(!argT.isNull() && "Can't find 'SEL' type");
1741 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001742 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001743 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001744 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001745 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001746 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001747 msgSendIdent, msgSendType,
1748 FunctionDecl::Extern, false, 0);
1749}
1750
Steve Naroff874e2322007-11-15 10:28:18 +00001751// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001752void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00001753 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1754 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001755 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001756 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00001757 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00001758 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1759 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1760 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001761 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00001762 assert(!argT.isNull() && "Can't find 'SEL' type");
1763 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001764 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00001765 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001766 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001767 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001768 SourceLocation(),
Steve Naroff874e2322007-11-15 10:28:18 +00001769 msgSendIdent, msgSendType,
1770 FunctionDecl::Extern, false, 0);
1771}
1772
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001773// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001774void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001775 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1776 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001777 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001778 assert(!argT.isNull() && "Can't find 'id' type");
1779 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001780 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001781 assert(!argT.isNull() && "Can't find 'SEL' type");
1782 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001783 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001784 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001785 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001786 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001787 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001788 msgSendIdent, msgSendType,
1789 FunctionDecl::Extern, false, 0);
1790}
1791
1792// SynthMsgSendSuperStretFunctionDecl -
1793// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001794void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001795 IdentifierInfo *msgSendIdent =
1796 &Context->Idents.get("objc_msgSendSuper_stret");
1797 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001798 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001799 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00001800 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001801 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1802 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1803 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001804 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001805 assert(!argT.isNull() && "Can't find 'SEL' type");
1806 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001807 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001808 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001809 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001810 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnera98e58d2008-03-15 21:24:04 +00001811 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001812 msgSendIdent, msgSendType,
1813 FunctionDecl::Extern, false, 0);
1814}
1815
Steve Naroff1284db82008-05-08 22:02:18 +00001816// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001817void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001818 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1819 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001820 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001821 assert(!argT.isNull() && "Can't find 'id' type");
1822 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001823 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001824 assert(!argT.isNull() && "Can't find 'SEL' type");
1825 ArgTys.push_back(argT);
Steve Naroff1284db82008-05-08 22:02:18 +00001826 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001827 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001828 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001829 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001830 SourceLocation(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001831 msgSendIdent, msgSendType,
1832 FunctionDecl::Extern, false, 0);
1833}
1834
Steve Naroff09b266e2007-10-30 23:14:51 +00001835// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00001836void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00001837 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1838 llvm::SmallVector<QualType, 16> ArgTys;
1839 ArgTys.push_back(Context->getPointerType(
1840 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001841 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001842 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001843 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001844 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001845 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001846 getClassIdent, getClassType,
1847 FunctionDecl::Extern, false, 0);
1848}
1849
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001850// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00001851void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001852 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1853 llvm::SmallVector<QualType, 16> ArgTys;
1854 ArgTys.push_back(Context->getPointerType(
1855 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001856 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001857 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001858 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001859 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001860 SourceLocation(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001861 getClassIdent, getClassType,
1862 FunctionDecl::Extern, false, 0);
1863}
1864
Steve Naroffb29b4272008-04-14 22:03:09 +00001865Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001866 QualType strType = getConstantStringStructType();
1867
1868 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00001869
1870 std::string tmpName = InFileName;
1871 unsigned i;
1872 for (i=0; i < tmpName.length(); i++) {
1873 char c = tmpName.at(i);
1874 // replace any non alphanumeric characters with '_'.
1875 if (!isalpha(c) && (c < '0' || c > '9'))
1876 tmpName[i] = '_';
1877 }
1878 S += tmpName;
1879 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001880 S += utostr(NumObjCStringLiterals++);
1881
Steve Naroffba92b2e2008-03-27 22:29:16 +00001882 Preamble += "static __NSConstantStringImpl " + S;
1883 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
1884 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001885 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00001886 std::string prettyBufS;
1887 llvm::raw_string_ostream prettyBuf(prettyBufS);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001888 Exp->getString()->printPretty(prettyBuf);
Steve Naroffba92b2e2008-03-27 22:29:16 +00001889 Preamble += prettyBuf.str();
1890 Preamble += ",";
Steve Naroff3652c2d2008-03-15 01:36:04 +00001891 // The minus 2 removes the begin/end double quotes.
Steve Naroffba92b2e2008-03-27 22:29:16 +00001892 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001893
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001894 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Steve Naroff248a7532008-04-15 22:42:06 +00001895 &Context->Idents.get(S.c_str()), strType,
1896 VarDecl::Static, NULL);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001897 DeclRefExpr *DRE = new DeclRefExpr(NewVD, strType, SourceLocation());
1898 Expr *Unop = new UnaryOperator(DRE, UnaryOperator::AddrOf,
1899 Context->getPointerType(DRE->getType()),
1900 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00001901 // cast to NSConstantString *
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001902 CastExpr *cast = new CStyleCastExpr(Exp->getType(), Unop,
Steve Naroffb2f9e512008-11-03 23:29:32 +00001903 Exp->getType(), SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001904 ReplaceStmt(Exp, cast);
Steve Naroff96984642007-11-08 14:30:50 +00001905 delete Exp;
1906 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00001907}
1908
Steve Naroffb29b4272008-04-14 22:03:09 +00001909ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001910 // check if we are sending a message to 'super'
Steve Naroff54055232008-10-27 17:20:55 +00001911 if (!CurMethodDef || !CurMethodDef->isInstance()) return 0;
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001912
Douglas Gregorcd9b46e2008-11-04 14:56:14 +00001913 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
1914 const PointerType *PT = Super->getType()->getAsPointerType();
Chris Lattner0d17f6f2008-06-21 18:04:54 +00001915 assert(PT);
1916 ObjCInterfaceType *IT = cast<ObjCInterfaceType>(PT->getPointeeType());
1917 return IT->getDecl();
1918 }
1919 return 0;
Steve Naroff874e2322007-11-15 10:28:18 +00001920}
1921
1922// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00001923QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00001924 if (!SuperStructDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001925 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00001926 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00001927 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00001928 QualType FieldTypes[2];
1929
1930 // struct objc_object *receiver;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001931 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00001932 // struct objc_class *super;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001933 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff874e2322007-11-15 10:28:18 +00001934 // Create fields
1935 FieldDecl *FieldDecls[2];
1936
1937 for (unsigned i = 0; i < 2; ++i)
Chris Lattnerb048c982008-04-06 04:47:34 +00001938 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00001939 FieldTypes[i]);
Steve Naroff874e2322007-11-15 10:28:18 +00001940
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001941 SuperStructDecl->defineBody(*Context, FieldDecls, 4);
Steve Naroff874e2322007-11-15 10:28:18 +00001942 }
1943 return Context->getTagDeclType(SuperStructDecl);
1944}
1945
Steve Naroffb29b4272008-04-14 22:03:09 +00001946QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001947 if (!ConstantStringDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001948 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00001949 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00001950 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001951 QualType FieldTypes[4];
1952
1953 // struct objc_object *receiver;
1954 FieldTypes[0] = Context->getObjCIdType();
1955 // int flags;
1956 FieldTypes[1] = Context->IntTy;
1957 // char *str;
1958 FieldTypes[2] = Context->getPointerType(Context->CharTy);
1959 // long length;
1960 FieldTypes[3] = Context->LongTy;
1961 // Create fields
Steve Naroff9630ec52008-03-27 22:59:54 +00001962 FieldDecl *FieldDecls[4];
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001963
1964 for (unsigned i = 0; i < 4; ++i)
Chris Lattnerb048c982008-04-06 04:47:34 +00001965 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00001966 FieldTypes[i]);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001967
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001968 ConstantStringDecl->defineBody(*Context, FieldDecls, 4);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001969 }
1970 return Context->getTagDeclType(ConstantStringDecl);
1971}
1972
Steve Naroffb29b4272008-04-14 22:03:09 +00001973Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001974 if (!SelGetUidFunctionDecl)
1975 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001976 if (!MsgSendFunctionDecl)
1977 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00001978 if (!MsgSendSuperFunctionDecl)
1979 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001980 if (!MsgSendStretFunctionDecl)
1981 SynthMsgSendStretFunctionDecl();
1982 if (!MsgSendSuperStretFunctionDecl)
1983 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001984 if (!MsgSendFpretFunctionDecl)
1985 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001986 if (!GetClassFunctionDecl)
1987 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001988 if (!GetMetaClassFunctionDecl)
1989 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001990
Steve Naroff874e2322007-11-15 10:28:18 +00001991 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001992 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1993 // May need to use objc_msgSend_stret() as well.
1994 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001995 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001996 QualType resultType = mDecl->getResultType();
Chris Lattner8b51fd72008-07-26 22:36:27 +00001997 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001998 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00001999 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002000 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002001 }
Steve Naroff874e2322007-11-15 10:28:18 +00002002
Steve Naroff934f2762007-10-24 22:48:43 +00002003 // Synthesize a call to objc_msgSend().
2004 llvm::SmallVector<Expr*, 8> MsgExprs;
2005 IdentifierInfo *clsName = Exp->getClassName();
2006
2007 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2008 if (clsName) { // class message.
Steve Narofffc93d522008-07-24 19:44:33 +00002009 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2010 // the 'super' idiom within a class method.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002011 if (!strcmp(clsName->getName(), "super")) {
2012 MsgSendFlavor = MsgSendSuperFunctionDecl;
2013 if (MsgSendStretFlavor)
2014 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2015 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2016
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002017 ObjCInterfaceDecl *SuperDecl =
Steve Naroff54055232008-10-27 17:20:55 +00002018 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002019
2020 llvm::SmallVector<Expr*, 4> InitExprs;
2021
2022 // set the receiver to self, the first argument to all methods.
Chris Lattner41110242008-06-17 18:05:57 +00002023 InitExprs.push_back(new DeclRefExpr(
Steve Naroff54055232008-10-27 17:20:55 +00002024 CurMethodDef->getSelfDecl(),
Chris Lattner41110242008-06-17 18:05:57 +00002025 Context->getObjCIdType(),
2026 SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002027 llvm::SmallVector<Expr*, 8> ClsExprs;
2028 QualType argType = Context->getPointerType(Context->CharTy);
2029 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2030 SuperDecl->getIdentifier()->getLength(),
2031 false, argType, SourceLocation(),
2032 SourceLocation()));
2033 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2034 &ClsExprs[0],
2035 ClsExprs.size());
2036 // To turn off a warning, type-cast to 'id'
Douglas Gregor49badde2008-10-27 19:41:14 +00002037 InitExprs.push_back( // set 'super class', using objc_getClass().
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002038 new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002039 Cls, Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002040 SourceLocation(), SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002041 // struct objc_super
2042 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00002043 Expr *SuperRep;
Steve Naroffc0a123c2008-03-11 17:37:02 +00002044
Steve Naroff23f41272008-03-11 18:14:26 +00002045 if (LangOpts.Microsoft) {
2046 SynthSuperContructorFunctionDecl();
2047 // Simulate a contructor call...
2048 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2049 superType, SourceLocation());
2050 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2051 superType, SourceLocation());
2052 } else {
2053 // (struct objc_super) { <exprs from above> }
2054 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2055 &InitExprs[0], InitExprs.size(),
Chris Lattner418f6c72008-10-26 23:43:26 +00002056 SourceLocation(), false);
2057 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE,
2058 false);
Steve Naroff23f41272008-03-11 18:14:26 +00002059 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002060 // struct objc_super *
2061 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2062 Context->getPointerType(SuperRep->getType()),
2063 SourceLocation());
2064 MsgExprs.push_back(Unop);
2065 } else {
2066 llvm::SmallVector<Expr*, 8> ClsExprs;
2067 QualType argType = Context->getPointerType(Context->CharTy);
2068 ClsExprs.push_back(new StringLiteral(clsName->getName(),
2069 clsName->getLength(),
2070 false, argType, SourceLocation(),
2071 SourceLocation()));
2072 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2073 &ClsExprs[0],
2074 ClsExprs.size());
2075 MsgExprs.push_back(Cls);
2076 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002077 } else { // instance message.
2078 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00002079
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002080 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00002081 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002082 if (MsgSendStretFlavor)
2083 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00002084 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2085
2086 llvm::SmallVector<Expr*, 4> InitExprs;
2087
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002088 InitExprs.push_back(
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002089 new CStyleCastExpr(Context->getObjCIdType(),
Steve Naroff54055232008-10-27 17:20:55 +00002090 new DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Narofff616ebb2008-07-16 22:35:27 +00002091 Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002092 SourceLocation()),
2093 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002094 SourceLocation(), SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00002095
2096 llvm::SmallVector<Expr*, 8> ClsExprs;
2097 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002098 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2099 SuperDecl->getIdentifier()->getLength(),
Steve Naroff874e2322007-11-15 10:28:18 +00002100 false, argType, SourceLocation(),
2101 SourceLocation()));
2102 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002103 &ClsExprs[0],
2104 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00002105 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002106 InitExprs.push_back(
Douglas Gregor49badde2008-10-27 19:41:14 +00002107 // set 'super class', using objc_getClass().
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002108 new CStyleCastExpr(Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002109 Cls, Context->getObjCIdType(), SourceLocation(), SourceLocation()));
Steve Naroff874e2322007-11-15 10:28:18 +00002110 // struct objc_super
2111 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00002112 Expr *SuperRep;
2113
2114 if (LangOpts.Microsoft) {
2115 SynthSuperContructorFunctionDecl();
2116 // Simulate a contructor call...
2117 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2118 superType, SourceLocation());
2119 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2120 superType, SourceLocation());
2121 } else {
2122 // (struct objc_super) { <exprs from above> }
2123 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2124 &InitExprs[0], InitExprs.size(),
Chris Lattner418f6c72008-10-26 23:43:26 +00002125 SourceLocation(), false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002126 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
2127 }
Steve Naroff874e2322007-11-15 10:28:18 +00002128 // struct objc_super *
2129 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2130 Context->getPointerType(SuperRep->getType()),
2131 SourceLocation());
2132 MsgExprs.push_back(Unop);
2133 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002134 // Remove all type-casts because it may contain objc-style types; e.g.
2135 // Foo<Proto> *.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002136 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002137 recExpr = CE->getSubExpr();
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002138 recExpr = new CStyleCastExpr(Context->getObjCIdType(), recExpr,
Douglas Gregor49badde2008-10-27 19:41:14 +00002139 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002140 SourceLocation(), SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00002141 MsgExprs.push_back(recExpr);
2142 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002143 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00002144 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002145 llvm::SmallVector<Expr*, 8> SelExprs;
2146 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner077bf5e2008-11-24 03:33:13 +00002147 SelExprs.push_back(new StringLiteral(Exp->getSelector().getAsString().c_str(),
2148 Exp->getSelector().getAsString().size(),
Steve Naroff934f2762007-10-24 22:48:43 +00002149 false, argType, SourceLocation(),
2150 SourceLocation()));
2151 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2152 &SelExprs[0], SelExprs.size());
2153 MsgExprs.push_back(SelExp);
2154
2155 // Now push any user supplied arguments.
2156 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002157 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002158 // Make all implicit casts explicit...ICE comes in handy:-)
2159 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2160 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregor49badde2008-10-27 19:41:14 +00002161 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002162 ? Context->getObjCIdType()
Douglas Gregor49badde2008-10-27 19:41:14 +00002163 : ICE->getType();
Steve Naroffb2f9e512008-11-03 23:29:32 +00002164 userExpr = new CStyleCastExpr(type, userExpr, type, SourceLocation(), SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002165 }
2166 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002167 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002168 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002169 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002170 userExpr = CE->getSubExpr();
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002171 userExpr = new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002172 userExpr, Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002173 SourceLocation(), SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002174 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00002175 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002176 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00002177 // We've transferred the ownership to MsgExprs. Null out the argument in
2178 // the original expression, since we will delete it below.
2179 Exp->setArg(i, 0);
2180 }
Steve Naroffab972d32007-11-04 22:37:50 +00002181 // Generate the funky cast.
2182 CastExpr *cast;
2183 llvm::SmallVector<QualType, 8> ArgTypes;
2184 QualType returnType;
2185
2186 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002187 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2188 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2189 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002190 ArgTypes.push_back(Context->getObjCIdType());
2191 ArgTypes.push_back(Context->getObjCSelType());
2192 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002193 // Push any user argument types.
Chris Lattner58cce3b2008-03-16 01:07:14 +00002194 for (unsigned i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002195 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
2196 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002197 : mDecl->getParamDecl(i)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00002198 // Make sure we convert "t (^)(...)" to "t (*)(...)".
2199 if (isBlockPointerType(t)) {
2200 const BlockPointerType *BPT = t->getAsBlockPointerType();
2201 t = Context->getPointerType(BPT->getPointeeType());
2202 }
Steve Naroff352336b2007-11-05 14:36:37 +00002203 ArgTypes.push_back(t);
2204 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002205 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
2206 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00002207 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002208 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002209 }
2210 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002211 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00002212
2213 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002214 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
2215 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002216
2217 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2218 // If we don't do this cast, we get the following bizarre warning/note:
2219 // xx.m:13: warning: function called through a non-compatible type
2220 // xx.m:13: note: if this code is reached, the program will abort
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002221 cast = new CStyleCastExpr(Context->getPointerType(Context->VoidTy), DRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002222 Context->getPointerType(Context->VoidTy),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002223 SourceLocation(), SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00002224
Steve Naroffab972d32007-11-04 22:37:50 +00002225 // Now do the "normal" pointer to function cast.
2226 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002227 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00002228 // If we don't have a method decl, force a variadic cast.
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002229 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Naroffab972d32007-11-04 22:37:50 +00002230 castType = Context->getPointerType(castType);
Steve Naroffb2f9e512008-11-03 23:29:32 +00002231 cast = new CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002232
2233 // Don't forget the parens to enforce the proper binding.
2234 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2235
2236 const FunctionType *FT = msgSendType->getAsFunctionType();
2237 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2238 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002239 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002240 if (MsgSendStretFlavor) {
2241 // We have the method which returns a struct/union. Must also generate
2242 // call to objc_msgSend_stret and hang both varieties on a conditional
2243 // expression which dictate which one to envoke depending on size of
2244 // method's return type.
2245
2246 // Create a reference to the objc_msgSend_stret() declaration.
2247 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
2248 SourceLocation());
2249 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002250 cast = new CStyleCastExpr(Context->getPointerType(Context->VoidTy), STDRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002251 Context->getPointerType(Context->VoidTy),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002252 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002253 // Now do the "normal" pointer to function cast.
2254 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002255 &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002256 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002257 castType = Context->getPointerType(castType);
Steve Naroffb2f9e512008-11-03 23:29:32 +00002258 cast = new CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002259
2260 // Don't forget the parens to enforce the proper binding.
2261 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2262
2263 FT = msgSendType->getAsFunctionType();
2264 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2265 FT->getResultType(), SourceLocation());
2266
2267 // Build sizeof(returnType)
Sebastian Redl05189992008-11-11 17:56:53 +00002268 SizeOfAlignOfExpr *sizeofExpr = new SizeOfAlignOfExpr(true, true,
2269 returnType.getAsOpaquePtr(),
2270 Context->getSizeType(),
2271 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002272 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2273 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2274 // For X86 it is more complicated and some kind of target specific routine
2275 // is needed to decide what to do.
Chris Lattner98be4942008-03-05 18:54:05 +00002276 unsigned IntSize =
2277 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002278 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2279 Context->IntTy,
2280 SourceLocation());
2281 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2282 BinaryOperator::LE,
2283 Context->IntTy,
2284 SourceLocation());
2285 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2286 ConditionalOperator *CondExpr =
2287 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002288 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002289 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002290 return ReplacingStmt;
2291}
2292
Steve Naroffb29b4272008-04-14 22:03:09 +00002293Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002294 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff80c28552008-10-27 20:54:44 +00002295
Steve Naroff934f2762007-10-24 22:48:43 +00002296 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002297 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff934f2762007-10-24 22:48:43 +00002298
Chris Lattnere64b7772007-10-24 16:57:36 +00002299 delete Exp;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002300 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002301}
2302
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002303/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2304/// call to objc_getProtocol("proto-name").
Steve Naroffb29b4272008-04-14 22:03:09 +00002305Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002306 if (!GetProtocolFunctionDecl)
2307 SynthGetProtocolFunctionDecl();
2308 // Create a call to objc_getProtocol("ProtocolName").
2309 llvm::SmallVector<Expr*, 8> ProtoExprs;
2310 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner8ec03f52008-11-24 03:54:41 +00002311 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getNameAsCString(),
2312 strlen(Exp->getProtocol()->getNameAsCString()),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002313 false, argType, SourceLocation(),
2314 SourceLocation()));
2315 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2316 &ProtoExprs[0],
2317 ProtoExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002318 ReplaceStmt(Exp, ProtoExp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002319 delete Exp;
2320 return ProtoExp;
2321
2322}
2323
Steve Naroffbaf58c32008-05-31 14:15:04 +00002324bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
2325 const char *endBuf) {
2326 while (startBuf < endBuf) {
2327 if (*startBuf == '#') {
2328 // Skip whitespace.
2329 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2330 ;
2331 if (!strncmp(startBuf, "if", strlen("if")) ||
2332 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2333 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2334 !strncmp(startBuf, "define", strlen("define")) ||
2335 !strncmp(startBuf, "undef", strlen("undef")) ||
2336 !strncmp(startBuf, "else", strlen("else")) ||
2337 !strncmp(startBuf, "elif", strlen("elif")) ||
2338 !strncmp(startBuf, "endif", strlen("endif")) ||
2339 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2340 !strncmp(startBuf, "include", strlen("include")) ||
2341 !strncmp(startBuf, "import", strlen("import")) ||
2342 !strncmp(startBuf, "include_next", strlen("include_next")))
2343 return true;
2344 }
2345 startBuf++;
2346 }
2347 return false;
2348}
2349
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002350/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002351/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00002352void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002353 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002354 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Chris Lattner8ec03f52008-11-24 03:54:41 +00002355 assert(CDecl->getNameAsCString() &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002356 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002357 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002358 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002359 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002360 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002361 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00002362 SourceLocation LocStart = CDecl->getLocStart();
2363 SourceLocation LocEnd = CDecl->getLocEnd();
2364
2365 const char *startBuf = SM->getCharacterData(LocStart);
2366 const char *endBuf = SM->getCharacterData(LocEnd);
Steve Naroffbaf58c32008-05-31 14:15:04 +00002367
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002368 // If no ivars and no root or if its root, directly or indirectly,
2369 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002370 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2371 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002372 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattneraadaf782008-01-31 19:51:04 +00002373 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002374 return;
2375 }
2376
2377 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002378 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002379 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002380 Result += CDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002381 if (LangOpts.Microsoft)
2382 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00002383
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002384 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002385 const char *cursor = strchr(startBuf, '{');
2386 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002387 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00002388 // If the buffer contains preprocessor directives, we do more fine-grained
2389 // rewrites. This is intended to fix code that looks like (which occurs in
2390 // NSURL.h, for example):
2391 //
2392 // #ifdef XYZ
2393 // @interface Foo : NSObject
2394 // #else
2395 // @interface FooBar : NSObject
2396 // #endif
2397 // {
2398 // int i;
2399 // }
2400 // @end
2401 //
2402 // This clause is segregated to avoid breaking the common case.
2403 if (BufferContainsPPDirectives(startBuf, cursor)) {
2404 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
2405 CDecl->getClassLoc();
2406 const char *endHeader = SM->getCharacterData(L);
2407 endHeader += Lexer::MeasureTokenLength(L, *SM);
2408
Chris Lattner3db6cae2008-07-21 18:19:38 +00002409 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00002410 // advance to the end of the referenced protocols.
2411 while (endHeader < cursor && *endHeader != '>') endHeader++;
2412 endHeader++;
2413 }
2414 // rewrite the original header
2415 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2416 } else {
2417 // rewrite the original header *without* disturbing the '{'
2418 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
2419 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002420 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002421 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002422 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002423 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002424 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00002425 Result += "_IVARS;\n";
Steve Narofffea763e82007-11-14 19:25:57 +00002426
2427 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002428 SourceLocation OnePastCurly =
2429 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2430 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002431 }
2432 cursor++; // past '{'
2433
2434 // Now comment out any visibility specifiers.
2435 while (cursor < endBuf) {
2436 if (*cursor == '@') {
2437 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002438 // Skip whitespace.
2439 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2440 /*scan*/;
2441
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002442 // FIXME: presence of @public, etc. inside comment results in
2443 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002444 if (!strncmp(cursor, "public", strlen("public")) ||
2445 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00002446 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002447 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002448 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002449 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002450 // FIXME: If there are cases where '<' is used in ivar declaration part
2451 // of user code, then scan the ivar list and use needToScanForQualifiers
2452 // for type checking.
2453 else if (*cursor == '<') {
2454 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002455 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002456 cursor = strchr(cursor, '>');
2457 cursor++;
2458 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002459 InsertText(atLoc, " */", 3);
Steve Naroffced80a82008-10-30 12:09:33 +00002460 } else if (*cursor == '^') { // rewrite block specifier.
2461 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2462 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002463 }
Steve Narofffea763e82007-11-14 19:25:57 +00002464 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002465 }
Steve Narofffea763e82007-11-14 19:25:57 +00002466 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002467 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00002468 } else { // we don't have any instance variables - insert super struct.
2469 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2470 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002471 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002472 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002473 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00002474 Result += "_IVARS;\n};\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00002475 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002476 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002477 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002478 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00002479 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002480}
2481
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002482// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002483/// class methods.
Steve Naroffb29b4272008-04-14 22:03:09 +00002484void RewriteObjC::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002485 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002486 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002487 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002488 const char *ClassName,
2489 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002490 if (MethodBegin == MethodEnd) return;
2491
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002492 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002493 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002494 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002495 SEL _cmd;
2496 char *method_types;
2497 void *_imp;
2498 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002499 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002500 Result += "\nstruct _objc_method {\n";
2501 Result += "\tSEL _cmd;\n";
2502 Result += "\tchar *method_types;\n";
2503 Result += "\tvoid *_imp;\n";
2504 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002505
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002506 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002507 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002508
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002509 // Build _objc_method_list for class's methods if needed
Steve Naroff946a6932008-03-11 00:12:29 +00002510
2511 /* struct {
2512 struct _objc_method_list *next_method;
2513 int method_count;
2514 struct _objc_method method_list[];
2515 }
2516 */
2517 Result += "\nstatic struct {\n";
2518 Result += "\tstruct _objc_method_list *next_method;\n";
2519 Result += "\tint method_count;\n";
2520 Result += "\tstruct _objc_method method_list[";
2521 Result += utostr(MethodEnd-MethodBegin);
2522 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002523 Result += prefix;
2524 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2525 Result += "_METHODS_";
2526 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002527 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002528 Result += IsInstanceMethod ? "inst" : "cls";
2529 Result += "_meth\")))= ";
2530 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002531
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002532 Result += "\t,{{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002533 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002534 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002535 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +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];
2540 Result += "}\n";
2541 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2542 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002543 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002544 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002545 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002546 Result += "\", \"";
2547 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002548 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002549 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002550 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002551 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002552 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002553}
2554
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002555/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00002556void RewriteObjC::
2557RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
2558 const char *prefix,
2559 const char *ClassName,
2560 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002561 static bool objc_protocol_methods = false;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002562 if (Protocols.empty()) return;
2563
2564 for (unsigned i = 0; i != Protocols.size(); i++) {
2565 ObjCProtocolDecl *PDecl = Protocols[i];
2566 // Output struct protocol_methods holder of method selector and type.
2567 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
2568 /* struct protocol_methods {
2569 SEL _cmd;
2570 char *method_types;
2571 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002572 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002573 Result += "\nstruct protocol_methods {\n";
2574 Result += "\tSEL _cmd;\n";
2575 Result += "\tchar *method_types;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002576 Result += "};\n";
Steve Narofffbfe8252008-05-06 18:26:51 +00002577
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002578 objc_protocol_methods = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002579 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002580 // Do not synthesize the protocol more than once.
2581 if (ObjCSynthesizedProtocols.count(PDecl))
2582 continue;
2583
2584 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2585 unsigned NumMethods = PDecl->getNumInstanceMethods();
2586 /* struct _objc_protocol_method_list {
2587 int protocol_method_count;
2588 struct protocol_methods protocols[];
2589 }
2590 */
2591 Result += "\nstatic struct {\n";
2592 Result += "\tint protocol_method_count;\n";
2593 Result += "\tstruct protocol_methods protocols[";
2594 Result += utostr(NumMethods);
2595 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002596 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002597 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
2598 "{\n\t" + utostr(NumMethods) + "\n";
2599
2600 // Output instance methods declared in this protocol.
2601 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
2602 E = PDecl->instmeth_end(); I != E; ++I) {
2603 if (I == PDecl->instmeth_begin())
2604 Result += "\t ,{{(SEL)\"";
2605 else
2606 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002607 Result += (*I)->getSelector().getAsString().c_str();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002608 std::string MethodTypeString;
2609 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2610 Result += "\", \"";
2611 Result += MethodTypeString;
2612 Result += "\"}\n";
2613 }
2614 Result += "\t }\n};\n";
2615 }
2616
2617 // Output class methods declared in this protocol.
2618 int NumMethods = PDecl->getNumClassMethods();
2619 if (NumMethods > 0) {
2620 /* struct _objc_protocol_method_list {
2621 int protocol_method_count;
2622 struct protocol_methods protocols[];
2623 }
2624 */
2625 Result += "\nstatic struct {\n";
2626 Result += "\tint protocol_method_count;\n";
2627 Result += "\tstruct protocol_methods protocols[";
2628 Result += utostr(NumMethods);
2629 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002630 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002631 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2632 "{\n\t";
2633 Result += utostr(NumMethods);
2634 Result += "\n";
2635
2636 // Output instance methods declared in this protocol.
2637 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
2638 E = PDecl->classmeth_end(); I != E; ++I) {
2639 if (I == PDecl->classmeth_begin())
2640 Result += "\t ,{{(SEL)\"";
2641 else
2642 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002643 Result += (*I)->getSelector().getAsString().c_str();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002644 std::string MethodTypeString;
2645 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2646 Result += "\", \"";
2647 Result += MethodTypeString;
2648 Result += "\"}\n";
2649 }
2650 Result += "\t }\n};\n";
2651 }
2652
2653 // Output:
2654 /* struct _objc_protocol {
2655 // Objective-C 1.0 extensions
2656 struct _objc_protocol_extension *isa;
2657 char *protocol_name;
2658 struct _objc_protocol **protocol_list;
2659 struct _objc_protocol_method_list *instance_methods;
2660 struct _objc_protocol_method_list *class_methods;
2661 };
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002662 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002663 static bool objc_protocol = false;
2664 if (!objc_protocol) {
2665 Result += "\nstruct _objc_protocol {\n";
2666 Result += "\tstruct _objc_protocol_extension *isa;\n";
2667 Result += "\tchar *protocol_name;\n";
2668 Result += "\tstruct _objc_protocol **protocol_list;\n";
2669 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2670 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2671 Result += "};\n";
2672
2673 objc_protocol = true;
2674 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002675
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002676 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002677 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002678 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
2679 "{\n\t0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002680 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002681 Result += "\", 0, ";
2682 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2683 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002684 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002685 Result += ", ";
2686 }
2687 else
2688 Result += "0, ";
2689 if (PDecl->getNumClassMethods() > 0) {
2690 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002691 Result += PDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002692 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002693 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002694 else
2695 Result += "0\n";
2696 Result += "};\n";
2697
2698 // Mark this protocol as having been generated.
2699 if (!ObjCSynthesizedProtocols.insert(PDecl))
2700 assert(false && "protocol already synthesized");
2701 }
2702 // Output the top lovel protocol meta-data for the class.
2703 /* struct _objc_protocol_list {
2704 struct _objc_protocol_list *next;
2705 int protocol_count;
2706 struct _objc_protocol *class_protocols[];
2707 }
2708 */
2709 Result += "\nstatic struct {\n";
2710 Result += "\tstruct _objc_protocol_list *next;\n";
2711 Result += "\tint protocol_count;\n";
2712 Result += "\tstruct _objc_protocol *class_protocols[";
2713 Result += utostr(Protocols.size());
2714 Result += "];\n} _OBJC_";
2715 Result += prefix;
2716 Result += "_PROTOCOLS_";
2717 Result += ClassName;
2718 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2719 "{\n\t0, ";
2720 Result += utostr(Protocols.size());
2721 Result += "\n";
2722
2723 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002724 Result += Protocols[0]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002725 Result += " \n";
2726
2727 for (unsigned i = 1; i != Protocols.size(); i++) {
2728 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002729 Result += Protocols[i]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002730 Result += "\n";
2731 }
2732 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002733}
2734
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002735/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002736/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00002737void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002738 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002739 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002740 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002741 ObjCCategoryDecl *CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002742 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2743 CDecl = CDecl->getNextClassCategory())
2744 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2745 break;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002746
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002747 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00002748 FullCategoryName += '_';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002749 FullCategoryName += IDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00002750
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002751 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002752 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002753 true, "CATEGORY_", FullCategoryName.c_str(),
2754 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002755
2756 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002757 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002758 false, "CATEGORY_", FullCategoryName.c_str(),
2759 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002760
2761 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002762 // Null CDecl is case of a category implementation with no category interface
2763 if (CDecl)
Chris Lattner780f3292008-07-21 21:32:27 +00002764 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Chris Lattnereb44eee2007-12-23 01:40:15 +00002765 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002766
2767 /* struct _objc_category {
2768 char *category_name;
2769 char *class_name;
2770 struct _objc_method_list *instance_methods;
2771 struct _objc_method_list *class_methods;
2772 struct _objc_protocol_list *protocols;
2773 // Objective-C 1.0 extensions
2774 uint32_t size; // sizeof (struct _objc_category)
2775 struct _objc_property_list *instance_properties; // category's own
2776 // @property decl.
2777 };
2778 */
2779
2780 static bool objc_category = false;
2781 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002782 Result += "\nstruct _objc_category {\n";
2783 Result += "\tchar *category_name;\n";
2784 Result += "\tchar *class_name;\n";
2785 Result += "\tstruct _objc_method_list *instance_methods;\n";
2786 Result += "\tstruct _objc_method_list *class_methods;\n";
2787 Result += "\tstruct _objc_protocol_list *protocols;\n";
2788 Result += "\tunsigned int size;\n";
2789 Result += "\tstruct _objc_property_list *instance_properties;\n";
2790 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002791 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002792 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002793 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2794 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002795 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002796 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002797 Result += "\"\n\t, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002798 Result += ClassDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002799 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002800
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002801 if (IDecl->getNumInstanceMethods() > 0) {
2802 Result += "\t, (struct _objc_method_list *)"
2803 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2804 Result += FullCategoryName;
2805 Result += "\n";
2806 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002807 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002808 Result += "\t, 0\n";
2809 if (IDecl->getNumClassMethods() > 0) {
2810 Result += "\t, (struct _objc_method_list *)"
2811 "&_OBJC_CATEGORY_CLASS_METHODS_";
2812 Result += FullCategoryName;
2813 Result += "\n";
2814 }
2815 else
2816 Result += "\t, 0\n";
2817
Chris Lattner780f3292008-07-21 21:32:27 +00002818 if (CDecl && !CDecl->getReferencedProtocols().empty()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002819 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2820 Result += FullCategoryName;
2821 Result += "\n";
2822 }
2823 else
2824 Result += "\t, 0\n";
2825 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002826}
2827
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002828/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2829/// ivar offset.
Steve Naroffb29b4272008-04-14 22:03:09 +00002830void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002831 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002832 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00002833 if (ivar->isBitField()) {
2834 // FIXME: The hack below doesn't work for bitfields. For now, we simply
2835 // place all bitfields at offset 0.
2836 Result += "0";
2837 } else {
2838 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002839 Result += IDecl->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00002840 if (LangOpts.Microsoft)
2841 Result += "_IMPL";
2842 Result += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002843 Result += ivar->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00002844 Result += ")";
2845 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002846}
2847
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002848//===----------------------------------------------------------------------===//
2849// Meta Data Emission
2850//===----------------------------------------------------------------------===//
2851
Steve Naroffb29b4272008-04-14 22:03:09 +00002852void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002853 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002854 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002855
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002856 // Explictly declared @interface's are already synthesized.
2857 if (CDecl->ImplicitInterfaceDecl()) {
2858 // FIXME: Implementation of a class with no @interface (legacy) doese not
2859 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002860 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002861 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002862
Chris Lattnerbe6df082007-12-12 07:56:42 +00002863 // Build _objc_ivar_list metadata for classes ivars if needed
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002864 unsigned NumIvars = !IDecl->ivar_empty()
2865 ? IDecl->ivar_size()
2866 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002867 if (NumIvars > 0) {
2868 static bool objc_ivar = false;
2869 if (!objc_ivar) {
2870 /* struct _objc_ivar {
2871 char *ivar_name;
2872 char *ivar_type;
2873 int ivar_offset;
2874 };
2875 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002876 Result += "\nstruct _objc_ivar {\n";
2877 Result += "\tchar *ivar_name;\n";
2878 Result += "\tchar *ivar_type;\n";
2879 Result += "\tint ivar_offset;\n";
2880 Result += "};\n";
2881
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002882 objc_ivar = true;
2883 }
2884
Steve Naroff946a6932008-03-11 00:12:29 +00002885 /* struct {
2886 int ivar_count;
2887 struct _objc_ivar ivar_list[nIvars];
2888 };
2889 */
2890 Result += "\nstatic struct {\n";
2891 Result += "\tint ivar_count;\n";
2892 Result += "\tstruct _objc_ivar ivar_list[";
2893 Result += utostr(NumIvars);
2894 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002895 Result += IDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00002896 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002897 "{\n\t";
2898 Result += utostr(NumIvars);
2899 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002900
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002901 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002902 if (!IDecl->ivar_empty()) {
Chris Lattnerbe6df082007-12-12 07:56:42 +00002903 IVI = IDecl->ivar_begin();
2904 IVE = IDecl->ivar_end();
2905 } else {
2906 IVI = CDecl->ivar_begin();
2907 IVE = CDecl->ivar_end();
2908 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002909 Result += "\t,{{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002910 Result += (*IVI)->getNameAsString();
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";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002918 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002919 Result += "\t ,{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002920 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002921 Result += "\", \"";
2922 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002923 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002924 Result += StrEncoding;
2925 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002926 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002927 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002928 }
2929
2930 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002931 }
2932
2933 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002934 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00002935 true, "", IDecl->getNameAsCString(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002936
2937 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002938 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00002939 false, "", IDecl->getNameAsCString(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002940
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002941 // Protocols referenced in class declaration?
Chris Lattner780f3292008-07-21 21:32:27 +00002942 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00002943 "CLASS", CDecl->getNameAsCString(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002944
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002945
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002946 // Declaration of class/meta-class metadata
2947 /* struct _objc_class {
2948 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002949 const char *super_class_name;
2950 char *name;
2951 long version;
2952 long info;
2953 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002954 struct _objc_ivar_list *ivars;
2955 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002956 struct objc_cache *cache;
2957 struct objc_protocol_list *protocols;
2958 const char *ivar_layout;
2959 struct _objc_class_ext *ext;
2960 };
2961 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002962 static bool objc_class = false;
2963 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002964 Result += "\nstruct _objc_class {\n";
2965 Result += "\tstruct _objc_class *isa;\n";
2966 Result += "\tconst char *super_class_name;\n";
2967 Result += "\tchar *name;\n";
2968 Result += "\tlong version;\n";
2969 Result += "\tlong info;\n";
2970 Result += "\tlong instance_size;\n";
2971 Result += "\tstruct _objc_ivar_list *ivars;\n";
2972 Result += "\tstruct _objc_method_list *methods;\n";
2973 Result += "\tstruct objc_cache *cache;\n";
2974 Result += "\tstruct _objc_protocol_list *protocols;\n";
2975 Result += "\tconst char *ivar_layout;\n";
2976 Result += "\tstruct _objc_class_ext *ext;\n";
2977 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002978 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002979 }
2980
2981 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002982 ObjCInterfaceDecl *RootClass = 0;
2983 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002984 while (SuperClass) {
2985 RootClass = SuperClass;
2986 SuperClass = SuperClass->getSuperClass();
2987 }
2988 SuperClass = CDecl->getSuperClass();
2989
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002990 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002991 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00002992 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002993 "{\n\t(struct _objc_class *)\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002994 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002995 Result += "\"";
2996
2997 if (SuperClass) {
2998 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002999 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003000 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003001 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003002 Result += "\"";
3003 }
3004 else {
3005 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003006 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003007 Result += "\"";
3008 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003009 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003010 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003011 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffb26d7132007-12-05 21:49:40 +00003012 if (IDecl->getNumClassMethods() > 0) {
Steve Naroff23f41272008-03-11 18:14:26 +00003013 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003014 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003015 Result += "\n";
3016 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003017 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003018 Result += ", 0\n";
Chris Lattner3db6cae2008-07-21 18:19:38 +00003019 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003020 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003021 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003022 Result += ",0,0\n";
3023 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003024 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003025 Result += "\t,0,0,0,0\n";
3026 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003027
3028 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003029 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003030 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003031 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003032 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003033 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003034 if (SuperClass) {
3035 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003036 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003037 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003038 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003039 Result += "\"";
3040 }
3041 else {
3042 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003043 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003044 Result += "\"";
3045 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003046 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003047 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003048 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003049 Result += ",0";
3050 else {
3051 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003052 Result += ",sizeof(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003053 Result += CDecl->getNameAsString();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003054 if (LangOpts.Microsoft)
3055 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003056 Result += ")";
3057 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003058 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00003059 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003060 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003061 Result += "\n\t";
3062 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003063 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003064 Result += ",0";
3065 if (IDecl->getNumInstanceMethods() > 0) {
Steve Naroff946a6932008-03-11 00:12:29 +00003066 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003067 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003068 Result += ", 0\n\t";
3069 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003070 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003071 Result += ",0,0";
Chris Lattner3db6cae2008-07-21 18:19:38 +00003072 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003073 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003074 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003075 Result += ", 0,0\n";
3076 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003077 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003078 Result += ",0,0,0\n";
3079 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003080}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003081
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003082/// RewriteImplementations - This routine rewrites all method implementations
3083/// and emits meta-data.
3084
Steve Narofface66252008-11-13 20:07:04 +00003085void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003086 int ClsDefCount = ClassImplementation.size();
3087 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003088
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003089 // Rewrite implemented methods
3090 for (int i = 0; i < ClsDefCount; i++)
3091 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003092
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003093 for (int i = 0; i < CatDefCount; i++)
3094 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00003095}
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003096
Steve Narofface66252008-11-13 20:07:04 +00003097void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3098 int ClsDefCount = ClassImplementation.size();
3099 int CatDefCount = CategoryImplementation.size();
3100
Steve Naroff5df5b762008-05-07 21:23:49 +00003101 // This is needed for determining instance variable offsets.
Steve Naroffa11440b2008-08-05 18:47:23 +00003102 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003103 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003104 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003105 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003106
3107 // For each implemented category, write out all its meta data.
3108 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003109 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003110
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003111 // Write objc_symtab metadata
3112 /*
3113 struct _objc_symtab
3114 {
3115 long sel_ref_cnt;
3116 SEL *refs;
3117 short cls_def_cnt;
3118 short cat_def_cnt;
3119 void *defs[cls_def_cnt + cat_def_cnt];
3120 };
3121 */
3122
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003123 Result += "\nstruct _objc_symtab {\n";
3124 Result += "\tlong sel_ref_cnt;\n";
3125 Result += "\tSEL *refs;\n";
3126 Result += "\tshort cls_def_cnt;\n";
3127 Result += "\tshort cat_def_cnt;\n";
3128 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3129 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003130
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003131 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00003132 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003133 Result += "\t0, 0, " + utostr(ClsDefCount)
3134 + ", " + utostr(CatDefCount) + "\n";
3135 for (int i = 0; i < ClsDefCount; i++) {
3136 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003137 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003138 Result += "\n";
3139 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003140
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003141 for (int i = 0; i < CatDefCount; i++) {
3142 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003143 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003144 Result += "_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003145 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003146 Result += "\n";
3147 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003148
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003149 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003150
3151 // Write objc_module metadata
3152
3153 /*
3154 struct _objc_module {
3155 long version;
3156 long size;
3157 const char *name;
3158 struct _objc_symtab *symtab;
3159 }
3160 */
3161
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003162 Result += "\nstruct _objc_module {\n";
3163 Result += "\tlong version;\n";
3164 Result += "\tlong size;\n";
3165 Result += "\tconst char *name;\n";
3166 Result += "\tstruct _objc_symtab *symtab;\n";
3167 Result += "};\n\n";
3168 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00003169 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003170 Result += "\t" + utostr(OBJC_ABI_VERSION) +
3171 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003172 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003173
3174 if (LangOpts.Microsoft) {
3175 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00003176 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003177 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3178 Result += "&_OBJC_MODULES;\n";
3179 Result += "#pragma data_seg(pop)\n\n";
3180 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003181}
Chris Lattner311ff022007-10-16 22:36:42 +00003182
Steve Naroff54055232008-10-27 17:20:55 +00003183std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3184 const char *funcName,
3185 std::string Tag) {
3186 const FunctionType *AFT = CE->getFunctionType();
3187 QualType RT = AFT->getResultType();
3188 std::string StructRef = "struct " + Tag;
3189 std::string S = "static " + RT.getAsString() + " __" +
3190 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003191
Steve Naroff54055232008-10-27 17:20:55 +00003192 BlockDecl *BD = CE->getBlockDecl();
3193
3194 if (isa<FunctionTypeNoProto>(AFT)) {
3195 S += "()";
3196 } else if (BD->param_empty()) {
3197 S += "(" + StructRef + " *__cself)";
3198 } else {
3199 const FunctionTypeProto *FT = cast<FunctionTypeProto>(AFT);
3200 assert(FT && "SynthesizeBlockFunc: No function proto");
3201 S += '(';
3202 // first add the implicit argument.
3203 S += StructRef + " *__cself, ";
3204 std::string ParamStr;
3205 for (BlockDecl::param_iterator AI = BD->param_begin(),
3206 E = BD->param_end(); AI != E; ++AI) {
3207 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003208 ParamStr = (*AI)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003209 (*AI)->getType().getAsStringInternal(ParamStr);
3210 S += ParamStr;
3211 }
3212 if (FT->isVariadic()) {
3213 if (!BD->param_empty()) S += ", ";
3214 S += "...";
3215 }
3216 S += ')';
3217 }
3218 S += " {\n";
3219
3220 // Create local declarations to avoid rewriting all closure decl ref exprs.
3221 // First, emit a declaration for all "by ref" decls.
3222 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3223 E = BlockByRefDecls.end(); I != E; ++I) {
3224 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003225 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003226 Context->getPointerType((*I)->getType()).getAsStringInternal(Name);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003227 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Steve Naroff54055232008-10-27 17:20:55 +00003228 }
3229 // Next, emit a declaration for all "by copy" declarations.
3230 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3231 E = BlockByCopyDecls.end(); I != E; ++I) {
3232 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003233 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003234 // Handle nested closure invocation. For example:
3235 //
3236 // void (^myImportedClosure)(void);
3237 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3238 //
3239 // void (^anotherClosure)(void);
3240 // anotherClosure = ^(void) {
3241 // myImportedClosure(); // import and invoke the closure
3242 // };
3243 //
3244 if (isBlockPointerType((*I)->getType()))
3245 S += "struct __block_impl *";
3246 else
3247 (*I)->getType().getAsStringInternal(Name);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003248 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff54055232008-10-27 17:20:55 +00003249 }
3250 std::string RewrittenStr = RewrittenBlockExprs[CE];
3251 const char *cstr = RewrittenStr.c_str();
3252 while (*cstr++ != '{') ;
3253 S += cstr;
3254 S += "\n";
3255 return S;
3256}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003257
Steve Naroff54055232008-10-27 17:20:55 +00003258std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3259 const char *funcName,
3260 std::string Tag) {
3261 std::string StructRef = "struct " + Tag;
3262 std::string S = "static void __";
3263
3264 S += funcName;
3265 S += "_block_copy_" + utostr(i);
3266 S += "(" + StructRef;
3267 S += "*dst, " + StructRef;
3268 S += "*src) {";
3269 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3270 E = ImportedBlockDecls.end(); I != E; ++I) {
3271 S += "_Block_copy_assign(&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003272 S += (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003273 S += ", src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003274 S += (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003275 S += ");}";
3276 }
3277 S += "\nstatic void __";
3278 S += funcName;
3279 S += "_block_dispose_" + utostr(i);
3280 S += "(" + StructRef;
3281 S += "*src) {";
3282 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3283 E = ImportedBlockDecls.end(); I != E; ++I) {
3284 S += "_Block_destroy(src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003285 S += (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003286 S += ");";
3287 }
3288 S += "}\n";
3289 return S;
3290}
3291
3292std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3293 bool hasCopyDisposeHelpers) {
Steve Naroffced80a82008-10-30 12:09:33 +00003294 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00003295 std::string Constructor = " " + Tag;
3296
3297 S += " {\n struct __block_impl impl;\n";
3298
3299 if (hasCopyDisposeHelpers)
3300 S += " void *copy;\n void *dispose;\n";
3301
3302 Constructor += "(void *fp";
3303
3304 if (hasCopyDisposeHelpers)
3305 Constructor += ", void *copyHelp, void *disposeHelp";
3306
3307 if (BlockDeclRefs.size()) {
3308 // Output all "by copy" declarations.
3309 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3310 E = BlockByCopyDecls.end(); I != E; ++I) {
3311 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003312 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003313 std::string ArgName = "_" + FieldName;
3314 // Handle nested closure invocation. For example:
3315 //
3316 // void (^myImportedBlock)(void);
3317 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3318 //
3319 // void (^anotherBlock)(void);
3320 // anotherBlock = ^(void) {
3321 // myImportedBlock(); // import and invoke the closure
3322 // };
3323 //
3324 if (isBlockPointerType((*I)->getType())) {
3325 S += "struct __block_impl *";
3326 Constructor += ", void *" + ArgName;
3327 } else {
3328 (*I)->getType().getAsStringInternal(FieldName);
3329 (*I)->getType().getAsStringInternal(ArgName);
3330 Constructor += ", " + ArgName;
3331 }
3332 S += FieldName + ";\n";
3333 }
3334 // Output all "by ref" declarations.
3335 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3336 E = BlockByRefDecls.end(); I != E; ++I) {
3337 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003338 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003339 std::string ArgName = "_" + FieldName;
3340 // Handle nested closure invocation. For example:
3341 //
3342 // void (^myImportedBlock)(void);
3343 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3344 //
3345 // void (^anotherBlock)(void);
3346 // anotherBlock = ^(void) {
3347 // myImportedBlock(); // import and invoke the closure
3348 // };
3349 //
3350 if (isBlockPointerType((*I)->getType())) {
3351 S += "struct __block_impl *";
3352 Constructor += ", void *" + ArgName;
3353 } else {
3354 Context->getPointerType((*I)->getType()).getAsStringInternal(FieldName);
3355 Context->getPointerType((*I)->getType()).getAsStringInternal(ArgName);
3356 Constructor += ", " + ArgName;
3357 }
3358 S += FieldName + "; // by ref\n";
3359 }
3360 // Finish writing the constructor.
3361 // FIXME: handle NSConcreteGlobalBlock.
3362 Constructor += ", int flags=0) {\n";
3363 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3364 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3365
3366 if (hasCopyDisposeHelpers)
3367 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3368
3369 // Initialize all "by copy" arguments.
3370 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3371 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003372 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003373 Constructor += " ";
3374 if (isBlockPointerType((*I)->getType()))
3375 Constructor += Name + " = (struct __block_impl *)_";
3376 else
3377 Constructor += Name + " = _";
3378 Constructor += Name + ";\n";
3379 }
3380 // Initialize all "by ref" arguments.
3381 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3382 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003383 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003384 Constructor += " ";
3385 if (isBlockPointerType((*I)->getType()))
3386 Constructor += Name + " = (struct __block_impl *)_";
3387 else
3388 Constructor += Name + " = _";
3389 Constructor += Name + ";\n";
3390 }
3391 } else {
3392 // Finish writing the constructor.
3393 // FIXME: handle NSConcreteGlobalBlock.
3394 Constructor += ", int flags=0) {\n";
3395 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3396 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3397 if (hasCopyDisposeHelpers)
3398 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3399 }
3400 Constructor += " ";
3401 Constructor += "}\n";
3402 S += Constructor;
3403 S += "};\n";
3404 return S;
3405}
3406
3407void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3408 const char *FunName) {
3409 // Insert closures that were part of the function.
3410 for (unsigned i = 0; i < Blocks.size(); i++) {
3411
3412 CollectBlockDeclRefInfo(Blocks[i]);
3413
3414 std::string Tag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
3415
3416 std::string CI = SynthesizeBlockImpl(Blocks[i], Tag,
3417 ImportedBlockDecls.size() > 0);
3418
3419 InsertText(FunLocStart, CI.c_str(), CI.size());
3420
3421 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, Tag);
3422
3423 InsertText(FunLocStart, CF.c_str(), CF.size());
3424
3425 if (ImportedBlockDecls.size()) {
3426 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, Tag);
3427 InsertText(FunLocStart, HF.c_str(), HF.size());
3428 }
3429
3430 BlockDeclRefs.clear();
3431 BlockByRefDecls.clear();
3432 BlockByCopyDecls.clear();
3433 BlockCallExprs.clear();
3434 ImportedBlockDecls.clear();
3435 }
3436 Blocks.clear();
3437 RewrittenBlockExprs.clear();
3438}
3439
3440void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3441 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner8ec03f52008-11-24 03:54:41 +00003442 const char *FuncName = FD->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003443
3444 SynthesizeBlockLiterals(FunLocStart, FuncName);
3445}
3446
3447void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00003448 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3449 //SourceLocation FunLocStart = MD->getLocStart();
3450 // FIXME: This hack works around a bug in Rewrite.InsertText().
3451 SourceLocation FunLocStart = MD->getLocStart().getFileLocWithOffset(-1);
Chris Lattner077bf5e2008-11-24 03:33:13 +00003452 std::string FuncName = MD->getSelector().getAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003453 // Convert colons to underscores.
3454 std::string::size_type loc = 0;
3455 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3456 FuncName.replace(loc, 1, "_");
3457
3458 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
3459}
3460
3461void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
3462 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3463 CI != E; ++CI)
3464 if (*CI) {
3465 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3466 GetBlockDeclRefExprs(CBE->getBody());
3467 else
3468 GetBlockDeclRefExprs(*CI);
3469 }
3470 // Handle specific things.
3471 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
3472 // FIXME: Handle enums.
3473 if (!isa<FunctionDecl>(CDRE->getDecl()))
3474 BlockDeclRefs.push_back(CDRE);
3475 return;
3476}
3477
3478void RewriteObjC::GetBlockCallExprs(Stmt *S) {
3479 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3480 CI != E; ++CI)
3481 if (*CI) {
3482 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3483 GetBlockCallExprs(CBE->getBody());
3484 else
3485 GetBlockCallExprs(*CI);
3486 }
3487
3488 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
3489 if (CE->getCallee()->getType()->isBlockPointerType()) {
3490 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
3491 }
3492 }
3493 return;
3494}
3495
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003496Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00003497 // Navigate to relevant type information.
3498 const char *closureName = 0;
3499 const BlockPointerType *CPT = 0;
3500
3501 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003502 closureName = DRE->getDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003503 CPT = DRE->getType()->getAsBlockPointerType();
3504 } else if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003505 closureName = CDRE->getDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003506 CPT = CDRE->getType()->getAsBlockPointerType();
3507 } else if (MemberExpr *MExpr = dyn_cast<MemberExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003508 closureName = MExpr->getMemberDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003509 CPT = MExpr->getType()->getAsBlockPointerType();
3510 } else {
3511 assert(1 && "RewriteBlockClass: Bad type");
3512 }
3513 assert(CPT && "RewriteBlockClass: Bad type");
3514 const FunctionType *FT = CPT->getPointeeType()->getAsFunctionType();
3515 assert(FT && "RewriteBlockClass: Bad type");
3516 const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(FT);
3517 // FTP will be null for closures that don't take arguments.
3518
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003519 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
3520 SourceLocation(),
3521 &Context->Idents.get("__block_impl"));
3522 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00003523
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003524 // Generate a funky cast.
3525 llvm::SmallVector<QualType, 8> ArgTypes;
3526
3527 // Push the block argument type.
3528 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00003529 if (FTP) {
3530 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003531 E = FTP->arg_type_end(); I && (I != E); ++I) {
3532 QualType t = *I;
3533 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3534 if (isBlockPointerType(t)) {
3535 const BlockPointerType *BPT = t->getAsBlockPointerType();
3536 t = Context->getPointerType(BPT->getPointeeType());
3537 }
3538 ArgTypes.push_back(t);
3539 }
Steve Naroff54055232008-10-27 17:20:55 +00003540 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003541 // Now do the pointer to function cast.
3542 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
3543 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
3544
3545 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Steve Naroff54055232008-10-27 17:20:55 +00003546
Steve Naroffb2f9e512008-11-03 23:29:32 +00003547 CastExpr *BlkCast = new CStyleCastExpr(PtrBlock, Exp->getCallee(), PtrBlock, SourceLocation(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003548 // Don't forget the parens to enforce the proper binding.
3549 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), BlkCast);
3550 //PE->dump();
Steve Naroff54055232008-10-27 17:20:55 +00003551
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003552 FieldDecl *FD = FieldDecl::Create(*Context, SourceLocation(),
3553 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy);
3554 MemberExpr *ME = new MemberExpr(PE, true, FD, SourceLocation(), FD->getType());
3555
Steve Naroffb2f9e512008-11-03 23:29:32 +00003556 CastExpr *FunkCast = new CStyleCastExpr(PtrToFuncCastType, ME, PtrToFuncCastType, SourceLocation(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003557 PE = new ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
3558
3559 llvm::SmallVector<Expr*, 8> BlkExprs;
3560 // Add the implicit argument.
3561 BlkExprs.push_back(BlkCast);
3562 // Add the user arguments.
Steve Naroff54055232008-10-27 17:20:55 +00003563 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3564 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003565 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00003566 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003567 CallExpr *CE = new CallExpr(PE, &BlkExprs[0], BlkExprs.size(), Exp->getType(), SourceLocation());
3568 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00003569}
3570
3571void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003572 Stmt *BlockCall = SynthesizeBlockCall(Exp);
3573 ReplaceStmt(Exp, BlockCall);
Steve Naroff54055232008-10-27 17:20:55 +00003574}
3575
3576void RewriteObjC::RewriteBlockDeclRefExpr(BlockDeclRefExpr *BDRE) {
3577 // FIXME: Add more elaborate code generation required by the ABI.
3578 InsertText(BDRE->getLocStart(), "*", 1);
3579}
3580
Steve Naroffb2f9e512008-11-03 23:29:32 +00003581void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3582 SourceLocation LocStart = CE->getLParenLoc();
3583 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00003584
3585 // Need to avoid trying to rewrite synthesized casts.
3586 if (LocStart.isInvalid())
3587 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00003588 // Need to avoid trying to rewrite casts contained in macros.
3589 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3590 return;
Steve Narofffa15fd92008-10-28 20:29:00 +00003591
Steve Naroff54055232008-10-27 17:20:55 +00003592 const char *startBuf = SM->getCharacterData(LocStart);
3593 const char *endBuf = SM->getCharacterData(LocEnd);
3594
3595 // advance the location to startArgList.
3596 const char *argPtr = startBuf;
3597
3598 while (*argPtr++ && (argPtr < endBuf)) {
3599 switch (*argPtr) {
3600 case '^':
3601 // Replace the '^' with '*'.
3602 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
3603 ReplaceText(LocStart, 1, "*", 1);
3604 break;
3605 }
3606 }
3607 return;
3608}
3609
3610void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
3611 SourceLocation DeclLoc = FD->getLocation();
3612 unsigned parenCount = 0;
3613
3614 // We have 1 or more arguments that have closure pointers.
3615 const char *startBuf = SM->getCharacterData(DeclLoc);
3616 const char *startArgList = strchr(startBuf, '(');
3617
3618 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
3619
3620 parenCount++;
3621 // advance the location to startArgList.
3622 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
3623 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
3624
3625 const char *argPtr = startArgList;
3626
3627 while (*argPtr++ && parenCount) {
3628 switch (*argPtr) {
3629 case '^':
3630 // Replace the '^' with '*'.
3631 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
3632 ReplaceText(DeclLoc, 1, "*", 1);
3633 break;
3634 case '(':
3635 parenCount++;
3636 break;
3637 case ')':
3638 parenCount--;
3639 break;
3640 }
3641 }
3642 return;
3643}
3644
3645bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
3646 const FunctionTypeProto *FTP;
3647 const PointerType *PT = QT->getAsPointerType();
3648 if (PT) {
3649 FTP = PT->getPointeeType()->getAsFunctionTypeProto();
3650 } else {
3651 const BlockPointerType *BPT = QT->getAsBlockPointerType();
3652 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
3653 FTP = BPT->getPointeeType()->getAsFunctionTypeProto();
3654 }
3655 if (FTP) {
3656 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
3657 E = FTP->arg_type_end(); I != E; ++I)
3658 if (isBlockPointerType(*I))
3659 return true;
3660 }
3661 return false;
3662}
3663
3664void RewriteObjC::GetExtentOfArgList(const char *Name,
3665 const char *&LParen, const char *&RParen) {
3666 const char *argPtr = strchr(Name, '(');
3667 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
3668
3669 LParen = argPtr; // output the start.
3670 argPtr++; // skip past the left paren.
3671 unsigned parenCount = 1;
3672
3673 while (*argPtr && parenCount) {
3674 switch (*argPtr) {
3675 case '(': parenCount++; break;
3676 case ')': parenCount--; break;
3677 default: break;
3678 }
3679 if (parenCount) argPtr++;
3680 }
3681 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
3682 RParen = argPtr; // output the end
3683}
3684
3685void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
3686 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3687 RewriteBlockPointerFunctionArgs(FD);
3688 return;
3689 }
3690 // Handle Variables and Typedefs.
3691 SourceLocation DeclLoc = ND->getLocation();
3692 QualType DeclT;
3693 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3694 DeclT = VD->getType();
3695 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
3696 DeclT = TDD->getUnderlyingType();
3697 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
3698 DeclT = FD->getType();
3699 else
3700 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
3701
3702 const char *startBuf = SM->getCharacterData(DeclLoc);
3703 const char *endBuf = startBuf;
3704 // scan backward (from the decl location) for the end of the previous decl.
3705 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
3706 startBuf--;
3707
3708 // *startBuf != '^' if we are dealing with a pointer to function that
3709 // may take block argument types (which will be handled below).
3710 if (*startBuf == '^') {
3711 // Replace the '^' with '*', computing a negative offset.
3712 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
3713 ReplaceText(DeclLoc, 1, "*", 1);
3714 }
3715 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
3716 // Replace the '^' with '*' for arguments.
3717 DeclLoc = ND->getLocation();
3718 startBuf = SM->getCharacterData(DeclLoc);
3719 const char *argListBegin, *argListEnd;
3720 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
3721 while (argListBegin < argListEnd) {
3722 if (*argListBegin == '^') {
3723 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
3724 ReplaceText(CaretLoc, 1, "*", 1);
3725 }
3726 argListBegin++;
3727 }
3728 }
3729 return;
3730}
3731
3732void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
3733 // Add initializers for any closure decl refs.
3734 GetBlockDeclRefExprs(Exp->getBody());
3735 if (BlockDeclRefs.size()) {
3736 // Unique all "by copy" declarations.
3737 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3738 if (!BlockDeclRefs[i]->isByRef())
3739 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
3740 // Unique all "by ref" declarations.
3741 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3742 if (BlockDeclRefs[i]->isByRef()) {
3743 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
3744 }
3745 // Find any imported blocks...they will need special attention.
3746 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3747 if (isBlockPointerType(BlockDeclRefs[i]->getType())) {
Steve Naroff00072682008-11-13 17:40:07 +00003748 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff54055232008-10-27 17:20:55 +00003749 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
3750 }
3751 }
3752}
3753
Steve Narofffa15fd92008-10-28 20:29:00 +00003754FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
3755 IdentifierInfo *ID = &Context->Idents.get(name);
3756 QualType FType = Context->getFunctionTypeNoProto(Context->VoidPtrTy);
3757 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
3758 ID, FType, FunctionDecl::Extern, false, 0);
3759}
3760
Steve Naroff8e2f57a2008-10-29 18:15:37 +00003761Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Narofffa15fd92008-10-28 20:29:00 +00003762 Blocks.push_back(Exp);
3763
3764 CollectBlockDeclRefInfo(Exp);
3765 std::string FuncName;
3766
3767 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00003768 FuncName = CurFunctionDef->getNameAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00003769 else if (CurMethodDef) {
Chris Lattner077bf5e2008-11-24 03:33:13 +00003770 FuncName = CurMethodDef->getSelector().getAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00003771 // Convert colons to underscores.
3772 std::string::size_type loc = 0;
3773 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3774 FuncName.replace(loc, 1, "_");
Steve Naroff8e2f57a2008-10-29 18:15:37 +00003775 } else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003776 FuncName = std::string(GlobalVarDecl->getNameAsString());
Steve Narofffa15fd92008-10-28 20:29:00 +00003777
3778 std::string BlockNumber = utostr(Blocks.size()-1);
3779
3780 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
3781 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
3782
3783 // Get a pointer to the function type so we can cast appropriately.
3784 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
3785
3786 FunctionDecl *FD;
3787 Expr *NewRep;
3788
3789 // Simulate a contructor call...
3790 FD = SynthBlockInitFunctionDecl(Tag.c_str());
3791 DeclRefExpr *DRE = new DeclRefExpr(FD, FType, SourceLocation());
3792
3793 llvm::SmallVector<Expr*, 4> InitExprs;
3794
Steve Narofffdc03722008-10-29 21:23:59 +00003795 // Initialize the block function.
Steve Narofffa15fd92008-10-28 20:29:00 +00003796 FD = SynthBlockInitFunctionDecl(Func.c_str());
3797 DeclRefExpr *Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3798 CastExpr *castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00003799 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00003800 InitExprs.push_back(castExpr);
Steve Narofffa15fd92008-10-28 20:29:00 +00003801
3802 if (ImportedBlockDecls.size()) {
3803 std::string Buf = "__" + FuncName + "_block_copy_" + BlockNumber;
Steve Narofffdc03722008-10-29 21:23:59 +00003804 FD = SynthBlockInitFunctionDecl(Buf.c_str());
3805 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3806 castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00003807 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffdc03722008-10-29 21:23:59 +00003808 InitExprs.push_back(castExpr);
3809
Steve Narofffa15fd92008-10-28 20:29:00 +00003810 Buf = "__" + FuncName + "_block_dispose_" + BlockNumber;
Steve Narofffdc03722008-10-29 21:23:59 +00003811 FD = SynthBlockInitFunctionDecl(Buf.c_str());
3812 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3813 castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00003814 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffdc03722008-10-29 21:23:59 +00003815 InitExprs.push_back(castExpr);
Steve Narofffa15fd92008-10-28 20:29:00 +00003816 }
3817 // Add initializers for any closure decl refs.
3818 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00003819 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00003820 // Output all "by copy" declarations.
3821 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3822 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00003823 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00003824 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner8ec03f52008-11-24 03:54:41 +00003825 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00003826 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00003827 } else if (isBlockPointerType((*I)->getType())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003828 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00003829 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3830 Exp = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00003831 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00003832 } else {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003833 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00003834 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00003835 }
Steve Narofffdc03722008-10-29 21:23:59 +00003836 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00003837 }
3838 // Output all "by ref" declarations.
3839 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3840 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003841 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00003842 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3843 Exp = new UnaryOperator(Exp, UnaryOperator::AddrOf,
3844 Context->getPointerType(Exp->getType()),
3845 SourceLocation());
Steve Naroff707b0fe2008-11-14 21:36:12 +00003846 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00003847 }
3848 }
Steve Narofffa15fd92008-10-28 20:29:00 +00003849 NewRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
3850 FType, SourceLocation());
3851 NewRep = new UnaryOperator(NewRep, UnaryOperator::AddrOf,
3852 Context->getPointerType(NewRep->getType()),
3853 SourceLocation());
Steve Naroffb2f9e512008-11-03 23:29:32 +00003854 NewRep = new CStyleCastExpr(FType, NewRep, FType, SourceLocation(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00003855 BlockDeclRefs.clear();
3856 BlockByRefDecls.clear();
3857 BlockByCopyDecls.clear();
3858 ImportedBlockDecls.clear();
3859 return NewRep;
3860}
3861
3862//===----------------------------------------------------------------------===//
3863// Function Body / Expression rewriting
3864//===----------------------------------------------------------------------===//
3865
3866Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
3867 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
3868 isa<DoStmt>(S) || isa<ForStmt>(S))
3869 Stmts.push_back(S);
3870 else if (isa<ObjCForCollectionStmt>(S)) {
3871 Stmts.push_back(S);
3872 ObjCBcLabelNo.push_back(++BcLabelCount);
3873 }
3874
3875 SourceRange OrigStmtRange = S->getSourceRange();
3876
3877 // Perform a bottom up rewrite of all children.
3878 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3879 CI != E; ++CI)
3880 if (*CI) {
3881 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
3882 if (newStmt)
3883 *CI = newStmt;
3884 }
3885
3886 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
3887 // Rewrite the block body in place.
3888 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
3889
3890 // Now we snarf the rewritten text and stash it away for later use.
Steve Naroff8e2f57a2008-10-29 18:15:37 +00003891 std::string Str = Rewrite.getRewritenText(BE->getSourceRange());
3892 RewrittenBlockExprs[BE] = Str;
Steve Narofffa15fd92008-10-28 20:29:00 +00003893
3894 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
3895 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00003896 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00003897 return blockTranscribed;
3898 }
3899 // Handle specific things.
3900 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
3901 return RewriteAtEncode(AtEncode);
3902
3903 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
3904 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
3905
3906 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
3907 return RewriteAtSelector(AtSelector);
3908
3909 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
3910 return RewriteObjCStringLiteral(AtString);
3911
3912 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
3913 // Before we rewrite it, put the original message expression in a comment.
3914 SourceLocation startLoc = MessExpr->getLocStart();
3915 SourceLocation endLoc = MessExpr->getLocEnd();
3916
3917 const char *startBuf = SM->getCharacterData(startLoc);
3918 const char *endBuf = SM->getCharacterData(endLoc);
3919
3920 std::string messString;
3921 messString += "// ";
3922 messString.append(startBuf, endBuf-startBuf+1);
3923 messString += "\n";
3924
3925 // FIXME: Missing definition of
3926 // InsertText(clang::SourceLocation, char const*, unsigned int).
3927 // InsertText(startLoc, messString.c_str(), messString.size());
3928 // Tried this, but it didn't work either...
3929 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
3930 return RewriteMessageExpr(MessExpr);
3931 }
3932
3933 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
3934 return RewriteObjCTryStmt(StmtTry);
3935
3936 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
3937 return RewriteObjCSynchronizedStmt(StmtTry);
3938
3939 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
3940 return RewriteObjCThrowStmt(StmtThrow);
3941
3942 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
3943 return RewriteObjCProtocolExpr(ProtocolExp);
3944
3945 if (ObjCForCollectionStmt *StmtForCollection =
3946 dyn_cast<ObjCForCollectionStmt>(S))
3947 return RewriteObjCForCollectionStmt(StmtForCollection,
3948 OrigStmtRange.getEnd());
3949 if (BreakStmt *StmtBreakStmt =
3950 dyn_cast<BreakStmt>(S))
3951 return RewriteBreakStmt(StmtBreakStmt);
3952 if (ContinueStmt *StmtContinueStmt =
3953 dyn_cast<ContinueStmt>(S))
3954 return RewriteContinueStmt(StmtContinueStmt);
3955
3956 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
3957 // and cast exprs.
3958 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
3959 // FIXME: What we're doing here is modifying the type-specifier that
3960 // precedes the first Decl. In the future the DeclGroup should have
3961 // a separate type-specifier that we can rewrite.
3962 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
3963
3964 // Blocks rewrite rules.
3965 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
3966 DI != DE; ++DI) {
Steve Narofffa15fd92008-10-28 20:29:00 +00003967 ScopedDecl *SD = *DI;
3968 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
3969 if (isBlockPointerType(ND->getType()))
3970 RewriteBlockPointerDecl(ND);
3971 else if (ND->getType()->isFunctionPointerType())
3972 CheckFunctionPointerDecl(ND->getType(), ND);
3973 }
3974 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
3975 if (isBlockPointerType(TD->getUnderlyingType()))
3976 RewriteBlockPointerDecl(TD);
3977 else if (TD->getUnderlyingType()->isFunctionPointerType())
3978 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
3979 }
3980 }
3981 }
3982
3983 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
3984 RewriteObjCQualifiedInterfaceTypes(CE);
3985
3986 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
3987 isa<DoStmt>(S) || isa<ForStmt>(S)) {
3988 assert(!Stmts.empty() && "Statement stack is empty");
3989 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
3990 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
3991 && "Statement stack mismatch");
3992 Stmts.pop_back();
3993 }
3994 // Handle blocks rewriting.
3995 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
3996 if (BDRE->isByRef())
3997 RewriteBlockDeclRefExpr(BDRE);
3998 }
3999 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004000 if (CE->getCallee()->getType()->isBlockPointerType()) {
4001 Stmt *BlockCall = SynthesizeBlockCall(CE);
4002 ReplaceStmt(S, BlockCall);
4003 return BlockCall;
4004 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004005 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00004006 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004007 RewriteCastExpr(CE);
4008 }
4009#if 0
4010 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
4011 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
4012 // Get the new text.
4013 std::string SStr;
4014 llvm::raw_string_ostream Buf(SStr);
4015 Replacement->printPretty(Buf);
4016 const std::string &Str = Buf.str();
4017
4018 printf("CAST = %s\n", &Str[0]);
4019 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4020 delete S;
4021 return Replacement;
4022 }
4023#endif
4024 // Return this stmt unmodified.
4025 return S;
4026}
4027
4028/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4029/// main file of the input.
4030void RewriteObjC::HandleDeclInMainFile(Decl *D) {
4031 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4032 // Since function prototypes don't have ParmDecl's, we check the function
4033 // prototype. This enables us to rewrite function declarations and
4034 // definitions using the same code.
4035 RewriteBlocksInFunctionTypeProto(FD->getType(), FD);
4036
4037 if (Stmt *Body = FD->getBody()) {
4038 CurFunctionDef = FD;
4039 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
4040 // This synthesizes and inserts the block "impl" struct, invoke function,
4041 // and any copy/dispose helper functions.
4042 InsertBlockLiteralsWithinFunction(FD);
4043 CurFunctionDef = 0;
4044 }
4045 return;
4046 }
4047 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4048 if (Stmt *Body = MD->getBody()) {
4049 //Body->dump();
4050 CurMethodDef = MD;
4051 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
4052 InsertBlockLiteralsWithinMethod(MD);
4053 CurMethodDef = 0;
4054 }
4055 }
4056 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
4057 ClassImplementation.push_back(CI);
4058 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
4059 CategoryImplementation.push_back(CI);
4060 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
4061 RewriteForwardClassDecl(CD);
4062 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4063 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004064 if (isBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004065 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004066 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004067 CheckFunctionPointerDecl(VD->getType(), VD);
4068 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00004069 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004070 RewriteCastExpr(CE);
4071 }
4072 }
4073 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004074 if (VD->getInit()) {
4075 GlobalVarDecl = VD;
4076 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Douglas Gregor2e1cd422008-11-17 14:58:09 +00004077 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00004078 VD->getNameAsCString());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004079 GlobalVarDecl = 0;
4080
4081 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00004082 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004083 RewriteCastExpr(CE);
4084 }
4085 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004086 return;
4087 }
4088 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
4089 if (isBlockPointerType(TD->getUnderlyingType()))
4090 RewriteBlockPointerDecl(TD);
4091 else if (TD->getUnderlyingType()->isFunctionPointerType())
4092 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4093 return;
4094 }
4095 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
4096 if (RD->isDefinition()) {
4097 for (RecordDecl::field_const_iterator i = RD->field_begin(),
4098 e = RD->field_end(); i != e; ++i) {
4099 FieldDecl *FD = *i;
4100 if (isBlockPointerType(FD->getType()))
4101 RewriteBlockPointerDecl(FD);
4102 }
4103 }
4104 return;
4105 }
4106 // Nothing yet.
4107}
4108
4109void RewriteObjC::HandleTranslationUnit(TranslationUnit& TU) {
4110 // Get the top-level buffer that this corresponds to.
4111
4112 // Rewrite tabs if we care.
4113 //RewriteTabs();
4114
4115 if (Diags.hasErrorOccurred())
4116 return;
4117
4118 // Create the output file.
4119
4120 llvm::OwningPtr<llvm::raw_ostream> OwnedStream;
4121 llvm::raw_ostream *OutFile;
4122 if (OutFileName == "-") {
4123 OutFile = &llvm::outs();
4124 } else if (!OutFileName.empty()) {
4125 std::string Err;
Daniel Dunbar26fb2722008-11-13 05:09:21 +00004126 OutFile = new llvm::raw_fd_ostream(OutFileName.c_str(), false, Err);
Steve Narofffa15fd92008-10-28 20:29:00 +00004127 OwnedStream.reset(OutFile);
4128 } else if (InFileName == "-") {
4129 OutFile = &llvm::outs();
4130 } else {
4131 llvm::sys::Path Path(InFileName);
4132 Path.eraseSuffix();
4133 Path.appendSuffix("cpp");
4134 std::string Err;
Daniel Dunbar26fb2722008-11-13 05:09:21 +00004135 OutFile = new llvm::raw_fd_ostream(Path.toString().c_str(), false, Err);
Steve Narofffa15fd92008-10-28 20:29:00 +00004136 OwnedStream.reset(OutFile);
4137 }
4138
4139 RewriteInclude();
4140
4141 InsertText(SourceLocation::getFileLoc(MainFileID, 0),
4142 Preamble.c_str(), Preamble.size(), false);
4143
Steve Naroff0aab7962008-11-14 14:10:01 +00004144 if (ClassImplementation.size() || CategoryImplementation.size())
4145 RewriteImplementations();
Steve Narofffa15fd92008-10-28 20:29:00 +00004146
4147 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
4148 // we are done.
4149 if (const RewriteBuffer *RewriteBuf =
4150 Rewrite.getRewriteBufferFor(MainFileID)) {
4151 //printf("Changed:\n");
4152 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4153 } else {
4154 fprintf(stderr, "No changes\n");
4155 }
Steve Narofface66252008-11-13 20:07:04 +00004156
Steve Naroff0aab7962008-11-14 14:10:01 +00004157 if (ClassImplementation.size() || CategoryImplementation.size()) {
4158 // Rewrite Objective-c meta data*
4159 std::string ResultStr;
4160 SynthesizeMetaDataIntoBuffer(ResultStr);
4161 // Emit metadata.
4162 *OutFile << ResultStr;
4163 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004164 OutFile->flush();
4165}
4166