blob: a3ce8a8c569d48080f8075ce6dc2b49b2be21835 [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>
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000508 if (strcmp(FVD->getIdentifierName(), "_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_";
608 typedefString += ForwardDecl->getName();
609 typedefString += "\n";
610 typedefString += "#define _REWRITER_typedef_";
611 typedefString += ForwardDecl->getName();
612 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000613 typedefString += "typedef struct objc_object ";
Steve Naroff934f2762007-10-24 22:48:43 +0000614 typedefString += ForwardDecl->getName();
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
742 NameStr += OMD->getClassInterface()->getName();
743 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)) {
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000748 NameStr += CID->getName();
749 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000750 }
Steve Naroff563b8282008-04-04 22:23:44 +0000751 // Append selector names, replacing ':' with '_'
752 if (OMD->getSelector().getName().find(':') == std::string::npos)
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000753 NameStr += OMD->getSelector().getName();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000754 else {
755 std::string selString = OMD->getSelector().getName();
756 int len = selString.size();
757 for (int i = 0; i < len; i++)
758 if (selString[i] == ':')
759 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000760 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000761 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000762 // Remember this name for metadata emission
763 MethodInternalNames[OMD] = NameStr;
764 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000765
766 // Rewrite arguments
767 ResultStr += "(";
768
769 // invisible arguments
770 if (OMD->isInstance()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000771 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000772 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +0000773 if (!LangOpts.Microsoft) {
774 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
775 ResultStr += "struct ";
776 }
777 // When rewriting for Microsoft, explicitly omit the structure name.
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000778 ResultStr += OMD->getClassInterface()->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000779 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000780 }
781 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000782 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000783
784 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000785 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000786 ResultStr += " _cmd";
787
788 // Method arguments.
Chris Lattner58cce3b2008-03-16 01:07:14 +0000789 for (unsigned i = 0; i < OMD->getNumParams(); i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000790 ParmVarDecl *PDecl = OMD->getParamDecl(i);
791 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +0000792 if (PDecl->getType()->isObjCQualifiedIdType()) {
793 ResultStr += "id ";
794 ResultStr += PDecl->getName();
795 } else {
796 std::string Name = PDecl->getName();
Steve Naroffc8ad87b2008-10-30 14:45:29 +0000797 if (isBlockPointerType(PDecl->getType())) {
798 // Make sure we convert "t (^)(...)" to "t (*)(...)".
799 const BlockPointerType *BPT = PDecl->getType()->getAsBlockPointerType();
800 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name);
801 } else
802 PDecl->getType().getAsStringInternal(Name);
Steve Naroff543409e2008-04-18 21:13:19 +0000803 ResultStr += Name;
804 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000805 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +0000806 if (OMD->isVariadic())
807 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000808 ResultStr += ") ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000809
Steve Naroff76e429d2008-07-16 14:40:40 +0000810 if (FPRetType) {
811 ResultStr += ")"; // close the precedence "scope" for "*".
812
813 // Now, emit the argument types (if any).
814 if (const FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(FPRetType)) {
815 ResultStr += "(";
816 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
817 if (i) ResultStr += ", ";
818 std::string ParamStr = FT->getArgType(i).getAsString();
819 ResultStr += ParamStr;
820 }
821 if (FT->isVariadic()) {
822 if (FT->getNumArgs()) ResultStr += ", ";
823 ResultStr += "...";
824 }
825 ResultStr += ")";
826 } else {
827 ResultStr += "()";
828 }
829 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000830}
Steve Naroffb29b4272008-04-14 22:03:09 +0000831void RewriteObjC::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000832 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
833 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000834
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000835 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000836 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000837 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000838 InsertText(CID->getLocStart(), "// ", 3);
Steve Narofface66252008-11-13 20:07:04 +0000839
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000840 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000841 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
842 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000843 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000844 ObjCMethodDecl *OMD = *I;
845 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000846 SourceLocation LocStart = OMD->getLocStart();
847 SourceLocation LocEnd = OMD->getBody()->getLocStart();
848
849 const char *startBuf = SM->getCharacterData(LocStart);
850 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000851 ReplaceText(LocStart, endBuf-startBuf,
852 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000853 }
854
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000855 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000856 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
857 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000858 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000859 ObjCMethodDecl *OMD = *I;
860 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000861 SourceLocation LocStart = OMD->getLocStart();
862 SourceLocation LocEnd = OMD->getBody()->getLocStart();
863
864 const char *startBuf = SM->getCharacterData(LocStart);
865 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000866 ReplaceText(LocStart, endBuf-startBuf,
867 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000868 }
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000869 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000870 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000871 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000872 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000873}
874
Steve Naroffb29b4272008-04-14 22:03:09 +0000875void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000876 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000877 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000878 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +0000879 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff32174822007-11-09 12:50:28 +0000880 ResultStr += ClassDecl->getName();
881 ResultStr += "\n";
882 ResultStr += "#define _REWRITER_typedef_";
883 ResultStr += ClassDecl->getName();
884 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000885 ResultStr += "typedef struct objc_object ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000886 ResultStr += ClassDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000887 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000888 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000889 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000890 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000891 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Narofff908a872007-10-30 02:23:23 +0000892
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000893 RewriteProperties(ClassDecl->getNumPropertyDecl(),
894 ClassDecl->getPropertyDecl());
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000895 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000896 E = ClassDecl->instmeth_end(); I != E; ++I)
897 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000898 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000899 E = ClassDecl->classmeth_end(); I != E; ++I)
900 RewriteMethodDeclaration(*I);
901
Steve Naroff2feac5e2007-10-30 03:43:13 +0000902 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000903 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000904}
905
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000906Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
907 SourceLocation OrigStart) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000908 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff54055232008-10-27 17:20:55 +0000909 if (CurMethodDef) {
Steve Naroff05b8c782008-03-12 00:25:36 +0000910 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +0000911 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
912 // lookup which class implements the instance variable.
913 ObjCInterfaceDecl *clsDeclared = 0;
914 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
915 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
916
917 // Synthesize an explicit cast to gain access to the ivar.
918 std::string RecName = clsDeclared->getIdentifier()->getName();
919 RecName += "_IMPL";
920 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000921 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +0000922 SourceLocation(), II);
Steve Narofff0757612008-05-08 17:52:16 +0000923 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
924 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Douglas Gregor6eec8e82008-10-28 15:36:24 +0000925 CastExpr *castExpr = new CStyleCastExpr(castT, IV->getBase(), castT,
Steve Naroffb2f9e512008-11-03 23:29:32 +0000926 SourceLocation(), SourceLocation());
Steve Narofff0757612008-05-08 17:52:16 +0000927 // Don't forget the parens to enforce the proper binding.
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000928 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
929 IV->getBase()->getLocEnd(),
930 castExpr);
Steve Narofff0757612008-05-08 17:52:16 +0000931 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +0000932 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000933 MemberExpr *ME = new MemberExpr(PE, true, D, IV->getLocation(),
934 D->getType());
Steve Narofff0757612008-05-08 17:52:16 +0000935 ReplaceStmt(IV, ME);
936 delete IV;
937 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000938 }
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000939
940 ReplaceStmt(IV->getBase(), PE);
941 // Cannot delete IV->getBase(), since PE points to it.
942 // Replace the old base with the cast. This is important when doing
943 // embedded rewrites. For example, [newInv->_container addObject:0].
944 IV->setBase(PE);
945 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000946 }
Steve Naroff84472a82008-04-18 21:55:08 +0000947 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +0000948 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
949
950 // Explicit ivar refs need to have a cast inserted.
951 // FIXME: consider sharing some of this code with the code above.
952 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +0000953 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +0000954 // lookup which class implements the instance variable.
955 ObjCInterfaceDecl *clsDeclared = 0;
Steve Narofff0757612008-05-08 17:52:16 +0000956 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +0000957 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
958
959 // Synthesize an explicit cast to gain access to the ivar.
960 std::string RecName = clsDeclared->getIdentifier()->getName();
961 RecName += "_IMPL";
962 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000963 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +0000964 SourceLocation(), II);
Steve Naroff9f525972008-05-06 23:20:07 +0000965 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
966 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Douglas Gregor6eec8e82008-10-28 15:36:24 +0000967 CastExpr *castExpr = new CStyleCastExpr(castT, IV->getBase(), castT,
Steve Naroffb2f9e512008-11-03 23:29:32 +0000968 SourceLocation(), SourceLocation());
Steve Naroff9f525972008-05-06 23:20:07 +0000969 // Don't forget the parens to enforce the proper binding.
Chris Lattner8d366162008-05-28 16:38:23 +0000970 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
971 IV->getBase()->getLocEnd(), castExpr);
Steve Naroff9f525972008-05-06 23:20:07 +0000972 ReplaceStmt(IV->getBase(), PE);
973 // Cannot delete IV->getBase(), since PE points to it.
974 // Replace the old base with the cast. This is important when doing
975 // embedded rewrites. For example, [newInv->_container addObject:0].
976 IV->setBase(PE);
977 return IV;
978 }
Steve Naroffc2a689b2007-11-15 11:33:00 +0000979 }
Steve Naroff84472a82008-04-18 21:55:08 +0000980 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +0000981}
982
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000983/// SynthCountByEnumWithState - To print:
984/// ((unsigned int (*)
985/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
986/// (void *)objc_msgSend)((id)l_collection,
987/// sel_registerName(
988/// "countByEnumeratingWithState:objects:count:"),
989/// &enumState,
990/// (id *)items, (unsigned int)16)
991///
Steve Naroffb29b4272008-04-14 22:03:09 +0000992void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000993 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
994 "id *, unsigned int))(void *)objc_msgSend)";
995 buf += "\n\t\t";
996 buf += "((id)l_collection,\n\t\t";
997 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
998 buf += "\n\t\t";
999 buf += "&enumState, "
1000 "(id *)items, (unsigned int)16)";
1001}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001002
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001003/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1004/// statement to exit to its outer synthesized loop.
1005///
Steve Naroffb29b4272008-04-14 22:03:09 +00001006Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001007 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1008 return S;
1009 // replace break with goto __break_label
1010 std::string buf;
1011
1012 SourceLocation startLoc = S->getLocStart();
1013 buf = "goto __break_label_";
1014 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001015 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001016
1017 return 0;
1018}
1019
1020/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1021/// statement to continue with its inner synthesized loop.
1022///
Steve Naroffb29b4272008-04-14 22:03:09 +00001023Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001024 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1025 return S;
1026 // replace continue with goto __continue_label
1027 std::string buf;
1028
1029 SourceLocation startLoc = S->getLocStart();
1030 buf = "goto __continue_label_";
1031 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001032 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001033
1034 return 0;
1035}
1036
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001037/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001038/// It rewrites:
1039/// for ( type elem in collection) { stmts; }
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001040
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001041/// Into:
1042/// {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001043/// type elem;
1044/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001045/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001046/// id l_collection = (id)collection;
1047/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1048/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001049/// if (limit) {
1050/// unsigned long startMutations = *enumState.mutationsPtr;
1051/// do {
1052/// unsigned long counter = 0;
1053/// do {
1054/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001055/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001056/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001057/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001058/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001059/// } while (counter < limit);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001060/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1061/// objects:items count:16]);
1062/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001063/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001064/// }
1065/// else
1066/// elem = nil;
1067/// }
1068///
Steve Naroffb29b4272008-04-14 22:03:09 +00001069Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001070 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001071 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1072 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1073 "ObjCForCollectionStmt Statement stack mismatch");
1074 assert(!ObjCBcLabelNo.empty() &&
1075 "ObjCForCollectionStmt - Label No stack empty");
1076
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001077 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001078 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001079 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001080 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001081 std::string buf;
1082 buf = "\n{\n\t";
1083 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1084 // type elem;
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001085 ScopedDecl* D = DS->getSolitaryDecl();
1086 QualType ElementType = cast<ValueDecl>(D)->getType();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001087 elementTypeAsString = ElementType.getAsString();
1088 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001089 buf += " ";
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001090 elementName = D->getIdentifierName();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001091 buf += elementName;
1092 buf += ";\n\t";
1093 }
Chris Lattner06767512008-04-08 05:52:18 +00001094 else {
1095 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001096 elementName = DR->getDecl()->getIdentifierName();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001097 elementTypeAsString
1098 = cast<ValueDecl>(DR->getDecl())->getType().getAsString();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001099 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001100
1101 // struct __objcFastEnumerationState enumState = { 0 };
1102 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1103 // id items[16];
1104 buf += "id items[16];\n\t";
1105 // id l_collection = (id)
1106 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001107 // Find start location of 'collection' the hard way!
1108 const char *startCollectionBuf = startBuf;
1109 startCollectionBuf += 3; // skip 'for'
1110 startCollectionBuf = strchr(startCollectionBuf, '(');
1111 startCollectionBuf++; // skip '('
1112 // find 'in' and skip it.
1113 while (*startCollectionBuf != ' ' ||
1114 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1115 (*(startCollectionBuf+3) != ' ' &&
1116 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1117 startCollectionBuf++;
1118 startCollectionBuf += 3;
1119
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001120 // Replace: "for (type element in" with string constructed thus far.
Chris Lattneraadaf782008-01-31 19:51:04 +00001121 ReplaceText(startLoc, startCollectionBuf - startBuf,
1122 buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001123 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001124 SourceLocation rightParenLoc = S->getRParenLoc();
1125 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1126 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001127 buf = ";\n\t";
1128
1129 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1130 // objects:items count:16];
1131 // which is synthesized into:
1132 // unsigned int limit =
1133 // ((unsigned int (*)
1134 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1135 // (void *)objc_msgSend)((id)l_collection,
1136 // sel_registerName(
1137 // "countByEnumeratingWithState:objects:count:"),
1138 // (struct __objcFastEnumerationState *)&state,
1139 // (id *)items, (unsigned int)16);
1140 buf += "unsigned long limit =\n\t\t";
1141 SynthCountByEnumWithState(buf);
1142 buf += ";\n\t";
1143 /// if (limit) {
1144 /// unsigned long startMutations = *enumState.mutationsPtr;
1145 /// do {
1146 /// unsigned long counter = 0;
1147 /// do {
1148 /// if (startMutations != *enumState.mutationsPtr)
1149 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001150 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001151 buf += "if (limit) {\n\t";
1152 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1153 buf += "do {\n\t\t";
1154 buf += "unsigned long counter = 0;\n\t\t";
1155 buf += "do {\n\t\t\t";
1156 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1157 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1158 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001159 buf += " = (";
1160 buf += elementTypeAsString;
1161 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001162 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattneraadaf782008-01-31 19:51:04 +00001163 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001164
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001165 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001166 /// } while (counter < limit);
1167 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1168 /// objects:items count:16]);
1169 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001170 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001171 /// }
1172 /// else
1173 /// elem = nil;
1174 /// }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001175 ///
1176 buf = ";\n\t";
1177 buf += "__continue_label_";
1178 buf += utostr(ObjCBcLabelNo.back());
1179 buf += ": ;";
1180 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001181 buf += "} while (counter < limit);\n\t";
1182 buf += "} while (limit = ";
1183 SynthCountByEnumWithState(buf);
1184 buf += ");\n\t";
1185 buf += elementName;
1186 buf += " = nil;\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001187 buf += "__break_label_";
1188 buf += utostr(ObjCBcLabelNo.back());
1189 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001190 buf += "}\n\t";
1191 buf += "else\n\t\t";
1192 buf += elementName;
1193 buf += " = nil;\n";
1194 buf += "}\n";
Steve Naroff600e4e82008-07-21 18:26:02 +00001195
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001196 // Insert all these *after* the statement body.
Steve Naroff600e4e82008-07-21 18:26:02 +00001197 if (isa<CompoundStmt>(S->getBody())) {
1198 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1199 InsertText(endBodyLoc, buf.c_str(), buf.size());
1200 } else {
1201 /* Need to treat single statements specially. For example:
1202 *
1203 * for (A *a in b) if (stuff()) break;
1204 * for (A *a in b) xxxyy;
1205 *
1206 * The following code simply scans ahead to the semi to find the actual end.
1207 */
1208 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1209 const char *semiBuf = strchr(stmtBuf, ';');
1210 assert(semiBuf && "Can't find ';'");
1211 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1212 InsertText(endBodyLoc, buf.c_str(), buf.size());
1213 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001214 Stmts.pop_back();
1215 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001216 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001217}
1218
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001219/// RewriteObjCSynchronizedStmt -
1220/// This routine rewrites @synchronized(expr) stmt;
1221/// into:
1222/// objc_sync_enter(expr);
1223/// @try stmt @finally { objc_sync_exit(expr); }
1224///
Steve Naroffb29b4272008-04-14 22:03:09 +00001225Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001226 // Get the start location and compute the semi location.
1227 SourceLocation startLoc = S->getLocStart();
1228 const char *startBuf = SM->getCharacterData(startLoc);
1229
1230 assert((*startBuf == '@') && "bogus @synchronized location");
1231
1232 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001233 buf = "objc_sync_enter((id)";
1234 const char *lparenBuf = startBuf;
1235 while (*lparenBuf != '(') lparenBuf++;
1236 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Steve Naroffc7089f12008-08-19 13:04:19 +00001237 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1238 // the sync expression is typically a message expression that's already
1239 // been rewritten! (which implies the SourceLocation's are invalid).
1240 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001241 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001242 while (*endBuf != ')') endBuf--;
1243 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001244 buf = ");\n";
1245 // declare a new scope with two variables, _stack and _rethrow.
1246 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1247 buf += "int buf[18/*32-bit i386*/];\n";
1248 buf += "char *pointers[4];} _stack;\n";
1249 buf += "id volatile _rethrow = 0;\n";
1250 buf += "objc_exception_try_enter(&_stack);\n";
1251 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00001252 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001253 startLoc = S->getSynchBody()->getLocEnd();
1254 startBuf = SM->getCharacterData(startLoc);
1255
Steve Naroffc7089f12008-08-19 13:04:19 +00001256 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001257 SourceLocation lastCurlyLoc = startLoc;
1258 buf = "}\nelse {\n";
1259 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1260 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb2a39452008-07-16 19:47:39 +00001261 buf += " objc_sync_exit(";
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001262 Expr *syncExpr = new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00001263 S->getSynchExpr(),
1264 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00001265 SourceLocation(), SourceLocation());
Ted Kremeneka95d3752008-09-13 05:16:45 +00001266 std::string syncExprBufS;
1267 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Steve Naroff3498cc92008-08-21 13:03:03 +00001268 syncExpr->printPretty(syncExprBuf);
Steve Naroffb2a39452008-07-16 19:47:39 +00001269 buf += syncExprBuf.str();
1270 buf += ");\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001271 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1272 buf += "}\n";
1273 buf += "}";
1274
Chris Lattneraadaf782008-01-31 19:51:04 +00001275 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001276 return 0;
1277}
1278
Steve Naroffb29b4272008-04-14 22:03:09 +00001279Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001280 // Get the start location and compute the semi location.
1281 SourceLocation startLoc = S->getLocStart();
1282 const char *startBuf = SM->getCharacterData(startLoc);
1283
1284 assert((*startBuf == '@') && "bogus @try location");
1285
1286 std::string buf;
1287 // declare a new scope with two variables, _stack and _rethrow.
1288 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1289 buf += "int buf[18/*32-bit i386*/];\n";
1290 buf += "char *pointers[4];} _stack;\n";
1291 buf += "id volatile _rethrow = 0;\n";
1292 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001293 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001294
Chris Lattneraadaf782008-01-31 19:51:04 +00001295 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001296
1297 startLoc = S->getTryBody()->getLocEnd();
1298 startBuf = SM->getCharacterData(startLoc);
1299
1300 assert((*startBuf == '}') && "bogus @try block");
Steve Naroffc9ba1722008-07-16 15:31:30 +00001301
Steve Naroff75730982007-11-07 04:08:17 +00001302 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffc9ba1722008-07-16 15:31:30 +00001303 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1304 if (catchList) {
1305 startLoc = startLoc.getFileLocWithOffset(1);
1306 buf = " /* @catch begin */ else {\n";
1307 buf += " id _caught = objc_exception_extract(&_stack);\n";
1308 buf += " objc_exception_try_enter (&_stack);\n";
1309 buf += " if (_setjmp(_stack.buf))\n";
1310 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1311 buf += " else { /* @catch continue */";
1312
1313 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001314 } else { /* no catch list */
1315 buf = "}\nelse {\n";
1316 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1317 buf += "}";
1318 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffc9ba1722008-07-16 15:31:30 +00001319 }
Steve Naroff75730982007-11-07 04:08:17 +00001320 bool sawIdTypedCatch = false;
1321 Stmt *lastCatchBody = 0;
Steve Naroff75730982007-11-07 04:08:17 +00001322 while (catchList) {
1323 Stmt *catchStmt = catchList->getCatchParamStmt();
1324
1325 if (catchList == S->getCatchStmts())
1326 buf = "if ("; // we are generating code for the first catch clause
1327 else
1328 buf = "else if (";
1329 startLoc = catchList->getLocStart();
1330 startBuf = SM->getCharacterData(startLoc);
1331
1332 assert((*startBuf == '@') && "bogus @catch location");
1333
1334 const char *lParenLoc = strchr(startBuf, '(');
1335
Steve Naroffbe4b3332008-02-01 22:08:12 +00001336 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001337 // Now rewrite the body...
1338 lastCatchBody = catchList->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001339 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1340 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner06767512008-04-08 05:52:18 +00001341 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1342 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001343 assert((*bodyBuf == '{') && "bogus @catch body location");
1344
1345 buf += "1) { id _tmp = _caught;";
1346 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1347 buf.c_str(), buf.size());
1348 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Ted Kremenek50a25e22008-10-06 22:39:38 +00001349 QualType t = dyn_cast<ValueDecl>(declStmt->getSolitaryDecl())->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001350 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001351 buf += "1) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001352 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001353 sawIdTypedCatch = true;
1354 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001355 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroff75730982007-11-07 04:08:17 +00001356
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001357 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001358 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001359 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroff75730982007-11-07 04:08:17 +00001360 buf += cls->getDecl()->getName();
Steve Naroff21867b12007-11-07 18:43:40 +00001361 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001362 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001363 }
1364 }
1365 // Now rewrite the body...
1366 lastCatchBody = catchList->getCatchBody();
1367 SourceLocation rParenLoc = catchList->getRParenLoc();
1368 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1369 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1370 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1371 assert((*rParenBuf == ')') && "bogus @catch paren location");
1372 assert((*bodyBuf == '{') && "bogus @catch body location");
1373
1374 buf = " = _caught;";
1375 // Here we replace ") {" with "= _caught;" (which initializes and
1376 // declares the @catch parameter).
Chris Lattneraadaf782008-01-31 19:51:04 +00001377 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001378 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001379 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001380 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001381 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001382 catchList = catchList->getNextCatchStmt();
1383 }
1384 // Complete the catch list...
1385 if (lastCatchBody) {
1386 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001387 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1388 "bogus @catch body location");
Steve Naroff75730982007-11-07 04:08:17 +00001389
Steve Naroff378f47a2008-09-11 15:29:03 +00001390 // Insert the last (implicit) else clause *before* the right curly brace.
1391 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1392 buf = "} /* last catch end */\n";
1393 buf += "else {\n";
1394 buf += " _rethrow = _caught;\n";
1395 buf += " objc_exception_try_exit(&_stack);\n";
1396 buf += "} } /* @catch end */\n";
1397 if (!S->getFinallyStmt())
1398 buf += "}\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001399 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001400
1401 // Set lastCurlyLoc
1402 lastCurlyLoc = lastCatchBody->getLocEnd();
1403 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001404 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001405 startLoc = finalStmt->getLocStart();
1406 startBuf = SM->getCharacterData(startLoc);
1407 assert((*startBuf == '@') && "bogus @finally start");
1408
1409 buf = "/* @finally */";
Chris Lattneraadaf782008-01-31 19:51:04 +00001410 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001411
1412 Stmt *body = finalStmt->getFinallyBody();
1413 SourceLocation startLoc = body->getLocStart();
1414 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001415 assert(*SM->getCharacterData(startLoc) == '{' &&
1416 "bogus @finally body location");
1417 assert(*SM->getCharacterData(endLoc) == '}' &&
1418 "bogus @finally body location");
Steve Naroff75730982007-11-07 04:08:17 +00001419
1420 startLoc = startLoc.getFileLocWithOffset(1);
1421 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001422 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001423 endLoc = endLoc.getFileLocWithOffset(-1);
1424 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001425 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001426
1427 // Set lastCurlyLoc
1428 lastCurlyLoc = body->getLocEnd();
Steve Naroff378f47a2008-09-11 15:29:03 +00001429 } else { /* no finally clause - make sure we synthesize an implicit one */
1430 buf = "{ /* implicit finally clause */\n";
1431 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1432 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1433 buf += "}";
1434 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001435 }
1436 // Now emit the final closing curly brace...
1437 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1438 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001439 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001440 return 0;
1441}
1442
Steve Naroffb29b4272008-04-14 22:03:09 +00001443Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001444 return 0;
1445}
1446
Steve Naroffb29b4272008-04-14 22:03:09 +00001447Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001448 return 0;
1449}
1450
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001451// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff2bd03922007-11-07 15:32:26 +00001452// the throw expression is typically a message expression that's already
1453// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001454Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001455 // Get the start location and compute the semi location.
1456 SourceLocation startLoc = S->getLocStart();
1457 const char *startBuf = SM->getCharacterData(startLoc);
1458
1459 assert((*startBuf == '@') && "bogus @throw location");
1460
1461 std::string buf;
1462 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001463 if (S->getThrowExpr())
1464 buf = "objc_exception_throw(";
1465 else // add an implicit argument
1466 buf = "objc_exception_throw(_caught";
Steve Naroff4ba0acb2008-07-25 15:41:30 +00001467
1468 // handle "@ throw" correctly.
1469 const char *wBuf = strchr(startBuf, 'w');
1470 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1471 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
1472
Steve Naroff2bd03922007-11-07 15:32:26 +00001473 const char *semiBuf = strchr(startBuf, ';');
1474 assert((*semiBuf == ';') && "@throw: can't find ';'");
1475 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1476 buf = ");";
Chris Lattneraadaf782008-01-31 19:51:04 +00001477 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001478 return 0;
1479}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001480
Steve Naroffb29b4272008-04-14 22:03:09 +00001481Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001482 // Create a new string expression.
1483 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001484 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001485 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001486 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1487 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +00001488 SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001489 ReplaceStmt(Exp, Replacement);
Chris Lattnere365c502007-11-30 22:25:36 +00001490
Chris Lattner07506182007-11-30 22:53:43 +00001491 // Replace this subexpr in the parent.
Chris Lattnere64b7772007-10-24 16:57:36 +00001492 delete Exp;
1493 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001494}
1495
Steve Naroffb29b4272008-04-14 22:03:09 +00001496Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroffb42f8412007-11-05 14:50:49 +00001497 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1498 // Create a call to sel_registerName("selName").
1499 llvm::SmallVector<Expr*, 8> SelExprs;
1500 QualType argType = Context->getPointerType(Context->CharTy);
1501 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1502 Exp->getSelector().getName().size(),
1503 false, argType, SourceLocation(),
1504 SourceLocation()));
1505 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1506 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001507 ReplaceStmt(Exp, SelExp);
Steve Naroffb42f8412007-11-05 14:50:49 +00001508 delete Exp;
1509 return SelExp;
1510}
1511
Steve Naroffb29b4272008-04-14 22:03:09 +00001512CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff934f2762007-10-24 22:48:43 +00001513 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001514 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001515 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +00001516
1517 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +00001518 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +00001519
1520 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001521 QualType pToFunc = Context->getPointerType(msgSendType);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001522 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE,
1523 /*isLvalue=*/false);
Steve Naroffebf2b562007-10-23 23:50:29 +00001524
1525 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +00001526
Steve Naroff934f2762007-10-24 22:48:43 +00001527 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1528}
1529
Steve Naroffd5255f52007-11-01 13:24:47 +00001530static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1531 const char *&startRef, const char *&endRef) {
1532 while (startBuf < endBuf) {
1533 if (*startBuf == '<')
1534 startRef = startBuf; // mark the start.
1535 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001536 if (startRef && *startRef == '<') {
1537 endRef = startBuf; // mark the end.
1538 return true;
1539 }
1540 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001541 }
1542 startBuf++;
1543 }
1544 return false;
1545}
1546
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001547static void scanToNextArgument(const char *&argRef) {
1548 int angle = 0;
1549 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1550 if (*argRef == '<')
1551 angle++;
1552 else if (*argRef == '>')
1553 angle--;
1554 argRef++;
1555 }
1556 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1557}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001558
Steve Naroffb29b4272008-04-14 22:03:09 +00001559bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001560
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001561 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001562 return true;
1563
Steve Naroffd5255f52007-11-01 13:24:47 +00001564 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +00001565 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001566 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff9165ad32007-10-31 04:38:33 +00001567 return true; // we have "Class <Protocol> *".
1568 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001569 return false;
1570}
1571
Steve Naroff4f95b752008-07-29 18:15:38 +00001572void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1573 QualType Type = E->getType();
1574 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00001575 SourceLocation Loc, EndLoc;
1576
1577 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
1578 Loc = ECE->getLParenLoc();
1579 EndLoc = ECE->getRParenLoc();
1580 } else {
1581 Loc = E->getLocStart();
1582 EndLoc = E->getLocEnd();
1583 }
1584 // This will defend against trying to rewrite synthesized expressions.
1585 if (Loc.isInvalid() || EndLoc.isInvalid())
1586 return;
1587
Steve Naroff4f95b752008-07-29 18:15:38 +00001588 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00001589 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00001590 const char *startRef = 0, *endRef = 0;
1591 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1592 // Get the locations of the startRef, endRef.
1593 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1594 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1595 // Comment out the protocol references.
1596 InsertText(LessLoc, "/*", 2);
1597 InsertText(GreaterLoc, "*/", 2);
1598 }
1599 }
1600}
1601
Steve Naroffb29b4272008-04-14 22:03:09 +00001602void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001603 SourceLocation Loc;
1604 QualType Type;
1605 const FunctionTypeProto *proto = 0;
1606 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1607 Loc = VD->getLocation();
1608 Type = VD->getType();
1609 }
1610 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1611 Loc = FD->getLocation();
1612 // Check for ObjC 'id' and class types that have been adorned with protocol
1613 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1614 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1615 assert(funcType && "missing function type");
1616 proto = dyn_cast<FunctionTypeProto>(funcType);
1617 if (!proto)
1618 return;
1619 Type = proto->getResultType();
1620 }
1621 else
1622 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001623
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001624 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001625 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001626
1627 const char *endBuf = SM->getCharacterData(Loc);
1628 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00001629 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001630 startBuf--; // scan backward (from the decl location) for return type.
1631 const char *startRef = 0, *endRef = 0;
1632 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1633 // Get the locations of the startRef, endRef.
1634 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1635 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1636 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001637 InsertText(LessLoc, "/*", 2);
1638 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001639 }
1640 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001641 if (!proto)
1642 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001643 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001644 const char *startBuf = SM->getCharacterData(Loc);
1645 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001646 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1647 if (needToScanForQualifiers(proto->getArgType(i))) {
1648 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001649
Steve Naroffd5255f52007-11-01 13:24:47 +00001650 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001651 // scan forward (from the decl location) for argument types.
1652 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001653 const char *startRef = 0, *endRef = 0;
1654 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1655 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001656 SourceLocation LessLoc =
1657 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1658 SourceLocation GreaterLoc =
1659 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001660 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001661 InsertText(LessLoc, "/*", 2);
1662 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001663 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001664 startBuf = ++endBuf;
1665 }
1666 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00001667 // If the function name is derived from a macro expansion, then the
1668 // argument buffer will not follow the name. Need to speak with Chris.
1669 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001670 startBuf++; // scan forward (from the decl location) for argument types.
1671 startBuf++;
1672 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001673 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001674}
1675
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001676// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00001677void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001678 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1679 llvm::SmallVector<QualType, 16> ArgTys;
1680 ArgTys.push_back(Context->getPointerType(
1681 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001682 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001683 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001684 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001685 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001686 SourceLocation(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001687 SelGetUidIdent, getFuncType,
1688 FunctionDecl::Extern, false, 0);
1689}
1690
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001691// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
Steve Naroffb29b4272008-04-14 22:03:09 +00001692void RewriteObjC::SynthGetProtocolFunctionDecl() {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001693 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1694 llvm::SmallVector<QualType, 16> ArgTys;
1695 ArgTys.push_back(Context->getPointerType(
1696 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001697 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001698 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001699 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001700 GetProtocolFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001701 SourceLocation(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001702 SelGetProtoIdent, getFuncType,
1703 FunctionDecl::Extern, false, 0);
1704}
1705
Steve Naroffb29b4272008-04-14 22:03:09 +00001706void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001707 // declared in <objc/objc.h>
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001708 if (strcmp(FD->getIdentifierName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001709 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001710 return;
1711 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001712 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001713}
1714
Steve Naroffc0a123c2008-03-11 17:37:02 +00001715// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00001716void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00001717 if (SuperContructorFunctionDecl)
1718 return;
1719 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_super");
1720 llvm::SmallVector<QualType, 16> ArgTys;
1721 QualType argT = Context->getObjCIdType();
1722 assert(!argT.isNull() && "Can't find 'id' type");
1723 ArgTys.push_back(argT);
1724 ArgTys.push_back(argT);
1725 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1726 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001727 false, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001728 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001729 SourceLocation(),
Steve Naroffc0a123c2008-03-11 17:37:02 +00001730 msgSendIdent, msgSendType,
1731 FunctionDecl::Extern, false, 0);
1732}
1733
Steve Naroff09b266e2007-10-30 23:14:51 +00001734// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001735void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00001736 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1737 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001738 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001739 assert(!argT.isNull() && "Can't find 'id' type");
1740 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001741 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001742 assert(!argT.isNull() && "Can't find 'SEL' type");
1743 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001744 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001745 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001746 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001747 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001748 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001749 msgSendIdent, msgSendType,
1750 FunctionDecl::Extern, false, 0);
1751}
1752
Steve Naroff874e2322007-11-15 10:28:18 +00001753// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001754void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00001755 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1756 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001757 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001758 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00001759 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00001760 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1761 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1762 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001763 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00001764 assert(!argT.isNull() && "Can't find 'SEL' type");
1765 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001766 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00001767 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001768 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001769 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001770 SourceLocation(),
Steve Naroff874e2322007-11-15 10:28:18 +00001771 msgSendIdent, msgSendType,
1772 FunctionDecl::Extern, false, 0);
1773}
1774
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001775// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001776void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001777 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1778 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001779 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001780 assert(!argT.isNull() && "Can't find 'id' type");
1781 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001782 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001783 assert(!argT.isNull() && "Can't find 'SEL' type");
1784 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001785 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001786 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001787 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001788 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001789 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001790 msgSendIdent, msgSendType,
1791 FunctionDecl::Extern, false, 0);
1792}
1793
1794// SynthMsgSendSuperStretFunctionDecl -
1795// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001796void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001797 IdentifierInfo *msgSendIdent =
1798 &Context->Idents.get("objc_msgSendSuper_stret");
1799 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001800 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001801 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00001802 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001803 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1804 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1805 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001806 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001807 assert(!argT.isNull() && "Can't find 'SEL' type");
1808 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001809 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001810 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001811 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001812 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnera98e58d2008-03-15 21:24:04 +00001813 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001814 msgSendIdent, msgSendType,
1815 FunctionDecl::Extern, false, 0);
1816}
1817
Steve Naroff1284db82008-05-08 22:02:18 +00001818// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001819void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001820 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1821 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001822 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001823 assert(!argT.isNull() && "Can't find 'id' type");
1824 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001825 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001826 assert(!argT.isNull() && "Can't find 'SEL' type");
1827 ArgTys.push_back(argT);
Steve Naroff1284db82008-05-08 22:02:18 +00001828 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001829 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001830 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001831 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001832 SourceLocation(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001833 msgSendIdent, msgSendType,
1834 FunctionDecl::Extern, false, 0);
1835}
1836
Steve Naroff09b266e2007-10-30 23:14:51 +00001837// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00001838void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00001839 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1840 llvm::SmallVector<QualType, 16> ArgTys;
1841 ArgTys.push_back(Context->getPointerType(
1842 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001843 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001844 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001845 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001846 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001847 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001848 getClassIdent, getClassType,
1849 FunctionDecl::Extern, false, 0);
1850}
1851
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001852// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00001853void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001854 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1855 llvm::SmallVector<QualType, 16> ArgTys;
1856 ArgTys.push_back(Context->getPointerType(
1857 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001858 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001859 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001860 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001861 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001862 SourceLocation(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001863 getClassIdent, getClassType,
1864 FunctionDecl::Extern, false, 0);
1865}
1866
Steve Naroffb29b4272008-04-14 22:03:09 +00001867Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001868 QualType strType = getConstantStringStructType();
1869
1870 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00001871
1872 std::string tmpName = InFileName;
1873 unsigned i;
1874 for (i=0; i < tmpName.length(); i++) {
1875 char c = tmpName.at(i);
1876 // replace any non alphanumeric characters with '_'.
1877 if (!isalpha(c) && (c < '0' || c > '9'))
1878 tmpName[i] = '_';
1879 }
1880 S += tmpName;
1881 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001882 S += utostr(NumObjCStringLiterals++);
1883
Steve Naroffba92b2e2008-03-27 22:29:16 +00001884 Preamble += "static __NSConstantStringImpl " + S;
1885 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
1886 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001887 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00001888 std::string prettyBufS;
1889 llvm::raw_string_ostream prettyBuf(prettyBufS);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001890 Exp->getString()->printPretty(prettyBuf);
Steve Naroffba92b2e2008-03-27 22:29:16 +00001891 Preamble += prettyBuf.str();
1892 Preamble += ",";
Steve Naroff3652c2d2008-03-15 01:36:04 +00001893 // The minus 2 removes the begin/end double quotes.
Steve Naroffba92b2e2008-03-27 22:29:16 +00001894 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001895
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001896 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Steve Naroff248a7532008-04-15 22:42:06 +00001897 &Context->Idents.get(S.c_str()), strType,
1898 VarDecl::Static, NULL);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001899 DeclRefExpr *DRE = new DeclRefExpr(NewVD, strType, SourceLocation());
1900 Expr *Unop = new UnaryOperator(DRE, UnaryOperator::AddrOf,
1901 Context->getPointerType(DRE->getType()),
1902 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00001903 // cast to NSConstantString *
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001904 CastExpr *cast = new CStyleCastExpr(Exp->getType(), Unop,
Steve Naroffb2f9e512008-11-03 23:29:32 +00001905 Exp->getType(), SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001906 ReplaceStmt(Exp, cast);
Steve Naroff96984642007-11-08 14:30:50 +00001907 delete Exp;
1908 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00001909}
1910
Steve Naroffb29b4272008-04-14 22:03:09 +00001911ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001912 // check if we are sending a message to 'super'
Steve Naroff54055232008-10-27 17:20:55 +00001913 if (!CurMethodDef || !CurMethodDef->isInstance()) return 0;
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001914
Douglas Gregorcd9b46e2008-11-04 14:56:14 +00001915 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
1916 const PointerType *PT = Super->getType()->getAsPointerType();
Chris Lattner0d17f6f2008-06-21 18:04:54 +00001917 assert(PT);
1918 ObjCInterfaceType *IT = cast<ObjCInterfaceType>(PT->getPointeeType());
1919 return IT->getDecl();
1920 }
1921 return 0;
Steve Naroff874e2322007-11-15 10:28:18 +00001922}
1923
1924// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00001925QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00001926 if (!SuperStructDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001927 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00001928 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00001929 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00001930 QualType FieldTypes[2];
1931
1932 // struct objc_object *receiver;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001933 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00001934 // struct objc_class *super;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001935 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff874e2322007-11-15 10:28:18 +00001936 // Create fields
1937 FieldDecl *FieldDecls[2];
1938
1939 for (unsigned i = 0; i < 2; ++i)
Chris Lattnerb048c982008-04-06 04:47:34 +00001940 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00001941 FieldTypes[i]);
Steve Naroff874e2322007-11-15 10:28:18 +00001942
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001943 SuperStructDecl->defineBody(*Context, FieldDecls, 4);
Steve Naroff874e2322007-11-15 10:28:18 +00001944 }
1945 return Context->getTagDeclType(SuperStructDecl);
1946}
1947
Steve Naroffb29b4272008-04-14 22:03:09 +00001948QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001949 if (!ConstantStringDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001950 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00001951 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00001952 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001953 QualType FieldTypes[4];
1954
1955 // struct objc_object *receiver;
1956 FieldTypes[0] = Context->getObjCIdType();
1957 // int flags;
1958 FieldTypes[1] = Context->IntTy;
1959 // char *str;
1960 FieldTypes[2] = Context->getPointerType(Context->CharTy);
1961 // long length;
1962 FieldTypes[3] = Context->LongTy;
1963 // Create fields
Steve Naroff9630ec52008-03-27 22:59:54 +00001964 FieldDecl *FieldDecls[4];
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001965
1966 for (unsigned i = 0; i < 4; ++i)
Chris Lattnerb048c982008-04-06 04:47:34 +00001967 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00001968 FieldTypes[i]);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001969
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001970 ConstantStringDecl->defineBody(*Context, FieldDecls, 4);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001971 }
1972 return Context->getTagDeclType(ConstantStringDecl);
1973}
1974
Steve Naroffb29b4272008-04-14 22:03:09 +00001975Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001976 if (!SelGetUidFunctionDecl)
1977 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001978 if (!MsgSendFunctionDecl)
1979 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00001980 if (!MsgSendSuperFunctionDecl)
1981 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001982 if (!MsgSendStretFunctionDecl)
1983 SynthMsgSendStretFunctionDecl();
1984 if (!MsgSendSuperStretFunctionDecl)
1985 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001986 if (!MsgSendFpretFunctionDecl)
1987 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001988 if (!GetClassFunctionDecl)
1989 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001990 if (!GetMetaClassFunctionDecl)
1991 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001992
Steve Naroff874e2322007-11-15 10:28:18 +00001993 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001994 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1995 // May need to use objc_msgSend_stret() as well.
1996 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001997 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001998 QualType resultType = mDecl->getResultType();
Chris Lattner8b51fd72008-07-26 22:36:27 +00001999 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002000 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002001 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002002 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002003 }
Steve Naroff874e2322007-11-15 10:28:18 +00002004
Steve Naroff934f2762007-10-24 22:48:43 +00002005 // Synthesize a call to objc_msgSend().
2006 llvm::SmallVector<Expr*, 8> MsgExprs;
2007 IdentifierInfo *clsName = Exp->getClassName();
2008
2009 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2010 if (clsName) { // class message.
Steve Narofffc93d522008-07-24 19:44:33 +00002011 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2012 // the 'super' idiom within a class method.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002013 if (!strcmp(clsName->getName(), "super")) {
2014 MsgSendFlavor = MsgSendSuperFunctionDecl;
2015 if (MsgSendStretFlavor)
2016 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2017 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2018
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002019 ObjCInterfaceDecl *SuperDecl =
Steve Naroff54055232008-10-27 17:20:55 +00002020 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002021
2022 llvm::SmallVector<Expr*, 4> InitExprs;
2023
2024 // set the receiver to self, the first argument to all methods.
Chris Lattner41110242008-06-17 18:05:57 +00002025 InitExprs.push_back(new DeclRefExpr(
Steve Naroff54055232008-10-27 17:20:55 +00002026 CurMethodDef->getSelfDecl(),
Chris Lattner41110242008-06-17 18:05:57 +00002027 Context->getObjCIdType(),
2028 SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002029 llvm::SmallVector<Expr*, 8> ClsExprs;
2030 QualType argType = Context->getPointerType(Context->CharTy);
2031 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2032 SuperDecl->getIdentifier()->getLength(),
2033 false, argType, SourceLocation(),
2034 SourceLocation()));
2035 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2036 &ClsExprs[0],
2037 ClsExprs.size());
2038 // To turn off a warning, type-cast to 'id'
Douglas Gregor49badde2008-10-27 19:41:14 +00002039 InitExprs.push_back( // set 'super class', using objc_getClass().
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002040 new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002041 Cls, Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002042 SourceLocation(), SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002043 // struct objc_super
2044 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00002045 Expr *SuperRep;
Steve Naroffc0a123c2008-03-11 17:37:02 +00002046
Steve Naroff23f41272008-03-11 18:14:26 +00002047 if (LangOpts.Microsoft) {
2048 SynthSuperContructorFunctionDecl();
2049 // Simulate a contructor call...
2050 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2051 superType, SourceLocation());
2052 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2053 superType, SourceLocation());
2054 } else {
2055 // (struct objc_super) { <exprs from above> }
2056 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2057 &InitExprs[0], InitExprs.size(),
Chris Lattner418f6c72008-10-26 23:43:26 +00002058 SourceLocation(), false);
2059 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE,
2060 false);
Steve Naroff23f41272008-03-11 18:14:26 +00002061 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002062 // struct objc_super *
2063 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2064 Context->getPointerType(SuperRep->getType()),
2065 SourceLocation());
2066 MsgExprs.push_back(Unop);
2067 } else {
2068 llvm::SmallVector<Expr*, 8> ClsExprs;
2069 QualType argType = Context->getPointerType(Context->CharTy);
2070 ClsExprs.push_back(new StringLiteral(clsName->getName(),
2071 clsName->getLength(),
2072 false, argType, SourceLocation(),
2073 SourceLocation()));
2074 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2075 &ClsExprs[0],
2076 ClsExprs.size());
2077 MsgExprs.push_back(Cls);
2078 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002079 } else { // instance message.
2080 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00002081
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002082 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00002083 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002084 if (MsgSendStretFlavor)
2085 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00002086 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2087
2088 llvm::SmallVector<Expr*, 4> InitExprs;
2089
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002090 InitExprs.push_back(
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002091 new CStyleCastExpr(Context->getObjCIdType(),
Steve Naroff54055232008-10-27 17:20:55 +00002092 new DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Narofff616ebb2008-07-16 22:35:27 +00002093 Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002094 SourceLocation()),
2095 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002096 SourceLocation(), SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00002097
2098 llvm::SmallVector<Expr*, 8> ClsExprs;
2099 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002100 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2101 SuperDecl->getIdentifier()->getLength(),
Steve Naroff874e2322007-11-15 10:28:18 +00002102 false, argType, SourceLocation(),
2103 SourceLocation()));
2104 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002105 &ClsExprs[0],
2106 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00002107 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002108 InitExprs.push_back(
Douglas Gregor49badde2008-10-27 19:41:14 +00002109 // set 'super class', using objc_getClass().
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002110 new CStyleCastExpr(Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002111 Cls, Context->getObjCIdType(), SourceLocation(), SourceLocation()));
Steve Naroff874e2322007-11-15 10:28:18 +00002112 // struct objc_super
2113 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00002114 Expr *SuperRep;
2115
2116 if (LangOpts.Microsoft) {
2117 SynthSuperContructorFunctionDecl();
2118 // Simulate a contructor call...
2119 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2120 superType, SourceLocation());
2121 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2122 superType, SourceLocation());
2123 } else {
2124 // (struct objc_super) { <exprs from above> }
2125 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2126 &InitExprs[0], InitExprs.size(),
Chris Lattner418f6c72008-10-26 23:43:26 +00002127 SourceLocation(), false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002128 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
2129 }
Steve Naroff874e2322007-11-15 10:28:18 +00002130 // struct objc_super *
2131 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2132 Context->getPointerType(SuperRep->getType()),
2133 SourceLocation());
2134 MsgExprs.push_back(Unop);
2135 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002136 // Remove all type-casts because it may contain objc-style types; e.g.
2137 // Foo<Proto> *.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002138 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002139 recExpr = CE->getSubExpr();
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002140 recExpr = new CStyleCastExpr(Context->getObjCIdType(), recExpr,
Douglas Gregor49badde2008-10-27 19:41:14 +00002141 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002142 SourceLocation(), SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00002143 MsgExprs.push_back(recExpr);
2144 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002145 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00002146 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002147 llvm::SmallVector<Expr*, 8> SelExprs;
2148 QualType argType = Context->getPointerType(Context->CharTy);
2149 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
2150 Exp->getSelector().getName().size(),
2151 false, argType, SourceLocation(),
2152 SourceLocation()));
2153 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2154 &SelExprs[0], SelExprs.size());
2155 MsgExprs.push_back(SelExp);
2156
2157 // Now push any user supplied arguments.
2158 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002159 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002160 // Make all implicit casts explicit...ICE comes in handy:-)
2161 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2162 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregor49badde2008-10-27 19:41:14 +00002163 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002164 ? Context->getObjCIdType()
Douglas Gregor49badde2008-10-27 19:41:14 +00002165 : ICE->getType();
Steve Naroffb2f9e512008-11-03 23:29:32 +00002166 userExpr = new CStyleCastExpr(type, userExpr, type, SourceLocation(), SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002167 }
2168 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002169 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002170 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002171 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002172 userExpr = CE->getSubExpr();
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002173 userExpr = new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002174 userExpr, Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002175 SourceLocation(), SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002176 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00002177 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002178 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00002179 // We've transferred the ownership to MsgExprs. Null out the argument in
2180 // the original expression, since we will delete it below.
2181 Exp->setArg(i, 0);
2182 }
Steve Naroffab972d32007-11-04 22:37:50 +00002183 // Generate the funky cast.
2184 CastExpr *cast;
2185 llvm::SmallVector<QualType, 8> ArgTypes;
2186 QualType returnType;
2187
2188 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002189 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2190 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2191 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002192 ArgTypes.push_back(Context->getObjCIdType());
2193 ArgTypes.push_back(Context->getObjCSelType());
2194 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002195 // Push any user argument types.
Chris Lattner58cce3b2008-03-16 01:07:14 +00002196 for (unsigned i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002197 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
2198 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002199 : mDecl->getParamDecl(i)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00002200 // Make sure we convert "t (^)(...)" to "t (*)(...)".
2201 if (isBlockPointerType(t)) {
2202 const BlockPointerType *BPT = t->getAsBlockPointerType();
2203 t = Context->getPointerType(BPT->getPointeeType());
2204 }
Steve Naroff352336b2007-11-05 14:36:37 +00002205 ArgTypes.push_back(t);
2206 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002207 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
2208 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00002209 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002210 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002211 }
2212 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002213 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00002214
2215 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002216 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
2217 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002218
2219 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2220 // If we don't do this cast, we get the following bizarre warning/note:
2221 // xx.m:13: warning: function called through a non-compatible type
2222 // xx.m:13: note: if this code is reached, the program will abort
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002223 cast = new CStyleCastExpr(Context->getPointerType(Context->VoidTy), DRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002224 Context->getPointerType(Context->VoidTy),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002225 SourceLocation(), SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00002226
Steve Naroffab972d32007-11-04 22:37:50 +00002227 // Now do the "normal" pointer to function cast.
2228 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002229 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00002230 // If we don't have a method decl, force a variadic cast.
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002231 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Naroffab972d32007-11-04 22:37:50 +00002232 castType = Context->getPointerType(castType);
Steve Naroffb2f9e512008-11-03 23:29:32 +00002233 cast = new CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002234
2235 // Don't forget the parens to enforce the proper binding.
2236 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2237
2238 const FunctionType *FT = msgSendType->getAsFunctionType();
2239 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2240 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002241 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002242 if (MsgSendStretFlavor) {
2243 // We have the method which returns a struct/union. Must also generate
2244 // call to objc_msgSend_stret and hang both varieties on a conditional
2245 // expression which dictate which one to envoke depending on size of
2246 // method's return type.
2247
2248 // Create a reference to the objc_msgSend_stret() declaration.
2249 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
2250 SourceLocation());
2251 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002252 cast = new CStyleCastExpr(Context->getPointerType(Context->VoidTy), STDRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002253 Context->getPointerType(Context->VoidTy),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002254 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002255 // Now do the "normal" pointer to function cast.
2256 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002257 &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002258 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002259 castType = Context->getPointerType(castType);
Steve Naroffb2f9e512008-11-03 23:29:32 +00002260 cast = new CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002261
2262 // Don't forget the parens to enforce the proper binding.
2263 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2264
2265 FT = msgSendType->getAsFunctionType();
2266 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2267 FT->getResultType(), SourceLocation());
2268
2269 // Build sizeof(returnType)
Sebastian Redl05189992008-11-11 17:56:53 +00002270 SizeOfAlignOfExpr *sizeofExpr = new SizeOfAlignOfExpr(true, true,
2271 returnType.getAsOpaquePtr(),
2272 Context->getSizeType(),
2273 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002274 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2275 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2276 // For X86 it is more complicated and some kind of target specific routine
2277 // is needed to decide what to do.
Chris Lattner98be4942008-03-05 18:54:05 +00002278 unsigned IntSize =
2279 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002280 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2281 Context->IntTy,
2282 SourceLocation());
2283 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2284 BinaryOperator::LE,
2285 Context->IntTy,
2286 SourceLocation());
2287 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2288 ConditionalOperator *CondExpr =
2289 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002290 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002291 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002292 return ReplacingStmt;
2293}
2294
Steve Naroffb29b4272008-04-14 22:03:09 +00002295Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002296 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff80c28552008-10-27 20:54:44 +00002297
Steve Naroff934f2762007-10-24 22:48:43 +00002298 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002299 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff934f2762007-10-24 22:48:43 +00002300
Chris Lattnere64b7772007-10-24 16:57:36 +00002301 delete Exp;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002302 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002303}
2304
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002305/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2306/// call to objc_getProtocol("proto-name").
Steve Naroffb29b4272008-04-14 22:03:09 +00002307Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002308 if (!GetProtocolFunctionDecl)
2309 SynthGetProtocolFunctionDecl();
2310 // Create a call to objc_getProtocol("ProtocolName").
2311 llvm::SmallVector<Expr*, 8> ProtoExprs;
2312 QualType argType = Context->getPointerType(Context->CharTy);
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002313 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getIdentifierName(),
2314 strlen(Exp->getProtocol()->getIdentifierName()),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002315 false, argType, SourceLocation(),
2316 SourceLocation()));
2317 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2318 &ProtoExprs[0],
2319 ProtoExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002320 ReplaceStmt(Exp, ProtoExp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002321 delete Exp;
2322 return ProtoExp;
2323
2324}
2325
Steve Naroffbaf58c32008-05-31 14:15:04 +00002326bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
2327 const char *endBuf) {
2328 while (startBuf < endBuf) {
2329 if (*startBuf == '#') {
2330 // Skip whitespace.
2331 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2332 ;
2333 if (!strncmp(startBuf, "if", strlen("if")) ||
2334 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2335 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2336 !strncmp(startBuf, "define", strlen("define")) ||
2337 !strncmp(startBuf, "undef", strlen("undef")) ||
2338 !strncmp(startBuf, "else", strlen("else")) ||
2339 !strncmp(startBuf, "elif", strlen("elif")) ||
2340 !strncmp(startBuf, "endif", strlen("endif")) ||
2341 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2342 !strncmp(startBuf, "include", strlen("include")) ||
2343 !strncmp(startBuf, "import", strlen("import")) ||
2344 !strncmp(startBuf, "include_next", strlen("include_next")))
2345 return true;
2346 }
2347 startBuf++;
2348 }
2349 return false;
2350}
2351
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002352/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002353/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00002354void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002355 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002356 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002357 assert(CDecl->getIdentifierName() &&
2358 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002359 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002360 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002361 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002362 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002363 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00002364 SourceLocation LocStart = CDecl->getLocStart();
2365 SourceLocation LocEnd = CDecl->getLocEnd();
2366
2367 const char *startBuf = SM->getCharacterData(LocStart);
2368 const char *endBuf = SM->getCharacterData(LocEnd);
Steve Naroffbaf58c32008-05-31 14:15:04 +00002369
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002370 // If no ivars and no root or if its root, directly or indirectly,
2371 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002372 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2373 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002374 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattneraadaf782008-01-31 19:51:04 +00002375 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002376 return;
2377 }
2378
2379 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002380 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002381 Result += "\nstruct ";
2382 Result += CDecl->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002383 if (LangOpts.Microsoft)
2384 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00002385
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002386 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002387 const char *cursor = strchr(startBuf, '{');
2388 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002389 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00002390 // If the buffer contains preprocessor directives, we do more fine-grained
2391 // rewrites. This is intended to fix code that looks like (which occurs in
2392 // NSURL.h, for example):
2393 //
2394 // #ifdef XYZ
2395 // @interface Foo : NSObject
2396 // #else
2397 // @interface FooBar : NSObject
2398 // #endif
2399 // {
2400 // int i;
2401 // }
2402 // @end
2403 //
2404 // This clause is segregated to avoid breaking the common case.
2405 if (BufferContainsPPDirectives(startBuf, cursor)) {
2406 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
2407 CDecl->getClassLoc();
2408 const char *endHeader = SM->getCharacterData(L);
2409 endHeader += Lexer::MeasureTokenLength(L, *SM);
2410
Chris Lattner3db6cae2008-07-21 18:19:38 +00002411 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00002412 // advance to the end of the referenced protocols.
2413 while (endHeader < cursor && *endHeader != '>') endHeader++;
2414 endHeader++;
2415 }
2416 // rewrite the original header
2417 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2418 } else {
2419 // rewrite the original header *without* disturbing the '{'
2420 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
2421 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002422 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002423 Result = "\n struct ";
2424 Result += RCDecl->getName();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002425 Result += "_IMPL ";
2426 Result += RCDecl->getName();
Steve Naroff819173c2008-03-12 21:22:52 +00002427 Result += "_IVARS;\n";
Steve Narofffea763e82007-11-14 19:25:57 +00002428
2429 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002430 SourceLocation OnePastCurly =
2431 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2432 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002433 }
2434 cursor++; // past '{'
2435
2436 // Now comment out any visibility specifiers.
2437 while (cursor < endBuf) {
2438 if (*cursor == '@') {
2439 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002440 // Skip whitespace.
2441 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2442 /*scan*/;
2443
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002444 // FIXME: presence of @public, etc. inside comment results in
2445 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002446 if (!strncmp(cursor, "public", strlen("public")) ||
2447 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00002448 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002449 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002450 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002451 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002452 // FIXME: If there are cases where '<' is used in ivar declaration part
2453 // of user code, then scan the ivar list and use needToScanForQualifiers
2454 // for type checking.
2455 else if (*cursor == '<') {
2456 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002457 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002458 cursor = strchr(cursor, '>');
2459 cursor++;
2460 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002461 InsertText(atLoc, " */", 3);
Steve Naroffced80a82008-10-30 12:09:33 +00002462 } else if (*cursor == '^') { // rewrite block specifier.
2463 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2464 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002465 }
Steve Narofffea763e82007-11-14 19:25:57 +00002466 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002467 }
Steve Narofffea763e82007-11-14 19:25:57 +00002468 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002469 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00002470 } else { // we don't have any instance variables - insert super struct.
2471 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2472 Result += " {\n struct ";
2473 Result += RCDecl->getName();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002474 Result += "_IMPL ";
2475 Result += RCDecl->getName();
Steve Naroff819173c2008-03-12 21:22:52 +00002476 Result += "_IVARS;\n};\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00002477 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002478 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002479 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002480 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00002481 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002482}
2483
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002484// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002485/// class methods.
Steve Naroffb29b4272008-04-14 22:03:09 +00002486void RewriteObjC::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002487 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002488 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002489 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002490 const char *ClassName,
2491 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002492 if (MethodBegin == MethodEnd) return;
2493
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002494 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002495 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002496 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002497 SEL _cmd;
2498 char *method_types;
2499 void *_imp;
2500 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002501 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002502 Result += "\nstruct _objc_method {\n";
2503 Result += "\tSEL _cmd;\n";
2504 Result += "\tchar *method_types;\n";
2505 Result += "\tvoid *_imp;\n";
2506 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002507
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002508 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002509 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002510
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002511 // Build _objc_method_list for class's methods if needed
Steve Naroff946a6932008-03-11 00:12:29 +00002512
2513 /* struct {
2514 struct _objc_method_list *next_method;
2515 int method_count;
2516 struct _objc_method method_list[];
2517 }
2518 */
2519 Result += "\nstatic struct {\n";
2520 Result += "\tstruct _objc_method_list *next_method;\n";
2521 Result += "\tint method_count;\n";
2522 Result += "\tstruct _objc_method method_list[";
2523 Result += utostr(MethodEnd-MethodBegin);
2524 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002525 Result += prefix;
2526 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2527 Result += "_METHODS_";
2528 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002529 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002530 Result += IsInstanceMethod ? "inst" : "cls";
2531 Result += "_meth\")))= ";
2532 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002533
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002534 Result += "\t,{{(SEL)\"";
2535 Result += (*MethodBegin)->getSelector().getName().c_str();
2536 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002537 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002538 Result += "\", \"";
2539 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002540 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002541 Result += MethodInternalNames[*MethodBegin];
2542 Result += "}\n";
2543 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2544 Result += "\t ,{(SEL)\"";
2545 Result += (*MethodBegin)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002546 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002547 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002548 Result += "\", \"";
2549 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002550 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002551 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002552 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002553 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002554 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002555}
2556
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002557/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00002558void RewriteObjC::
2559RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
2560 const char *prefix,
2561 const char *ClassName,
2562 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002563 static bool objc_protocol_methods = false;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002564 if (Protocols.empty()) return;
2565
2566 for (unsigned i = 0; i != Protocols.size(); i++) {
2567 ObjCProtocolDecl *PDecl = Protocols[i];
2568 // Output struct protocol_methods holder of method selector and type.
2569 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
2570 /* struct protocol_methods {
2571 SEL _cmd;
2572 char *method_types;
2573 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002574 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002575 Result += "\nstruct protocol_methods {\n";
2576 Result += "\tSEL _cmd;\n";
2577 Result += "\tchar *method_types;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002578 Result += "};\n";
Steve Narofffbfe8252008-05-06 18:26:51 +00002579
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002580 objc_protocol_methods = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002581 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002582 // Do not synthesize the protocol more than once.
2583 if (ObjCSynthesizedProtocols.count(PDecl))
2584 continue;
2585
2586 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2587 unsigned NumMethods = PDecl->getNumInstanceMethods();
2588 /* struct _objc_protocol_method_list {
2589 int protocol_method_count;
2590 struct protocol_methods protocols[];
2591 }
2592 */
2593 Result += "\nstatic struct {\n";
2594 Result += "\tint protocol_method_count;\n";
2595 Result += "\tstruct protocol_methods protocols[";
2596 Result += utostr(NumMethods);
2597 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
2598 Result += PDecl->getName();
2599 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
2600 "{\n\t" + utostr(NumMethods) + "\n";
2601
2602 // Output instance methods declared in this protocol.
2603 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
2604 E = PDecl->instmeth_end(); I != E; ++I) {
2605 if (I == PDecl->instmeth_begin())
2606 Result += "\t ,{{(SEL)\"";
2607 else
2608 Result += "\t ,{(SEL)\"";
2609 Result += (*I)->getSelector().getName().c_str();
2610 std::string MethodTypeString;
2611 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2612 Result += "\", \"";
2613 Result += MethodTypeString;
2614 Result += "\"}\n";
2615 }
2616 Result += "\t }\n};\n";
2617 }
2618
2619 // Output class methods declared in this protocol.
2620 int NumMethods = PDecl->getNumClassMethods();
2621 if (NumMethods > 0) {
2622 /* struct _objc_protocol_method_list {
2623 int protocol_method_count;
2624 struct protocol_methods protocols[];
2625 }
2626 */
2627 Result += "\nstatic struct {\n";
2628 Result += "\tint protocol_method_count;\n";
2629 Result += "\tstruct protocol_methods protocols[";
2630 Result += utostr(NumMethods);
2631 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
2632 Result += PDecl->getName();
2633 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2634 "{\n\t";
2635 Result += utostr(NumMethods);
2636 Result += "\n";
2637
2638 // Output instance methods declared in this protocol.
2639 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
2640 E = PDecl->classmeth_end(); I != E; ++I) {
2641 if (I == PDecl->classmeth_begin())
2642 Result += "\t ,{{(SEL)\"";
2643 else
2644 Result += "\t ,{(SEL)\"";
2645 Result += (*I)->getSelector().getName().c_str();
2646 std::string MethodTypeString;
2647 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2648 Result += "\", \"";
2649 Result += MethodTypeString;
2650 Result += "\"}\n";
2651 }
2652 Result += "\t }\n};\n";
2653 }
2654
2655 // Output:
2656 /* struct _objc_protocol {
2657 // Objective-C 1.0 extensions
2658 struct _objc_protocol_extension *isa;
2659 char *protocol_name;
2660 struct _objc_protocol **protocol_list;
2661 struct _objc_protocol_method_list *instance_methods;
2662 struct _objc_protocol_method_list *class_methods;
2663 };
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002664 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002665 static bool objc_protocol = false;
2666 if (!objc_protocol) {
2667 Result += "\nstruct _objc_protocol {\n";
2668 Result += "\tstruct _objc_protocol_extension *isa;\n";
2669 Result += "\tchar *protocol_name;\n";
2670 Result += "\tstruct _objc_protocol **protocol_list;\n";
2671 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2672 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2673 Result += "};\n";
2674
2675 objc_protocol = true;
2676 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002677
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002678 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2679 Result += PDecl->getName();
2680 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
2681 "{\n\t0, \"";
2682 Result += PDecl->getName();
2683 Result += "\", 0, ";
2684 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2685 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
2686 Result += PDecl->getName();
2687 Result += ", ";
2688 }
2689 else
2690 Result += "0, ";
2691 if (PDecl->getNumClassMethods() > 0) {
2692 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
2693 Result += PDecl->getName();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002694 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002695 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002696 else
2697 Result += "0\n";
2698 Result += "};\n";
2699
2700 // Mark this protocol as having been generated.
2701 if (!ObjCSynthesizedProtocols.insert(PDecl))
2702 assert(false && "protocol already synthesized");
2703 }
2704 // Output the top lovel protocol meta-data for the class.
2705 /* struct _objc_protocol_list {
2706 struct _objc_protocol_list *next;
2707 int protocol_count;
2708 struct _objc_protocol *class_protocols[];
2709 }
2710 */
2711 Result += "\nstatic struct {\n";
2712 Result += "\tstruct _objc_protocol_list *next;\n";
2713 Result += "\tint protocol_count;\n";
2714 Result += "\tstruct _objc_protocol *class_protocols[";
2715 Result += utostr(Protocols.size());
2716 Result += "];\n} _OBJC_";
2717 Result += prefix;
2718 Result += "_PROTOCOLS_";
2719 Result += ClassName;
2720 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2721 "{\n\t0, ";
2722 Result += utostr(Protocols.size());
2723 Result += "\n";
2724
2725 Result += "\t,{&_OBJC_PROTOCOL_";
2726 Result += Protocols[0]->getName();
2727 Result += " \n";
2728
2729 for (unsigned i = 1; i != Protocols.size(); i++) {
2730 Result += "\t ,&_OBJC_PROTOCOL_";
2731 Result += Protocols[i]->getName();
2732 Result += "\n";
2733 }
2734 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002735}
2736
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002737/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002738/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00002739void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002740 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002741 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002742 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002743 ObjCCategoryDecl *CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002744 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2745 CDecl = CDecl->getNextClassCategory())
2746 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2747 break;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002748
Chris Lattnereb44eee2007-12-23 01:40:15 +00002749 std::string FullCategoryName = ClassDecl->getName();
2750 FullCategoryName += '_';
2751 FullCategoryName += IDecl->getName();
2752
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002753 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002754 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002755 true, "CATEGORY_", FullCategoryName.c_str(),
2756 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002757
2758 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002759 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002760 false, "CATEGORY_", FullCategoryName.c_str(),
2761 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002762
2763 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002764 // Null CDecl is case of a category implementation with no category interface
2765 if (CDecl)
Chris Lattner780f3292008-07-21 21:32:27 +00002766 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Chris Lattnereb44eee2007-12-23 01:40:15 +00002767 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002768
2769 /* struct _objc_category {
2770 char *category_name;
2771 char *class_name;
2772 struct _objc_method_list *instance_methods;
2773 struct _objc_method_list *class_methods;
2774 struct _objc_protocol_list *protocols;
2775 // Objective-C 1.0 extensions
2776 uint32_t size; // sizeof (struct _objc_category)
2777 struct _objc_property_list *instance_properties; // category's own
2778 // @property decl.
2779 };
2780 */
2781
2782 static bool objc_category = false;
2783 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002784 Result += "\nstruct _objc_category {\n";
2785 Result += "\tchar *category_name;\n";
2786 Result += "\tchar *class_name;\n";
2787 Result += "\tstruct _objc_method_list *instance_methods;\n";
2788 Result += "\tstruct _objc_method_list *class_methods;\n";
2789 Result += "\tstruct _objc_protocol_list *protocols;\n";
2790 Result += "\tunsigned int size;\n";
2791 Result += "\tstruct _objc_property_list *instance_properties;\n";
2792 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002793 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002794 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002795 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2796 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002797 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002798 Result += IDecl->getName();
2799 Result += "\"\n\t, \"";
2800 Result += ClassDecl->getName();
2801 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002802
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002803 if (IDecl->getNumInstanceMethods() > 0) {
2804 Result += "\t, (struct _objc_method_list *)"
2805 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2806 Result += FullCategoryName;
2807 Result += "\n";
2808 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002809 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002810 Result += "\t, 0\n";
2811 if (IDecl->getNumClassMethods() > 0) {
2812 Result += "\t, (struct _objc_method_list *)"
2813 "&_OBJC_CATEGORY_CLASS_METHODS_";
2814 Result += FullCategoryName;
2815 Result += "\n";
2816 }
2817 else
2818 Result += "\t, 0\n";
2819
Chris Lattner780f3292008-07-21 21:32:27 +00002820 if (CDecl && !CDecl->getReferencedProtocols().empty()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002821 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2822 Result += FullCategoryName;
2823 Result += "\n";
2824 }
2825 else
2826 Result += "\t, 0\n";
2827 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002828}
2829
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002830/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2831/// ivar offset.
Steve Naroffb29b4272008-04-14 22:03:09 +00002832void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002833 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002834 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00002835 if (ivar->isBitField()) {
2836 // FIXME: The hack below doesn't work for bitfields. For now, we simply
2837 // place all bitfields at offset 0.
2838 Result += "0";
2839 } else {
2840 Result += "__OFFSETOFIVAR__(struct ";
2841 Result += IDecl->getName();
2842 if (LangOpts.Microsoft)
2843 Result += "_IMPL";
2844 Result += ", ";
2845 Result += ivar->getName();
2846 Result += ")";
2847 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002848}
2849
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002850//===----------------------------------------------------------------------===//
2851// Meta Data Emission
2852//===----------------------------------------------------------------------===//
2853
Steve Naroffb29b4272008-04-14 22:03:09 +00002854void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002855 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002856 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002857
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002858 // Explictly declared @interface's are already synthesized.
2859 if (CDecl->ImplicitInterfaceDecl()) {
2860 // FIXME: Implementation of a class with no @interface (legacy) doese not
2861 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002862 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002863 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002864
Chris Lattnerbe6df082007-12-12 07:56:42 +00002865 // Build _objc_ivar_list metadata for classes ivars if needed
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002866 unsigned NumIvars = !IDecl->ivar_empty()
2867 ? IDecl->ivar_size()
2868 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002869 if (NumIvars > 0) {
2870 static bool objc_ivar = false;
2871 if (!objc_ivar) {
2872 /* struct _objc_ivar {
2873 char *ivar_name;
2874 char *ivar_type;
2875 int ivar_offset;
2876 };
2877 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002878 Result += "\nstruct _objc_ivar {\n";
2879 Result += "\tchar *ivar_name;\n";
2880 Result += "\tchar *ivar_type;\n";
2881 Result += "\tint ivar_offset;\n";
2882 Result += "};\n";
2883
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002884 objc_ivar = true;
2885 }
2886
Steve Naroff946a6932008-03-11 00:12:29 +00002887 /* struct {
2888 int ivar_count;
2889 struct _objc_ivar ivar_list[nIvars];
2890 };
2891 */
2892 Result += "\nstatic struct {\n";
2893 Result += "\tint ivar_count;\n";
2894 Result += "\tstruct _objc_ivar ivar_list[";
2895 Result += utostr(NumIvars);
2896 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002897 Result += IDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002898 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002899 "{\n\t";
2900 Result += utostr(NumIvars);
2901 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002902
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002903 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002904 if (!IDecl->ivar_empty()) {
Chris Lattnerbe6df082007-12-12 07:56:42 +00002905 IVI = IDecl->ivar_begin();
2906 IVE = IDecl->ivar_end();
2907 } else {
2908 IVI = CDecl->ivar_begin();
2909 IVE = CDecl->ivar_end();
2910 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002911 Result += "\t,{{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002912 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002913 Result += "\", \"";
2914 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002915 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002916 Result += StrEncoding;
2917 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002918 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002919 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002920 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002921 Result += "\t ,{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002922 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002923 Result += "\", \"";
2924 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002925 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002926 Result += StrEncoding;
2927 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002928 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002929 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002930 }
2931
2932 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002933 }
2934
2935 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002936 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002937 true, "", IDecl->getIdentifierName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002938
2939 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002940 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002941 false, "", IDecl->getIdentifierName(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002942
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002943 // Protocols referenced in class declaration?
Chris Lattner780f3292008-07-21 21:32:27 +00002944 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002945 "CLASS", CDecl->getIdentifierName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002946
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002947
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002948 // Declaration of class/meta-class metadata
2949 /* struct _objc_class {
2950 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002951 const char *super_class_name;
2952 char *name;
2953 long version;
2954 long info;
2955 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002956 struct _objc_ivar_list *ivars;
2957 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002958 struct objc_cache *cache;
2959 struct objc_protocol_list *protocols;
2960 const char *ivar_layout;
2961 struct _objc_class_ext *ext;
2962 };
2963 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002964 static bool objc_class = false;
2965 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002966 Result += "\nstruct _objc_class {\n";
2967 Result += "\tstruct _objc_class *isa;\n";
2968 Result += "\tconst char *super_class_name;\n";
2969 Result += "\tchar *name;\n";
2970 Result += "\tlong version;\n";
2971 Result += "\tlong info;\n";
2972 Result += "\tlong instance_size;\n";
2973 Result += "\tstruct _objc_ivar_list *ivars;\n";
2974 Result += "\tstruct _objc_method_list *methods;\n";
2975 Result += "\tstruct objc_cache *cache;\n";
2976 Result += "\tstruct _objc_protocol_list *protocols;\n";
2977 Result += "\tconst char *ivar_layout;\n";
2978 Result += "\tstruct _objc_class_ext *ext;\n";
2979 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002980 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002981 }
2982
2983 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002984 ObjCInterfaceDecl *RootClass = 0;
2985 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002986 while (SuperClass) {
2987 RootClass = SuperClass;
2988 SuperClass = SuperClass->getSuperClass();
2989 }
2990 SuperClass = CDecl->getSuperClass();
2991
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002992 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2993 Result += CDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002994 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002995 "{\n\t(struct _objc_class *)\"";
2996 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2997 Result += "\"";
2998
2999 if (SuperClass) {
3000 Result += ", \"";
3001 Result += SuperClass->getName();
3002 Result += "\", \"";
3003 Result += CDecl->getName();
3004 Result += "\"";
3005 }
3006 else {
3007 Result += ", 0, \"";
3008 Result += CDecl->getName();
3009 Result += "\"";
3010 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003011 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003012 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003013 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffb26d7132007-12-05 21:49:40 +00003014 if (IDecl->getNumClassMethods() > 0) {
Steve Naroff23f41272008-03-11 18:14:26 +00003015 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Steve Naroffb26d7132007-12-05 21:49:40 +00003016 Result += IDecl->getName();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003017 Result += "\n";
3018 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003019 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003020 Result += ", 0\n";
Chris Lattner3db6cae2008-07-21 18:19:38 +00003021 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003022 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003023 Result += CDecl->getName();
3024 Result += ",0,0\n";
3025 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003026 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003027 Result += "\t,0,0,0,0\n";
3028 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003029
3030 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003031 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
3032 Result += CDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00003033 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003034 "{\n\t&_OBJC_METACLASS_";
3035 Result += CDecl->getName();
3036 if (SuperClass) {
3037 Result += ", \"";
3038 Result += SuperClass->getName();
3039 Result += "\", \"";
3040 Result += CDecl->getName();
3041 Result += "\"";
3042 }
3043 else {
3044 Result += ", 0, \"";
3045 Result += CDecl->getName();
3046 Result += "\"";
3047 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003048 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003049 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003050 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003051 Result += ",0";
3052 else {
3053 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003054 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003055 Result += CDecl->getName();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003056 if (LangOpts.Microsoft)
3057 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003058 Result += ")";
3059 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003060 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00003061 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003062 Result += CDecl->getName();
3063 Result += "\n\t";
3064 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003065 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003066 Result += ",0";
3067 if (IDecl->getNumInstanceMethods() > 0) {
Steve Naroff946a6932008-03-11 00:12:29 +00003068 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003069 Result += CDecl->getName();
3070 Result += ", 0\n\t";
3071 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003072 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003073 Result += ",0,0";
Chris Lattner3db6cae2008-07-21 18:19:38 +00003074 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003075 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003076 Result += CDecl->getName();
3077 Result += ", 0,0\n";
3078 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003079 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003080 Result += ",0,0,0\n";
3081 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003082}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003083
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003084/// RewriteImplementations - This routine rewrites all method implementations
3085/// and emits meta-data.
3086
Steve Narofface66252008-11-13 20:07:04 +00003087void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003088 int ClsDefCount = ClassImplementation.size();
3089 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003090
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003091 // Rewrite implemented methods
3092 for (int i = 0; i < ClsDefCount; i++)
3093 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003094
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003095 for (int i = 0; i < CatDefCount; i++)
3096 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00003097}
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003098
Steve Narofface66252008-11-13 20:07:04 +00003099void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3100 int ClsDefCount = ClassImplementation.size();
3101 int CatDefCount = CategoryImplementation.size();
3102
Steve Naroff5df5b762008-05-07 21:23:49 +00003103 // This is needed for determining instance variable offsets.
Steve Naroffa11440b2008-08-05 18:47:23 +00003104 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003105 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003106 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003107 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003108
3109 // For each implemented category, write out all its meta data.
3110 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003111 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003112
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003113 // Write objc_symtab metadata
3114 /*
3115 struct _objc_symtab
3116 {
3117 long sel_ref_cnt;
3118 SEL *refs;
3119 short cls_def_cnt;
3120 short cat_def_cnt;
3121 void *defs[cls_def_cnt + cat_def_cnt];
3122 };
3123 */
3124
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003125 Result += "\nstruct _objc_symtab {\n";
3126 Result += "\tlong sel_ref_cnt;\n";
3127 Result += "\tSEL *refs;\n";
3128 Result += "\tshort cls_def_cnt;\n";
3129 Result += "\tshort cat_def_cnt;\n";
3130 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3131 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003132
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003133 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00003134 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003135 Result += "\t0, 0, " + utostr(ClsDefCount)
3136 + ", " + utostr(CatDefCount) + "\n";
3137 for (int i = 0; i < ClsDefCount; i++) {
3138 Result += "\t,&_OBJC_CLASS_";
3139 Result += ClassImplementation[i]->getName();
3140 Result += "\n";
3141 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003142
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003143 for (int i = 0; i < CatDefCount; i++) {
3144 Result += "\t,&_OBJC_CATEGORY_";
3145 Result += CategoryImplementation[i]->getClassInterface()->getName();
3146 Result += "_";
3147 Result += CategoryImplementation[i]->getName();
3148 Result += "\n";
3149 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003150
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003151 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003152
3153 // Write objc_module metadata
3154
3155 /*
3156 struct _objc_module {
3157 long version;
3158 long size;
3159 const char *name;
3160 struct _objc_symtab *symtab;
3161 }
3162 */
3163
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003164 Result += "\nstruct _objc_module {\n";
3165 Result += "\tlong version;\n";
3166 Result += "\tlong size;\n";
3167 Result += "\tconst char *name;\n";
3168 Result += "\tstruct _objc_symtab *symtab;\n";
3169 Result += "};\n\n";
3170 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00003171 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003172 Result += "\t" + utostr(OBJC_ABI_VERSION) +
3173 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003174 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003175
3176 if (LangOpts.Microsoft) {
3177 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00003178 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003179 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3180 Result += "&_OBJC_MODULES;\n";
3181 Result += "#pragma data_seg(pop)\n\n";
3182 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003183}
Chris Lattner311ff022007-10-16 22:36:42 +00003184
Steve Naroff54055232008-10-27 17:20:55 +00003185std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3186 const char *funcName,
3187 std::string Tag) {
3188 const FunctionType *AFT = CE->getFunctionType();
3189 QualType RT = AFT->getResultType();
3190 std::string StructRef = "struct " + Tag;
3191 std::string S = "static " + RT.getAsString() + " __" +
3192 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003193
Steve Naroff54055232008-10-27 17:20:55 +00003194 BlockDecl *BD = CE->getBlockDecl();
3195
3196 if (isa<FunctionTypeNoProto>(AFT)) {
3197 S += "()";
3198 } else if (BD->param_empty()) {
3199 S += "(" + StructRef + " *__cself)";
3200 } else {
3201 const FunctionTypeProto *FT = cast<FunctionTypeProto>(AFT);
3202 assert(FT && "SynthesizeBlockFunc: No function proto");
3203 S += '(';
3204 // first add the implicit argument.
3205 S += StructRef + " *__cself, ";
3206 std::string ParamStr;
3207 for (BlockDecl::param_iterator AI = BD->param_begin(),
3208 E = BD->param_end(); AI != E; ++AI) {
3209 if (AI != BD->param_begin()) S += ", ";
3210 ParamStr = (*AI)->getName();
3211 (*AI)->getType().getAsStringInternal(ParamStr);
3212 S += ParamStr;
3213 }
3214 if (FT->isVariadic()) {
3215 if (!BD->param_empty()) S += ", ";
3216 S += "...";
3217 }
3218 S += ')';
3219 }
3220 S += " {\n";
3221
3222 // Create local declarations to avoid rewriting all closure decl ref exprs.
3223 // First, emit a declaration for all "by ref" decls.
3224 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3225 E = BlockByRefDecls.end(); I != E; ++I) {
3226 S += " ";
3227 std::string Name = (*I)->getName();
3228 Context->getPointerType((*I)->getType()).getAsStringInternal(Name);
3229 S += Name + " = __cself->" + (*I)->getName() + "; // bound by ref\n";
3230 }
3231 // Next, emit a declaration for all "by copy" declarations.
3232 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3233 E = BlockByCopyDecls.end(); I != E; ++I) {
3234 S += " ";
3235 std::string Name = (*I)->getName();
3236 // Handle nested closure invocation. For example:
3237 //
3238 // void (^myImportedClosure)(void);
3239 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3240 //
3241 // void (^anotherClosure)(void);
3242 // anotherClosure = ^(void) {
3243 // myImportedClosure(); // import and invoke the closure
3244 // };
3245 //
3246 if (isBlockPointerType((*I)->getType()))
3247 S += "struct __block_impl *";
3248 else
3249 (*I)->getType().getAsStringInternal(Name);
3250 S += Name + " = __cself->" + (*I)->getName() + "; // bound by copy\n";
3251 }
3252 std::string RewrittenStr = RewrittenBlockExprs[CE];
3253 const char *cstr = RewrittenStr.c_str();
3254 while (*cstr++ != '{') ;
3255 S += cstr;
3256 S += "\n";
3257 return S;
3258}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003259
Steve Naroff54055232008-10-27 17:20:55 +00003260std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3261 const char *funcName,
3262 std::string Tag) {
3263 std::string StructRef = "struct " + Tag;
3264 std::string S = "static void __";
3265
3266 S += funcName;
3267 S += "_block_copy_" + utostr(i);
3268 S += "(" + StructRef;
3269 S += "*dst, " + StructRef;
3270 S += "*src) {";
3271 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3272 E = ImportedBlockDecls.end(); I != E; ++I) {
3273 S += "_Block_copy_assign(&dst->";
3274 S += (*I)->getName();
3275 S += ", src->";
3276 S += (*I)->getName();
3277 S += ");}";
3278 }
3279 S += "\nstatic void __";
3280 S += funcName;
3281 S += "_block_dispose_" + utostr(i);
3282 S += "(" + StructRef;
3283 S += "*src) {";
3284 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3285 E = ImportedBlockDecls.end(); I != E; ++I) {
3286 S += "_Block_destroy(src->";
3287 S += (*I)->getName();
3288 S += ");";
3289 }
3290 S += "}\n";
3291 return S;
3292}
3293
3294std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3295 bool hasCopyDisposeHelpers) {
Steve Naroffced80a82008-10-30 12:09:33 +00003296 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00003297 std::string Constructor = " " + Tag;
3298
3299 S += " {\n struct __block_impl impl;\n";
3300
3301 if (hasCopyDisposeHelpers)
3302 S += " void *copy;\n void *dispose;\n";
3303
3304 Constructor += "(void *fp";
3305
3306 if (hasCopyDisposeHelpers)
3307 Constructor += ", void *copyHelp, void *disposeHelp";
3308
3309 if (BlockDeclRefs.size()) {
3310 // Output all "by copy" declarations.
3311 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3312 E = BlockByCopyDecls.end(); I != E; ++I) {
3313 S += " ";
3314 std::string FieldName = (*I)->getName();
3315 std::string ArgName = "_" + FieldName;
3316 // Handle nested closure invocation. For example:
3317 //
3318 // void (^myImportedBlock)(void);
3319 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3320 //
3321 // void (^anotherBlock)(void);
3322 // anotherBlock = ^(void) {
3323 // myImportedBlock(); // import and invoke the closure
3324 // };
3325 //
3326 if (isBlockPointerType((*I)->getType())) {
3327 S += "struct __block_impl *";
3328 Constructor += ", void *" + ArgName;
3329 } else {
3330 (*I)->getType().getAsStringInternal(FieldName);
3331 (*I)->getType().getAsStringInternal(ArgName);
3332 Constructor += ", " + ArgName;
3333 }
3334 S += FieldName + ";\n";
3335 }
3336 // Output all "by ref" declarations.
3337 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3338 E = BlockByRefDecls.end(); I != E; ++I) {
3339 S += " ";
3340 std::string FieldName = (*I)->getName();
3341 std::string ArgName = "_" + FieldName;
3342 // Handle nested closure invocation. For example:
3343 //
3344 // void (^myImportedBlock)(void);
3345 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3346 //
3347 // void (^anotherBlock)(void);
3348 // anotherBlock = ^(void) {
3349 // myImportedBlock(); // import and invoke the closure
3350 // };
3351 //
3352 if (isBlockPointerType((*I)->getType())) {
3353 S += "struct __block_impl *";
3354 Constructor += ", void *" + ArgName;
3355 } else {
3356 Context->getPointerType((*I)->getType()).getAsStringInternal(FieldName);
3357 Context->getPointerType((*I)->getType()).getAsStringInternal(ArgName);
3358 Constructor += ", " + ArgName;
3359 }
3360 S += FieldName + "; // by ref\n";
3361 }
3362 // Finish writing the constructor.
3363 // FIXME: handle NSConcreteGlobalBlock.
3364 Constructor += ", int flags=0) {\n";
3365 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3366 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3367
3368 if (hasCopyDisposeHelpers)
3369 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3370
3371 // Initialize all "by copy" arguments.
3372 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3373 E = BlockByCopyDecls.end(); I != E; ++I) {
3374 std::string Name = (*I)->getName();
3375 Constructor += " ";
3376 if (isBlockPointerType((*I)->getType()))
3377 Constructor += Name + " = (struct __block_impl *)_";
3378 else
3379 Constructor += Name + " = _";
3380 Constructor += Name + ";\n";
3381 }
3382 // Initialize all "by ref" arguments.
3383 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3384 E = BlockByRefDecls.end(); I != E; ++I) {
3385 std::string Name = (*I)->getName();
3386 Constructor += " ";
3387 if (isBlockPointerType((*I)->getType()))
3388 Constructor += Name + " = (struct __block_impl *)_";
3389 else
3390 Constructor += Name + " = _";
3391 Constructor += Name + ";\n";
3392 }
3393 } else {
3394 // Finish writing the constructor.
3395 // FIXME: handle NSConcreteGlobalBlock.
3396 Constructor += ", int flags=0) {\n";
3397 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3398 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3399 if (hasCopyDisposeHelpers)
3400 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3401 }
3402 Constructor += " ";
3403 Constructor += "}\n";
3404 S += Constructor;
3405 S += "};\n";
3406 return S;
3407}
3408
3409void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3410 const char *FunName) {
3411 // Insert closures that were part of the function.
3412 for (unsigned i = 0; i < Blocks.size(); i++) {
3413
3414 CollectBlockDeclRefInfo(Blocks[i]);
3415
3416 std::string Tag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
3417
3418 std::string CI = SynthesizeBlockImpl(Blocks[i], Tag,
3419 ImportedBlockDecls.size() > 0);
3420
3421 InsertText(FunLocStart, CI.c_str(), CI.size());
3422
3423 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, Tag);
3424
3425 InsertText(FunLocStart, CF.c_str(), CF.size());
3426
3427 if (ImportedBlockDecls.size()) {
3428 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, Tag);
3429 InsertText(FunLocStart, HF.c_str(), HF.size());
3430 }
3431
3432 BlockDeclRefs.clear();
3433 BlockByRefDecls.clear();
3434 BlockByCopyDecls.clear();
3435 BlockCallExprs.clear();
3436 ImportedBlockDecls.clear();
3437 }
3438 Blocks.clear();
3439 RewrittenBlockExprs.clear();
3440}
3441
3442void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3443 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003444 const char *FuncName = FD->getIdentifierName();
Steve Naroff54055232008-10-27 17:20:55 +00003445
3446 SynthesizeBlockLiterals(FunLocStart, FuncName);
3447}
3448
3449void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00003450 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3451 //SourceLocation FunLocStart = MD->getLocStart();
3452 // FIXME: This hack works around a bug in Rewrite.InsertText().
3453 SourceLocation FunLocStart = MD->getLocStart().getFileLocWithOffset(-1);
Steve Naroff54055232008-10-27 17:20:55 +00003454 std::string FuncName = std::string(MD->getSelector().getName());
3455 // Convert colons to underscores.
3456 std::string::size_type loc = 0;
3457 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3458 FuncName.replace(loc, 1, "_");
3459
3460 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
3461}
3462
3463void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
3464 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3465 CI != E; ++CI)
3466 if (*CI) {
3467 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3468 GetBlockDeclRefExprs(CBE->getBody());
3469 else
3470 GetBlockDeclRefExprs(*CI);
3471 }
3472 // Handle specific things.
3473 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
3474 // FIXME: Handle enums.
3475 if (!isa<FunctionDecl>(CDRE->getDecl()))
3476 BlockDeclRefs.push_back(CDRE);
3477 return;
3478}
3479
3480void RewriteObjC::GetBlockCallExprs(Stmt *S) {
3481 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3482 CI != E; ++CI)
3483 if (*CI) {
3484 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3485 GetBlockCallExprs(CBE->getBody());
3486 else
3487 GetBlockCallExprs(*CI);
3488 }
3489
3490 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
3491 if (CE->getCallee()->getType()->isBlockPointerType()) {
3492 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
3493 }
3494 }
3495 return;
3496}
3497
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003498Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00003499 // Navigate to relevant type information.
3500 const char *closureName = 0;
3501 const BlockPointerType *CPT = 0;
3502
3503 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp->getCallee())) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003504 closureName = DRE->getDecl()->getIdentifierName();
Steve Naroff54055232008-10-27 17:20:55 +00003505 CPT = DRE->getType()->getAsBlockPointerType();
3506 } else if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(Exp->getCallee())) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003507 closureName = CDRE->getDecl()->getIdentifierName();
Steve Naroff54055232008-10-27 17:20:55 +00003508 CPT = CDRE->getType()->getAsBlockPointerType();
3509 } else if (MemberExpr *MExpr = dyn_cast<MemberExpr>(Exp->getCallee())) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003510 closureName = MExpr->getMemberDecl()->getIdentifierName();
Steve Naroff54055232008-10-27 17:20:55 +00003511 CPT = MExpr->getType()->getAsBlockPointerType();
3512 } else {
3513 assert(1 && "RewriteBlockClass: Bad type");
3514 }
3515 assert(CPT && "RewriteBlockClass: Bad type");
3516 const FunctionType *FT = CPT->getPointeeType()->getAsFunctionType();
3517 assert(FT && "RewriteBlockClass: Bad type");
3518 const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(FT);
3519 // FTP will be null for closures that don't take arguments.
3520
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003521 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
3522 SourceLocation(),
3523 &Context->Idents.get("__block_impl"));
3524 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00003525
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003526 // Generate a funky cast.
3527 llvm::SmallVector<QualType, 8> ArgTypes;
3528
3529 // Push the block argument type.
3530 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00003531 if (FTP) {
3532 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003533 E = FTP->arg_type_end(); I && (I != E); ++I) {
3534 QualType t = *I;
3535 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3536 if (isBlockPointerType(t)) {
3537 const BlockPointerType *BPT = t->getAsBlockPointerType();
3538 t = Context->getPointerType(BPT->getPointeeType());
3539 }
3540 ArgTypes.push_back(t);
3541 }
Steve Naroff54055232008-10-27 17:20:55 +00003542 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003543 // Now do the pointer to function cast.
3544 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
3545 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
3546
3547 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Steve Naroff54055232008-10-27 17:20:55 +00003548
Steve Naroffb2f9e512008-11-03 23:29:32 +00003549 CastExpr *BlkCast = new CStyleCastExpr(PtrBlock, Exp->getCallee(), PtrBlock, SourceLocation(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003550 // Don't forget the parens to enforce the proper binding.
3551 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), BlkCast);
3552 //PE->dump();
Steve Naroff54055232008-10-27 17:20:55 +00003553
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003554 FieldDecl *FD = FieldDecl::Create(*Context, SourceLocation(),
3555 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy);
3556 MemberExpr *ME = new MemberExpr(PE, true, FD, SourceLocation(), FD->getType());
3557
Steve Naroffb2f9e512008-11-03 23:29:32 +00003558 CastExpr *FunkCast = new CStyleCastExpr(PtrToFuncCastType, ME, PtrToFuncCastType, SourceLocation(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003559 PE = new ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
3560
3561 llvm::SmallVector<Expr*, 8> BlkExprs;
3562 // Add the implicit argument.
3563 BlkExprs.push_back(BlkCast);
3564 // Add the user arguments.
Steve Naroff54055232008-10-27 17:20:55 +00003565 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3566 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003567 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00003568 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003569 CallExpr *CE = new CallExpr(PE, &BlkExprs[0], BlkExprs.size(), Exp->getType(), SourceLocation());
3570 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00003571}
3572
3573void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003574 Stmt *BlockCall = SynthesizeBlockCall(Exp);
3575 ReplaceStmt(Exp, BlockCall);
Steve Naroff54055232008-10-27 17:20:55 +00003576}
3577
3578void RewriteObjC::RewriteBlockDeclRefExpr(BlockDeclRefExpr *BDRE) {
3579 // FIXME: Add more elaborate code generation required by the ABI.
3580 InsertText(BDRE->getLocStart(), "*", 1);
3581}
3582
Steve Naroffb2f9e512008-11-03 23:29:32 +00003583void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3584 SourceLocation LocStart = CE->getLParenLoc();
3585 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00003586
3587 // Need to avoid trying to rewrite synthesized casts.
3588 if (LocStart.isInvalid())
3589 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00003590 // Need to avoid trying to rewrite casts contained in macros.
3591 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3592 return;
Steve Narofffa15fd92008-10-28 20:29:00 +00003593
Steve Naroff54055232008-10-27 17:20:55 +00003594 const char *startBuf = SM->getCharacterData(LocStart);
3595 const char *endBuf = SM->getCharacterData(LocEnd);
3596
3597 // advance the location to startArgList.
3598 const char *argPtr = startBuf;
3599
3600 while (*argPtr++ && (argPtr < endBuf)) {
3601 switch (*argPtr) {
3602 case '^':
3603 // Replace the '^' with '*'.
3604 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
3605 ReplaceText(LocStart, 1, "*", 1);
3606 break;
3607 }
3608 }
3609 return;
3610}
3611
3612void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
3613 SourceLocation DeclLoc = FD->getLocation();
3614 unsigned parenCount = 0;
3615
3616 // We have 1 or more arguments that have closure pointers.
3617 const char *startBuf = SM->getCharacterData(DeclLoc);
3618 const char *startArgList = strchr(startBuf, '(');
3619
3620 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
3621
3622 parenCount++;
3623 // advance the location to startArgList.
3624 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
3625 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
3626
3627 const char *argPtr = startArgList;
3628
3629 while (*argPtr++ && parenCount) {
3630 switch (*argPtr) {
3631 case '^':
3632 // Replace the '^' with '*'.
3633 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
3634 ReplaceText(DeclLoc, 1, "*", 1);
3635 break;
3636 case '(':
3637 parenCount++;
3638 break;
3639 case ')':
3640 parenCount--;
3641 break;
3642 }
3643 }
3644 return;
3645}
3646
3647bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
3648 const FunctionTypeProto *FTP;
3649 const PointerType *PT = QT->getAsPointerType();
3650 if (PT) {
3651 FTP = PT->getPointeeType()->getAsFunctionTypeProto();
3652 } else {
3653 const BlockPointerType *BPT = QT->getAsBlockPointerType();
3654 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
3655 FTP = BPT->getPointeeType()->getAsFunctionTypeProto();
3656 }
3657 if (FTP) {
3658 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
3659 E = FTP->arg_type_end(); I != E; ++I)
3660 if (isBlockPointerType(*I))
3661 return true;
3662 }
3663 return false;
3664}
3665
3666void RewriteObjC::GetExtentOfArgList(const char *Name,
3667 const char *&LParen, const char *&RParen) {
3668 const char *argPtr = strchr(Name, '(');
3669 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
3670
3671 LParen = argPtr; // output the start.
3672 argPtr++; // skip past the left paren.
3673 unsigned parenCount = 1;
3674
3675 while (*argPtr && parenCount) {
3676 switch (*argPtr) {
3677 case '(': parenCount++; break;
3678 case ')': parenCount--; break;
3679 default: break;
3680 }
3681 if (parenCount) argPtr++;
3682 }
3683 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
3684 RParen = argPtr; // output the end
3685}
3686
3687void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
3688 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3689 RewriteBlockPointerFunctionArgs(FD);
3690 return;
3691 }
3692 // Handle Variables and Typedefs.
3693 SourceLocation DeclLoc = ND->getLocation();
3694 QualType DeclT;
3695 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3696 DeclT = VD->getType();
3697 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
3698 DeclT = TDD->getUnderlyingType();
3699 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
3700 DeclT = FD->getType();
3701 else
3702 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
3703
3704 const char *startBuf = SM->getCharacterData(DeclLoc);
3705 const char *endBuf = startBuf;
3706 // scan backward (from the decl location) for the end of the previous decl.
3707 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
3708 startBuf--;
3709
3710 // *startBuf != '^' if we are dealing with a pointer to function that
3711 // may take block argument types (which will be handled below).
3712 if (*startBuf == '^') {
3713 // Replace the '^' with '*', computing a negative offset.
3714 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
3715 ReplaceText(DeclLoc, 1, "*", 1);
3716 }
3717 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
3718 // Replace the '^' with '*' for arguments.
3719 DeclLoc = ND->getLocation();
3720 startBuf = SM->getCharacterData(DeclLoc);
3721 const char *argListBegin, *argListEnd;
3722 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
3723 while (argListBegin < argListEnd) {
3724 if (*argListBegin == '^') {
3725 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
3726 ReplaceText(CaretLoc, 1, "*", 1);
3727 }
3728 argListBegin++;
3729 }
3730 }
3731 return;
3732}
3733
3734void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
3735 // Add initializers for any closure decl refs.
3736 GetBlockDeclRefExprs(Exp->getBody());
3737 if (BlockDeclRefs.size()) {
3738 // Unique all "by copy" declarations.
3739 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3740 if (!BlockDeclRefs[i]->isByRef())
3741 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
3742 // Unique all "by ref" declarations.
3743 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3744 if (BlockDeclRefs[i]->isByRef()) {
3745 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
3746 }
3747 // Find any imported blocks...they will need special attention.
3748 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3749 if (isBlockPointerType(BlockDeclRefs[i]->getType())) {
Steve Naroff00072682008-11-13 17:40:07 +00003750 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff54055232008-10-27 17:20:55 +00003751 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
3752 }
3753 }
3754}
3755
Steve Narofffa15fd92008-10-28 20:29:00 +00003756FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
3757 IdentifierInfo *ID = &Context->Idents.get(name);
3758 QualType FType = Context->getFunctionTypeNoProto(Context->VoidPtrTy);
3759 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
3760 ID, FType, FunctionDecl::Extern, false, 0);
3761}
3762
Steve Naroff8e2f57a2008-10-29 18:15:37 +00003763Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Narofffa15fd92008-10-28 20:29:00 +00003764 Blocks.push_back(Exp);
3765
3766 CollectBlockDeclRefInfo(Exp);
3767 std::string FuncName;
3768
3769 if (CurFunctionDef)
3770 FuncName = std::string(CurFunctionDef->getName());
3771 else if (CurMethodDef) {
3772 FuncName = std::string(CurMethodDef->getSelector().getName());
3773 // Convert colons to underscores.
3774 std::string::size_type loc = 0;
3775 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3776 FuncName.replace(loc, 1, "_");
Steve Naroff8e2f57a2008-10-29 18:15:37 +00003777 } else if (GlobalVarDecl)
3778 FuncName = std::string(GlobalVarDecl->getName());
Steve Narofffa15fd92008-10-28 20:29:00 +00003779
3780 std::string BlockNumber = utostr(Blocks.size()-1);
3781
3782 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
3783 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
3784
3785 // Get a pointer to the function type so we can cast appropriately.
3786 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
3787
3788 FunctionDecl *FD;
3789 Expr *NewRep;
3790
3791 // Simulate a contructor call...
3792 FD = SynthBlockInitFunctionDecl(Tag.c_str());
3793 DeclRefExpr *DRE = new DeclRefExpr(FD, FType, SourceLocation());
3794
3795 llvm::SmallVector<Expr*, 4> InitExprs;
3796
Steve Narofffdc03722008-10-29 21:23:59 +00003797 // Initialize the block function.
Steve Narofffa15fd92008-10-28 20:29:00 +00003798 FD = SynthBlockInitFunctionDecl(Func.c_str());
3799 DeclRefExpr *Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3800 CastExpr *castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00003801 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00003802 InitExprs.push_back(castExpr);
Steve Narofffa15fd92008-10-28 20:29:00 +00003803
3804 if (ImportedBlockDecls.size()) {
3805 std::string Buf = "__" + FuncName + "_block_copy_" + BlockNumber;
Steve Narofffdc03722008-10-29 21:23:59 +00003806 FD = SynthBlockInitFunctionDecl(Buf.c_str());
3807 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3808 castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00003809 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffdc03722008-10-29 21:23:59 +00003810 InitExprs.push_back(castExpr);
3811
Steve Narofffa15fd92008-10-28 20:29:00 +00003812 Buf = "__" + FuncName + "_block_dispose_" + BlockNumber;
Steve Narofffdc03722008-10-29 21:23:59 +00003813 FD = SynthBlockInitFunctionDecl(Buf.c_str());
3814 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3815 castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00003816 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffdc03722008-10-29 21:23:59 +00003817 InitExprs.push_back(castExpr);
Steve Narofffa15fd92008-10-28 20:29:00 +00003818 }
3819 // Add initializers for any closure decl refs.
3820 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00003821 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00003822 // Output all "by copy" declarations.
3823 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3824 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00003825 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00003826 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003827 FD = SynthBlockInitFunctionDecl((*I)->getIdentifierName());
Steve Narofffdc03722008-10-29 21:23:59 +00003828 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00003829 } else if (isBlockPointerType((*I)->getType())) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003830 FD = SynthBlockInitFunctionDecl((*I)->getIdentifierName());
Steve Narofffdc03722008-10-29 21:23:59 +00003831 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3832 Exp = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00003833 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00003834 } else {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003835 FD = SynthBlockInitFunctionDecl((*I)->getIdentifierName());
Steve Narofffdc03722008-10-29 21:23:59 +00003836 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00003837 }
Steve Narofffdc03722008-10-29 21:23:59 +00003838 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00003839 }
3840 // Output all "by ref" declarations.
3841 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3842 E = BlockByRefDecls.end(); I != E; ++I) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003843 FD = SynthBlockInitFunctionDecl((*I)->getIdentifierName());
Steve Narofffdc03722008-10-29 21:23:59 +00003844 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3845 Exp = new UnaryOperator(Exp, UnaryOperator::AddrOf,
3846 Context->getPointerType(Exp->getType()),
3847 SourceLocation());
Steve Naroff707b0fe2008-11-14 21:36:12 +00003848 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00003849 }
3850 }
Steve Narofffa15fd92008-10-28 20:29:00 +00003851 NewRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
3852 FType, SourceLocation());
3853 NewRep = new UnaryOperator(NewRep, UnaryOperator::AddrOf,
3854 Context->getPointerType(NewRep->getType()),
3855 SourceLocation());
Steve Naroffb2f9e512008-11-03 23:29:32 +00003856 NewRep = new CStyleCastExpr(FType, NewRep, FType, SourceLocation(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00003857 BlockDeclRefs.clear();
3858 BlockByRefDecls.clear();
3859 BlockByCopyDecls.clear();
3860 ImportedBlockDecls.clear();
3861 return NewRep;
3862}
3863
3864//===----------------------------------------------------------------------===//
3865// Function Body / Expression rewriting
3866//===----------------------------------------------------------------------===//
3867
3868Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
3869 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
3870 isa<DoStmt>(S) || isa<ForStmt>(S))
3871 Stmts.push_back(S);
3872 else if (isa<ObjCForCollectionStmt>(S)) {
3873 Stmts.push_back(S);
3874 ObjCBcLabelNo.push_back(++BcLabelCount);
3875 }
3876
3877 SourceRange OrigStmtRange = S->getSourceRange();
3878
3879 // Perform a bottom up rewrite of all children.
3880 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3881 CI != E; ++CI)
3882 if (*CI) {
3883 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
3884 if (newStmt)
3885 *CI = newStmt;
3886 }
3887
3888 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
3889 // Rewrite the block body in place.
3890 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
3891
3892 // Now we snarf the rewritten text and stash it away for later use.
Steve Naroff8e2f57a2008-10-29 18:15:37 +00003893 std::string Str = Rewrite.getRewritenText(BE->getSourceRange());
3894 RewrittenBlockExprs[BE] = Str;
Steve Narofffa15fd92008-10-28 20:29:00 +00003895
3896 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
3897 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00003898 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00003899 return blockTranscribed;
3900 }
3901 // Handle specific things.
3902 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
3903 return RewriteAtEncode(AtEncode);
3904
3905 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
3906 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
3907
3908 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
3909 return RewriteAtSelector(AtSelector);
3910
3911 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
3912 return RewriteObjCStringLiteral(AtString);
3913
3914 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
3915 // Before we rewrite it, put the original message expression in a comment.
3916 SourceLocation startLoc = MessExpr->getLocStart();
3917 SourceLocation endLoc = MessExpr->getLocEnd();
3918
3919 const char *startBuf = SM->getCharacterData(startLoc);
3920 const char *endBuf = SM->getCharacterData(endLoc);
3921
3922 std::string messString;
3923 messString += "// ";
3924 messString.append(startBuf, endBuf-startBuf+1);
3925 messString += "\n";
3926
3927 // FIXME: Missing definition of
3928 // InsertText(clang::SourceLocation, char const*, unsigned int).
3929 // InsertText(startLoc, messString.c_str(), messString.size());
3930 // Tried this, but it didn't work either...
3931 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
3932 return RewriteMessageExpr(MessExpr);
3933 }
3934
3935 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
3936 return RewriteObjCTryStmt(StmtTry);
3937
3938 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
3939 return RewriteObjCSynchronizedStmt(StmtTry);
3940
3941 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
3942 return RewriteObjCThrowStmt(StmtThrow);
3943
3944 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
3945 return RewriteObjCProtocolExpr(ProtocolExp);
3946
3947 if (ObjCForCollectionStmt *StmtForCollection =
3948 dyn_cast<ObjCForCollectionStmt>(S))
3949 return RewriteObjCForCollectionStmt(StmtForCollection,
3950 OrigStmtRange.getEnd());
3951 if (BreakStmt *StmtBreakStmt =
3952 dyn_cast<BreakStmt>(S))
3953 return RewriteBreakStmt(StmtBreakStmt);
3954 if (ContinueStmt *StmtContinueStmt =
3955 dyn_cast<ContinueStmt>(S))
3956 return RewriteContinueStmt(StmtContinueStmt);
3957
3958 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
3959 // and cast exprs.
3960 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
3961 // FIXME: What we're doing here is modifying the type-specifier that
3962 // precedes the first Decl. In the future the DeclGroup should have
3963 // a separate type-specifier that we can rewrite.
3964 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
3965
3966 // Blocks rewrite rules.
3967 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
3968 DI != DE; ++DI) {
Steve Narofffa15fd92008-10-28 20:29:00 +00003969 ScopedDecl *SD = *DI;
3970 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
3971 if (isBlockPointerType(ND->getType()))
3972 RewriteBlockPointerDecl(ND);
3973 else if (ND->getType()->isFunctionPointerType())
3974 CheckFunctionPointerDecl(ND->getType(), ND);
3975 }
3976 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
3977 if (isBlockPointerType(TD->getUnderlyingType()))
3978 RewriteBlockPointerDecl(TD);
3979 else if (TD->getUnderlyingType()->isFunctionPointerType())
3980 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
3981 }
3982 }
3983 }
3984
3985 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
3986 RewriteObjCQualifiedInterfaceTypes(CE);
3987
3988 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
3989 isa<DoStmt>(S) || isa<ForStmt>(S)) {
3990 assert(!Stmts.empty() && "Statement stack is empty");
3991 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
3992 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
3993 && "Statement stack mismatch");
3994 Stmts.pop_back();
3995 }
3996 // Handle blocks rewriting.
3997 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
3998 if (BDRE->isByRef())
3999 RewriteBlockDeclRefExpr(BDRE);
4000 }
4001 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004002 if (CE->getCallee()->getType()->isBlockPointerType()) {
4003 Stmt *BlockCall = SynthesizeBlockCall(CE);
4004 ReplaceStmt(S, BlockCall);
4005 return BlockCall;
4006 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004007 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00004008 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004009 RewriteCastExpr(CE);
4010 }
4011#if 0
4012 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
4013 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
4014 // Get the new text.
4015 std::string SStr;
4016 llvm::raw_string_ostream Buf(SStr);
4017 Replacement->printPretty(Buf);
4018 const std::string &Str = Buf.str();
4019
4020 printf("CAST = %s\n", &Str[0]);
4021 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4022 delete S;
4023 return Replacement;
4024 }
4025#endif
4026 // Return this stmt unmodified.
4027 return S;
4028}
4029
4030/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4031/// main file of the input.
4032void RewriteObjC::HandleDeclInMainFile(Decl *D) {
4033 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4034 // Since function prototypes don't have ParmDecl's, we check the function
4035 // prototype. This enables us to rewrite function declarations and
4036 // definitions using the same code.
4037 RewriteBlocksInFunctionTypeProto(FD->getType(), FD);
4038
4039 if (Stmt *Body = FD->getBody()) {
4040 CurFunctionDef = FD;
4041 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
4042 // This synthesizes and inserts the block "impl" struct, invoke function,
4043 // and any copy/dispose helper functions.
4044 InsertBlockLiteralsWithinFunction(FD);
4045 CurFunctionDef = 0;
4046 }
4047 return;
4048 }
4049 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4050 if (Stmt *Body = MD->getBody()) {
4051 //Body->dump();
4052 CurMethodDef = MD;
4053 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
4054 InsertBlockLiteralsWithinMethod(MD);
4055 CurMethodDef = 0;
4056 }
4057 }
4058 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
4059 ClassImplementation.push_back(CI);
4060 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
4061 CategoryImplementation.push_back(CI);
4062 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
4063 RewriteForwardClassDecl(CD);
4064 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4065 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004066 if (isBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004067 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004068 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004069 CheckFunctionPointerDecl(VD->getType(), VD);
4070 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00004071 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004072 RewriteCastExpr(CE);
4073 }
4074 }
4075 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004076 if (VD->getInit()) {
4077 GlobalVarDecl = VD;
4078 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Douglas Gregor2e1cd422008-11-17 14:58:09 +00004079 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
4080 VD->getIdentifierName());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004081 GlobalVarDecl = 0;
4082
4083 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00004084 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004085 RewriteCastExpr(CE);
4086 }
4087 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004088 return;
4089 }
4090 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
4091 if (isBlockPointerType(TD->getUnderlyingType()))
4092 RewriteBlockPointerDecl(TD);
4093 else if (TD->getUnderlyingType()->isFunctionPointerType())
4094 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4095 return;
4096 }
4097 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
4098 if (RD->isDefinition()) {
4099 for (RecordDecl::field_const_iterator i = RD->field_begin(),
4100 e = RD->field_end(); i != e; ++i) {
4101 FieldDecl *FD = *i;
4102 if (isBlockPointerType(FD->getType()))
4103 RewriteBlockPointerDecl(FD);
4104 }
4105 }
4106 return;
4107 }
4108 // Nothing yet.
4109}
4110
4111void RewriteObjC::HandleTranslationUnit(TranslationUnit& TU) {
4112 // Get the top-level buffer that this corresponds to.
4113
4114 // Rewrite tabs if we care.
4115 //RewriteTabs();
4116
4117 if (Diags.hasErrorOccurred())
4118 return;
4119
4120 // Create the output file.
4121
4122 llvm::OwningPtr<llvm::raw_ostream> OwnedStream;
4123 llvm::raw_ostream *OutFile;
4124 if (OutFileName == "-") {
4125 OutFile = &llvm::outs();
4126 } else if (!OutFileName.empty()) {
4127 std::string Err;
Daniel Dunbar26fb2722008-11-13 05:09:21 +00004128 OutFile = new llvm::raw_fd_ostream(OutFileName.c_str(), false, Err);
Steve Narofffa15fd92008-10-28 20:29:00 +00004129 OwnedStream.reset(OutFile);
4130 } else if (InFileName == "-") {
4131 OutFile = &llvm::outs();
4132 } else {
4133 llvm::sys::Path Path(InFileName);
4134 Path.eraseSuffix();
4135 Path.appendSuffix("cpp");
4136 std::string Err;
Daniel Dunbar26fb2722008-11-13 05:09:21 +00004137 OutFile = new llvm::raw_fd_ostream(Path.toString().c_str(), false, Err);
Steve Narofffa15fd92008-10-28 20:29:00 +00004138 OwnedStream.reset(OutFile);
4139 }
4140
4141 RewriteInclude();
4142
4143 InsertText(SourceLocation::getFileLoc(MainFileID, 0),
4144 Preamble.c_str(), Preamble.size(), false);
4145
Steve Naroff0aab7962008-11-14 14:10:01 +00004146 if (ClassImplementation.size() || CategoryImplementation.size())
4147 RewriteImplementations();
Steve Narofffa15fd92008-10-28 20:29:00 +00004148
4149 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
4150 // we are done.
4151 if (const RewriteBuffer *RewriteBuf =
4152 Rewrite.getRewriteBufferFor(MainFileID)) {
4153 //printf("Changed:\n");
4154 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4155 } else {
4156 fprintf(stderr, "No changes\n");
4157 }
Steve Narofface66252008-11-13 20:07:04 +00004158
Steve Naroff0aab7962008-11-14 14:10:01 +00004159 if (ClassImplementation.size() || CategoryImplementation.size()) {
4160 // Rewrite Objective-c meta data*
4161 std::string ResultStr;
4162 SynthesizeMetaDataIntoBuffer(ResultStr);
4163 // Emit metadata.
4164 *OutFile << ResultStr;
4165 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004166 OutFile->flush();
4167}
4168