blob: 7f55d793d7c73cc237db6006614064a48e8f3f72 [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);
Steve Naroffd40910b2008-12-01 20:33:01 +0000172 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000173 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000174 void RewriteImplementationDecl(NamedDecl *Dcl);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000175 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
176 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
177 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
178 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
179 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Chris Lattner55d13b42008-03-16 21:23:50 +0000180 void RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +0000181 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000182 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroff4f95b752008-07-29 18:15:38 +0000183 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffd5255f52007-11-01 13:24:47 +0000184 bool needToScanForQualifiers(QualType T);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000185 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000186 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000187 QualType getConstantStringStructType();
Steve Naroffbaf58c32008-05-31 14:15:04 +0000188 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Chris Lattner311ff022007-10-16 22:36:42 +0000189
Chris Lattnerf04da132007-10-24 17:06:59 +0000190 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000191 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000192 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000193 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart);
Steve Naroffb42f8412007-11-05 14:50:49 +0000194 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000195 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000196 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000197 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000198 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000199 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000200 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
201 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
202 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000203 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
204 SourceLocation OrigEnd);
Steve Naroff934f2762007-10-24 22:48:43 +0000205 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
206 Expr **args, unsigned nargs);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000207 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000208 Stmt *RewriteBreakStmt(BreakStmt *S);
209 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000210 void SynthCountByEnumWithState(std::string &buf);
211
Steve Naroff09b266e2007-10-30 23:14:51 +0000212 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000213 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000214 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000215 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000216 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000217 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000218 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000219 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000220 void SynthGetProtocolFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000221 void SynthSuperContructorFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000222
Chris Lattnerf04da132007-10-24 17:06:59 +0000223 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000224 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000225 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000226
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000227 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000228 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000229
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000230 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
231 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000232 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000233 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000234 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000235 const char *ClassName,
236 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000237
Chris Lattner780f3292008-07-21 21:32:27 +0000238 void RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl>
239 &Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000240 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000241 const char *ClassName,
242 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000243 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000244 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000245 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
246 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000247 std::string &Result);
Steve Narofface66252008-11-13 20:07:04 +0000248 void RewriteImplementations();
249 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Steve Naroff54055232008-10-27 17:20:55 +0000250
251 // Block rewriting.
252 void RewriteBlocksInFunctionTypeProto(QualType funcType, NamedDecl *D);
253 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
254
255 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
256 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
257
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000258 // Block specific rewrite rules.
Steve Naroff54055232008-10-27 17:20:55 +0000259 void RewriteBlockCall(CallExpr *Exp);
260 void RewriteBlockPointerDecl(NamedDecl *VD);
261 void RewriteBlockDeclRefExpr(BlockDeclRefExpr *VD);
262 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
263
264 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
265 const char *funcName, std::string Tag);
266 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
267 const char *funcName, std::string Tag);
268 std::string SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
269 bool hasCopyDisposeHelpers);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +0000270 Stmt *SynthesizeBlockCall(CallExpr *Exp);
Steve Naroff54055232008-10-27 17:20:55 +0000271 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
272 const char *FunName);
273
274 void CollectBlockDeclRefInfo(BlockExpr *Exp);
275 void GetBlockCallExprs(Stmt *S);
276 void GetBlockDeclRefExprs(Stmt *S);
277
278 // We avoid calling Type::isBlockPointerType(), since it operates on the
279 // canonical type. We only care if the top-level type is a closure pointer.
280 bool isBlockPointerType(QualType T) { return isa<BlockPointerType>(T); }
281
282 // FIXME: This predicate seems like it would be useful to add to ASTContext.
283 bool isObjCType(QualType T) {
284 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
285 return false;
286
287 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
288
289 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
290 OCT == Context->getCanonicalType(Context->getObjCClassType()))
291 return true;
292
293 if (const PointerType *PT = OCT->getAsPointerType()) {
294 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
295 isa<ObjCQualifiedIdType>(PT->getPointeeType()))
296 return true;
297 }
298 return false;
299 }
300 bool PointerTypeTakesAnyBlockArguments(QualType QT);
301 void GetExtentOfArgList(const char *Name, const char *&LParen, const char *&RParen);
Steve Naroffb2f9e512008-11-03 23:29:32 +0000302 void RewriteCastExpr(CStyleCastExpr *CE);
Steve Narofffa15fd92008-10-28 20:29:00 +0000303
304 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000305 Stmt *SynthBlockInitExpr(BlockExpr *Exp);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000306 };
307}
308
Steve Naroff54055232008-10-27 17:20:55 +0000309void RewriteObjC::RewriteBlocksInFunctionTypeProto(QualType funcType,
310 NamedDecl *D) {
311 if (FunctionTypeProto *fproto = dyn_cast<FunctionTypeProto>(funcType)) {
312 for (FunctionTypeProto::arg_type_iterator I = fproto->arg_type_begin(),
313 E = fproto->arg_type_end(); I && (I != E); ++I)
314 if (isBlockPointerType(*I)) {
315 // All the args are checked/rewritten. Don't call twice!
316 RewriteBlockPointerDecl(D);
317 break;
318 }
319 }
320}
321
322void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
323 const PointerType *PT = funcType->getAsPointerType();
324 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
325 RewriteBlocksInFunctionTypeProto(PT->getPointeeType(), ND);
326}
327
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000328static bool IsHeaderFile(const std::string &Filename) {
329 std::string::size_type DotPos = Filename.rfind('.');
330
331 if (DotPos == std::string::npos) {
332 // no file extension
333 return false;
334 }
335
336 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
337 // C header: .h
338 // C++ header: .hh or .H;
339 return Ext == "h" || Ext == "hh" || Ext == "H";
340}
341
Steve Naroffb29b4272008-04-14 22:03:09 +0000342RewriteObjC::RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000343 Diagnostic &D, const LangOptions &LOpts)
344 : Diags(D), LangOpts(LOpts) {
345 IsHeader = IsHeaderFile(inFile);
346 InFileName = inFile;
347 OutFileName = outFile;
348 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
349 "rewriting sub-expression within a macro (may not be correct)");
350}
351
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000352ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
Chris Lattnerc68ab772008-03-22 00:08:40 +0000353 const std::string& OutFile,
Steve Naroff4f943c22008-03-10 20:43:59 +0000354 Diagnostic &Diags,
355 const LangOptions &LOpts) {
Steve Naroffb29b4272008-04-14 22:03:09 +0000356 return new RewriteObjC(InFile, OutFile, Diags, LOpts);
Chris Lattnere365c502007-11-30 22:25:36 +0000357}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000358
Steve Naroffb29b4272008-04-14 22:03:09 +0000359void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000360 Context = &context;
361 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000362 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000363 MsgSendFunctionDecl = 0;
364 MsgSendSuperFunctionDecl = 0;
365 MsgSendStretFunctionDecl = 0;
366 MsgSendSuperStretFunctionDecl = 0;
367 MsgSendFpretFunctionDecl = 0;
368 GetClassFunctionDecl = 0;
369 GetMetaClassFunctionDecl = 0;
370 SelGetUidFunctionDecl = 0;
371 CFStringFunctionDecl = 0;
372 GetProtocolFunctionDecl = 0;
373 ConstantStringClassReference = 0;
374 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000375 CurMethodDef = 0;
376 CurFunctionDef = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000377 SuperStructDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000378 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000379 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000380 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000381 NumObjCStringLiterals = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000382
383 // Get the ID and start/end of the main file.
384 MainFileID = SM->getMainFileID();
385 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
386 MainFileStart = MainBuf->getBufferStart();
387 MainFileEnd = MainBuf->getBufferEnd();
Steve Naroffba92b2e2008-03-27 22:29:16 +0000388
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000389 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000390
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000391 // declaring objc_selector outside the parameter list removes a silly
392 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000393 if (IsHeader)
394 Preamble = "#pragma once\n";
395 Preamble += "struct objc_selector; struct objc_class;\n";
396 Preamble += "#ifndef OBJC_SUPER\n";
397 Preamble += "struct objc_super { struct objc_object *object; ";
398 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000399 if (LangOpts.Microsoft) {
400 // Add a constructor for creating temporary objects.
Steve Naroffba92b2e2008-03-27 22:29:16 +0000401 Preamble += "objc_super(struct objc_object *o, struct objc_object *s) : ";
402 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000403 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000404 Preamble += "};\n";
405 Preamble += "#define OBJC_SUPER\n";
406 Preamble += "#endif\n";
407 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
408 Preamble += "typedef struct objc_object Protocol;\n";
409 Preamble += "#define _REWRITER_typedef_Protocol\n";
410 Preamble += "#endif\n";
Steve Naroff3c64d9e2008-03-12 13:19:12 +0000411 if (LangOpts.Microsoft)
Steve Naroff69c827f2008-05-06 22:45:19 +0000412 Preamble += "#define __OBJC_RW_EXTERN extern \"C\" __declspec(dllimport)\n";
413 else
414 Preamble += "#define __OBJC_RW_EXTERN extern\n";
415 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000416 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000417 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000418 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000419 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000420 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000421 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000422 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff1284db82008-05-08 22:02:18 +0000423 Preamble += "__OBJC_RW_EXTERN double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000424 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff0757612008-05-08 17:52:16 +0000425 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000426 Preamble += "(const char *);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000427 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000428 Preamble += "(const char *);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000429 Preamble += "__OBJC_RW_EXTERN void objc_exception_throw(struct objc_object *);\n";
430 Preamble += "__OBJC_RW_EXTERN void objc_exception_try_enter(void *);\n";
431 Preamble += "__OBJC_RW_EXTERN void objc_exception_try_exit(void *);\n";
432 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_exception_extract(void *);\n";
433 Preamble += "__OBJC_RW_EXTERN int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000434 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000435 // @synchronized hooks.
436 Preamble += "__OBJC_RW_EXTERN void objc_sync_enter(struct objc_object *);\n";
437 Preamble += "__OBJC_RW_EXTERN void objc_sync_exit(struct objc_object *);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000438 Preamble += "__OBJC_RW_EXTERN Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000439 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
440 Preamble += "struct __objcFastEnumerationState {\n\t";
441 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000442 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000443 Preamble += "unsigned long *mutationsPtr;\n\t";
444 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff73ebd6d2008-06-02 20:23:21 +0000445 Preamble += "__OBJC_RW_EXTERN void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000446 Preamble += "#define __FASTENUMERATIONSTATE\n";
447 Preamble += "#endif\n";
448 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
449 Preamble += "struct __NSConstantStringImpl {\n";
450 Preamble += " int *isa;\n";
451 Preamble += " int flags;\n";
452 Preamble += " char *str;\n";
453 Preamble += " long length;\n";
454 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000455 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
456 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
457 Preamble += "#else\n";
Steve Naroff73b17cd2008-05-15 21:12:10 +0000458 Preamble += "__OBJC_RW_EXTERN int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000459 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000460 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
461 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000462 // Blocks preamble.
463 Preamble += "#ifndef BLOCK_IMPL\n";
464 Preamble += "#define BLOCK_IMPL\n";
465 Preamble += "struct __block_impl {\n";
466 Preamble += " void *isa;\n";
467 Preamble += " int Flags;\n";
468 Preamble += " int Size;\n";
469 Preamble += " void *FuncPtr;\n";
470 Preamble += "};\n";
471 Preamble += "enum {\n";
472 Preamble += " BLOCK_HAS_COPY_DISPOSE = (1<<25),\n";
473 Preamble += " BLOCK_IS_GLOBAL = (1<<28)\n";
474 Preamble += "};\n";
Steve Naroff54055232008-10-27 17:20:55 +0000475 Preamble += "// Runtime copy/destroy helper functions\n";
476 Preamble += "__OBJC_RW_EXTERN void _Block_copy_assign(void *, void *);\n";
477 Preamble += "__OBJC_RW_EXTERN void _Block_byref_assign_copy(void *, void *);\n";
478 Preamble += "__OBJC_RW_EXTERN void _Block_destroy(void *);\n";
479 Preamble += "__OBJC_RW_EXTERN void _Block_byref_release(void *);\n";
480 Preamble += "__OBJC_RW_EXTERN void *_NSConcreteGlobalBlock;\n";
481 Preamble += "__OBJC_RW_EXTERN void *_NSConcreteStackBlock;\n";
482 Preamble += "#endif\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000483 if (LangOpts.Microsoft) {
484 Preamble += "#undef __OBJC_RW_EXTERN\n";
485 Preamble += "#define __attribute__(X)\n";
486 }
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000487}
488
489
Chris Lattnerf04da132007-10-24 17:06:59 +0000490//===----------------------------------------------------------------------===//
491// Top Level Driver Code
492//===----------------------------------------------------------------------===//
493
Steve Naroffb29b4272008-04-14 22:03:09 +0000494void RewriteObjC::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000495 // Two cases: either the decl could be in the main file, or it could be in a
496 // #included file. If the former, rewrite it now. If the later, check to see
497 // if we rewrote the #include/#import.
498 SourceLocation Loc = D->getLocation();
499 Loc = SM->getLogicalLoc(Loc);
500
501 // If this is for a builtin, ignore it.
502 if (Loc.isInvalid()) return;
503
Steve Naroffebf2b562007-10-23 23:50:29 +0000504 // Look for built-in declarations that we need to refer during the rewrite.
505 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000506 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000507 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000508 // declared in <Foundation/NSString.h>
Chris Lattner8ec03f52008-11-24 03:54:41 +0000509 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000510 ConstantStringClassReference = FVD;
511 return;
512 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000513 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000514 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000515 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000516 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000517 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000518 RewriteProtocolDecl(PD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000519 } else if (ObjCForwardProtocolDecl *FP =
520 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000521 RewriteForwardProtocolDecl(FP);
Steve Naroffebf2b562007-10-23 23:50:29 +0000522 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000523 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000524 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000525 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000526}
527
Chris Lattnerf04da132007-10-24 17:06:59 +0000528//===----------------------------------------------------------------------===//
529// Syntactic (non-AST) Rewriting Code
530//===----------------------------------------------------------------------===//
531
Steve Naroffb29b4272008-04-14 22:03:09 +0000532void RewriteObjC::RewriteInclude() {
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000533 SourceLocation LocStart = SourceLocation::getFileLoc(MainFileID, 0);
534 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
535 const char *MainBufStart = MainBuf.first;
536 const char *MainBufEnd = MainBuf.second;
537 size_t ImportLen = strlen("import");
538 size_t IncludeLen = strlen("include");
539
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000540 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000541 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
542 if (*BufPtr == '#') {
543 if (++BufPtr == MainBufEnd)
544 return;
545 while (*BufPtr == ' ' || *BufPtr == '\t')
546 if (++BufPtr == MainBufEnd)
547 return;
548 if (!strncmp(BufPtr, "import", ImportLen)) {
549 // replace import with include
550 SourceLocation ImportLoc =
551 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattneraadaf782008-01-31 19:51:04 +0000552 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000553 BufPtr += ImportLen;
554 }
555 }
556 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000557}
558
Steve Naroffb29b4272008-04-14 22:03:09 +0000559void RewriteObjC::RewriteTabs() {
Chris Lattnerf04da132007-10-24 17:06:59 +0000560 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
561 const char *MainBufStart = MainBuf.first;
562 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000563
Chris Lattnerf04da132007-10-24 17:06:59 +0000564 // Loop over the whole file, looking for tabs.
565 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
566 if (*BufPtr != '\t')
567 continue;
568
569 // Okay, we found a tab. This tab will turn into at least one character,
570 // but it depends on which 'virtual column' it is in. Compute that now.
571 unsigned VCol = 0;
572 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
573 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
574 ++VCol;
575
576 // Okay, now that we know the virtual column, we know how many spaces to
577 // insert. We assume 8-character tab-stops.
578 unsigned Spaces = 8-(VCol & 7);
579
580 // Get the location of the tab.
581 SourceLocation TabLoc =
582 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
583
584 // Rewrite the single tab character into a sequence of spaces.
Chris Lattneraadaf782008-01-31 19:51:04 +0000585 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerf04da132007-10-24 17:06:59 +0000586 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000587}
588
Steve Naroffeb0646c2008-12-02 15:48:25 +0000589static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
590 ObjCIvarDecl *OID) {
591 std::string S;
592 S = "((struct ";
593 S += ClassDecl->getIdentifier()->getName();
594 S += "_IMPL *)self)->";
595 S += OID->getNameAsCString();
596 return S;
597}
598
Steve Naroffd40910b2008-12-01 20:33:01 +0000599void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID) {
600 SourceLocation startLoc = PID->getLocStart();
601 InsertText(startLoc, "// ", 3);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000602 const char *startBuf = SM->getCharacterData(startLoc);
603 assert((*startBuf == '@') && "bogus @synthesize location");
604 const char *semiBuf = strchr(startBuf, ';');
605 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
606 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
607
608 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
609 return; // FIXME: is this correct?
610
611 // Generate the 'getter' function.
612 std::string Getr;
613 ObjCPropertyDecl *PD = PID->getPropertyDecl();
614
615 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
616 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
617
618 Getr += "{ ";
619 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
620 if (OID) {
621 // Synthesize an explicit cast to gain access to the ivar.
622 Getr += "return " + getIvarAccessString(ClassDecl, OID);
623 Getr += "; }";
624 }
625 InsertText(onePastSemiLoc, Getr.c_str(), Getr.size());
626
627 if (PD->isReadOnly())
628 return;
629
630 // Generate the 'setter' function.
631 std::string Setr;
632 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
633
634 Setr += "{ ";
635 if (OID) {
636 // Synthesize an explicit cast to initialize the ivar.
637 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
638 Setr += OID->getNameAsCString();
639 Setr += "; }";
640 }
641 InsertText(onePastSemiLoc, Setr.c_str(), Setr.size());
Steve Naroffd40910b2008-12-01 20:33:01 +0000642}
Chris Lattner8a12c272007-10-11 18:38:32 +0000643
Steve Naroffb29b4272008-04-14 22:03:09 +0000644void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000645 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000646 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerf04da132007-10-24 17:06:59 +0000647
648 // Get the start location and compute the semi location.
649 SourceLocation startLoc = ClassDecl->getLocation();
650 const char *startBuf = SM->getCharacterData(startLoc);
651 const char *semiPtr = strchr(startBuf, ';');
652
653 // Translate to typedef's that forward reference structs with the same name
654 // as the class. As a convenience, we include the original declaration
655 // as a comment.
656 std::string typedefString;
657 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000658 typedefString.append(startBuf, semiPtr-startBuf+1);
659 typedefString += "\n";
660 for (int i = 0; i < numDecls; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000661 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000662 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000663 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000664 typedefString += "\n";
665 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000666 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000667 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000668 typedefString += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000669 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000670 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000671 }
672
673 // Replace the @class with typedefs corresponding to the classes.
Chris Lattneraadaf782008-01-31 19:51:04 +0000674 ReplaceText(startLoc, semiPtr-startBuf+1,
675 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000676}
677
Steve Naroffb29b4272008-04-14 22:03:09 +0000678void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000679 SourceLocation LocStart = Method->getLocStart();
680 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000681
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000682 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
Steve Naroff94ac21e2008-10-21 13:37:27 +0000683 InsertText(LocStart, "#if 0\n", 6);
684 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000685 } else {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000686 InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000687 }
688}
689
Steve Naroffb29b4272008-04-14 22:03:09 +0000690void RewriteObjC::RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000691{
Chris Lattner55d13b42008-03-16 21:23:50 +0000692 for (unsigned i = 0; i < nProperties; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000693 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000694 SourceLocation Loc = Property->getLocation();
695
Chris Lattneraadaf782008-01-31 19:51:04 +0000696 ReplaceText(Loc, 0, "// ", 3);
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000697
698 // FIXME: handle properties that are declared across multiple lines.
699 }
700}
701
Steve Naroffb29b4272008-04-14 22:03:09 +0000702void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000703 SourceLocation LocStart = CatDecl->getLocStart();
704
705 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000706 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000707
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000708 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000709 E = CatDecl->instmeth_end(); I != E; ++I)
710 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000711 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000712 E = CatDecl->classmeth_end(); I != E; ++I)
713 RewriteMethodDeclaration(*I);
714
Steve Naroff423cb562007-10-30 13:30:57 +0000715 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000716 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000717}
718
Steve Naroffb29b4272008-04-14 22:03:09 +0000719void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000720 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000721
Steve Naroff752d6ef2007-10-30 16:42:30 +0000722 SourceLocation LocStart = PDecl->getLocStart();
723
724 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000725 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000726
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000727 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000728 E = PDecl->instmeth_end(); I != E; ++I)
729 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000730 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000731 E = PDecl->classmeth_end(); I != E; ++I)
732 RewriteMethodDeclaration(*I);
733
Steve Naroff752d6ef2007-10-30 16:42:30 +0000734 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000735 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattneraadaf782008-01-31 19:51:04 +0000736 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000737
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000738 // Must comment out @optional/@required
739 const char *startBuf = SM->getCharacterData(LocStart);
740 const char *endBuf = SM->getCharacterData(LocEnd);
741 for (const char *p = startBuf; p < endBuf; p++) {
742 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
743 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000744 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000745 ReplaceText(OptionalLoc, strlen("@optional"),
746 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000747
748 }
749 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
750 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000751 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000752 ReplaceText(OptionalLoc, strlen("@required"),
753 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000754
755 }
756 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000757}
758
Steve Naroffb29b4272008-04-14 22:03:09 +0000759void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000760 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000761 if (LocStart.isInvalid())
762 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000763 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000764 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000765}
766
Steve Naroffb29b4272008-04-14 22:03:09 +0000767void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000768 std::string &ResultStr) {
Steve Naroffced80a82008-10-30 12:09:33 +0000769 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroff76e429d2008-07-16 14:40:40 +0000770 const FunctionType *FPRetType = 0;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000771 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000772 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000773 ResultStr += "id";
Steve Naroff76e429d2008-07-16 14:40:40 +0000774 else if (OMD->getResultType()->isFunctionPointerType()) {
775 // needs special handling, since pointer-to-functions have special
776 // syntax (where a decaration models use).
777 QualType retType = OMD->getResultType();
778 if (const PointerType* PT = retType->getAsPointerType()) {
779 QualType PointeeTy = PT->getPointeeType();
780 if ((FPRetType = PointeeTy->getAsFunctionType())) {
781 ResultStr += FPRetType->getResultType().getAsString();
782 ResultStr += "(*";
783 }
784 }
785 } else
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000786 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000787 ResultStr += " ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000788
789 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000790 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000791
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000792 if (OMD->isInstance())
793 NameStr += "_I_";
794 else
795 NameStr += "_C_";
796
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000797 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000798 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000799
800 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000801 if (ObjCCategoryImplDecl *CID =
802 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000803 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000804 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000805 }
Steve Naroff563b8282008-04-04 22:23:44 +0000806 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +0000807 {
808 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000809 int len = selString.size();
810 for (int i = 0; i < len; i++)
811 if (selString[i] == ':')
812 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000813 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000814 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000815 // Remember this name for metadata emission
816 MethodInternalNames[OMD] = NameStr;
817 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000818
819 // Rewrite arguments
820 ResultStr += "(";
821
822 // invisible arguments
823 if (OMD->isInstance()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000824 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000825 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +0000826 if (!LangOpts.Microsoft) {
827 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
828 ResultStr += "struct ";
829 }
830 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000831 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000832 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000833 }
834 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000835 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000836
837 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000838 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000839 ResultStr += " _cmd";
840
841 // Method arguments.
Chris Lattner58cce3b2008-03-16 01:07:14 +0000842 for (unsigned i = 0; i < OMD->getNumParams(); i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000843 ParmVarDecl *PDecl = OMD->getParamDecl(i);
844 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +0000845 if (PDecl->getType()->isObjCQualifiedIdType()) {
846 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000847 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +0000848 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000849 std::string Name = PDecl->getNameAsString();
Steve Naroffc8ad87b2008-10-30 14:45:29 +0000850 if (isBlockPointerType(PDecl->getType())) {
851 // Make sure we convert "t (^)(...)" to "t (*)(...)".
852 const BlockPointerType *BPT = PDecl->getType()->getAsBlockPointerType();
853 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name);
854 } else
855 PDecl->getType().getAsStringInternal(Name);
Steve Naroff543409e2008-04-18 21:13:19 +0000856 ResultStr += Name;
857 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000858 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +0000859 if (OMD->isVariadic())
860 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000861 ResultStr += ") ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000862
Steve Naroff76e429d2008-07-16 14:40:40 +0000863 if (FPRetType) {
864 ResultStr += ")"; // close the precedence "scope" for "*".
865
866 // Now, emit the argument types (if any).
867 if (const FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(FPRetType)) {
868 ResultStr += "(";
869 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
870 if (i) ResultStr += ", ";
871 std::string ParamStr = FT->getArgType(i).getAsString();
872 ResultStr += ParamStr;
873 }
874 if (FT->isVariadic()) {
875 if (FT->getNumArgs()) ResultStr += ", ";
876 ResultStr += "...";
877 }
878 ResultStr += ")";
879 } else {
880 ResultStr += "()";
881 }
882 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000883}
Steve Naroffb29b4272008-04-14 22:03:09 +0000884void RewriteObjC::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000885 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
886 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000887
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000888 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000889 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000890 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000891 InsertText(CID->getLocStart(), "// ", 3);
Steve Narofface66252008-11-13 20:07:04 +0000892
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000893 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000894 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
895 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000896 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000897 ObjCMethodDecl *OMD = *I;
898 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000899 SourceLocation LocStart = OMD->getLocStart();
900 SourceLocation LocEnd = OMD->getBody()->getLocStart();
901
902 const char *startBuf = SM->getCharacterData(LocStart);
903 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000904 ReplaceText(LocStart, endBuf-startBuf,
905 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000906 }
907
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000908 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000909 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
910 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000911 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000912 ObjCMethodDecl *OMD = *I;
913 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000914 SourceLocation LocStart = OMD->getLocStart();
915 SourceLocation LocEnd = OMD->getBody()->getLocStart();
916
917 const char *startBuf = SM->getCharacterData(LocStart);
918 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000919 ReplaceText(LocStart, endBuf-startBuf,
920 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000921 }
Steve Naroffd40910b2008-12-01 20:33:01 +0000922 for (ObjCCategoryImplDecl::propimpl_iterator
923 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
924 E = IMD ? IMD->propimpl_end() : CID->propimpl_end(); I != E; ++I) {
925 RewritePropertyImplDecl(*I);
926 }
927
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000928 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000929 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000930 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000931 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000932}
933
Steve Naroffb29b4272008-04-14 22:03:09 +0000934void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000935 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000936 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000937 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +0000938 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000939 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000940 ResultStr += "\n";
941 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000942 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000943 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000944 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000945 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000946 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000947 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000948 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000949 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000950 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Narofff908a872007-10-30 02:23:23 +0000951
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000952 RewriteProperties(ClassDecl->getNumPropertyDecl(),
953 ClassDecl->getPropertyDecl());
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000954 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000955 E = ClassDecl->instmeth_end(); I != E; ++I)
956 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000957 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000958 E = ClassDecl->classmeth_end(); I != E; ++I)
959 RewriteMethodDeclaration(*I);
960
Steve Naroff2feac5e2007-10-30 03:43:13 +0000961 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000962 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000963}
964
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000965Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
966 SourceLocation OrigStart) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000967 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff54055232008-10-27 17:20:55 +0000968 if (CurMethodDef) {
Steve Naroff05b8c782008-03-12 00:25:36 +0000969 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +0000970 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
971 // lookup which class implements the instance variable.
972 ObjCInterfaceDecl *clsDeclared = 0;
973 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
974 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
975
976 // Synthesize an explicit cast to gain access to the ivar.
977 std::string RecName = clsDeclared->getIdentifier()->getName();
978 RecName += "_IMPL";
979 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000980 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +0000981 SourceLocation(), II);
Steve Narofff0757612008-05-08 17:52:16 +0000982 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
983 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Douglas Gregor6eec8e82008-10-28 15:36:24 +0000984 CastExpr *castExpr = new CStyleCastExpr(castT, IV->getBase(), castT,
Steve Naroffb2f9e512008-11-03 23:29:32 +0000985 SourceLocation(), SourceLocation());
Steve Narofff0757612008-05-08 17:52:16 +0000986 // Don't forget the parens to enforce the proper binding.
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000987 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
988 IV->getBase()->getLocEnd(),
989 castExpr);
Steve Narofff0757612008-05-08 17:52:16 +0000990 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +0000991 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000992 MemberExpr *ME = new MemberExpr(PE, true, D, IV->getLocation(),
993 D->getType());
Steve Narofff0757612008-05-08 17:52:16 +0000994 ReplaceStmt(IV, ME);
995 delete IV;
996 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000997 }
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000998
999 ReplaceStmt(IV->getBase(), PE);
1000 // Cannot delete IV->getBase(), since PE points to it.
1001 // Replace the old base with the cast. This is important when doing
1002 // embedded rewrites. For example, [newInv->_container addObject:0].
1003 IV->setBase(PE);
1004 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001005 }
Steve Naroff84472a82008-04-18 21:55:08 +00001006 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001007 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
1008
1009 // Explicit ivar refs need to have a cast inserted.
1010 // FIXME: consider sharing some of this code with the code above.
1011 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +00001012 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001013 // lookup which class implements the instance variable.
1014 ObjCInterfaceDecl *clsDeclared = 0;
Steve Narofff0757612008-05-08 17:52:16 +00001015 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001016 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1017
1018 // Synthesize an explicit cast to gain access to the ivar.
1019 std::string RecName = clsDeclared->getIdentifier()->getName();
1020 RecName += "_IMPL";
1021 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001022 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001023 SourceLocation(), II);
Steve Naroff9f525972008-05-06 23:20:07 +00001024 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1025 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001026 CastExpr *castExpr = new CStyleCastExpr(castT, IV->getBase(), castT,
Steve Naroffb2f9e512008-11-03 23:29:32 +00001027 SourceLocation(), SourceLocation());
Steve Naroff9f525972008-05-06 23:20:07 +00001028 // Don't forget the parens to enforce the proper binding.
Chris Lattner8d366162008-05-28 16:38:23 +00001029 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
1030 IV->getBase()->getLocEnd(), castExpr);
Steve Naroff9f525972008-05-06 23:20:07 +00001031 ReplaceStmt(IV->getBase(), PE);
1032 // Cannot delete IV->getBase(), since PE points to it.
1033 // Replace the old base with the cast. This is important when doing
1034 // embedded rewrites. For example, [newInv->_container addObject:0].
1035 IV->setBase(PE);
1036 return IV;
1037 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001038 }
Steve Naroff84472a82008-04-18 21:55:08 +00001039 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +00001040}
1041
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001042/// SynthCountByEnumWithState - To print:
1043/// ((unsigned int (*)
1044/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1045/// (void *)objc_msgSend)((id)l_collection,
1046/// sel_registerName(
1047/// "countByEnumeratingWithState:objects:count:"),
1048/// &enumState,
1049/// (id *)items, (unsigned int)16)
1050///
Steve Naroffb29b4272008-04-14 22:03:09 +00001051void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001052 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1053 "id *, unsigned int))(void *)objc_msgSend)";
1054 buf += "\n\t\t";
1055 buf += "((id)l_collection,\n\t\t";
1056 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1057 buf += "\n\t\t";
1058 buf += "&enumState, "
1059 "(id *)items, (unsigned int)16)";
1060}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001061
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001062/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1063/// statement to exit to its outer synthesized loop.
1064///
Steve Naroffb29b4272008-04-14 22:03:09 +00001065Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001066 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1067 return S;
1068 // replace break with goto __break_label
1069 std::string buf;
1070
1071 SourceLocation startLoc = S->getLocStart();
1072 buf = "goto __break_label_";
1073 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001074 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001075
1076 return 0;
1077}
1078
1079/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1080/// statement to continue with its inner synthesized loop.
1081///
Steve Naroffb29b4272008-04-14 22:03:09 +00001082Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001083 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1084 return S;
1085 // replace continue with goto __continue_label
1086 std::string buf;
1087
1088 SourceLocation startLoc = S->getLocStart();
1089 buf = "goto __continue_label_";
1090 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001091 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001092
1093 return 0;
1094}
1095
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001096/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001097/// It rewrites:
1098/// for ( type elem in collection) { stmts; }
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001099
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001100/// Into:
1101/// {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001102/// type elem;
1103/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001104/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001105/// id l_collection = (id)collection;
1106/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1107/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001108/// if (limit) {
1109/// unsigned long startMutations = *enumState.mutationsPtr;
1110/// do {
1111/// unsigned long counter = 0;
1112/// do {
1113/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001114/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001115/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001116/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001117/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001118/// } while (counter < limit);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001119/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1120/// objects:items count:16]);
1121/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001122/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001123/// }
1124/// else
1125/// elem = nil;
1126/// }
1127///
Steve Naroffb29b4272008-04-14 22:03:09 +00001128Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001129 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001130 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1131 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1132 "ObjCForCollectionStmt Statement stack mismatch");
1133 assert(!ObjCBcLabelNo.empty() &&
1134 "ObjCForCollectionStmt - Label No stack empty");
1135
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001136 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001137 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001138 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001139 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001140 std::string buf;
1141 buf = "\n{\n\t";
1142 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1143 // type elem;
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001144 ScopedDecl* D = DS->getSolitaryDecl();
1145 QualType ElementType = cast<ValueDecl>(D)->getType();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001146 elementTypeAsString = ElementType.getAsString();
1147 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001148 buf += " ";
Chris Lattner8ec03f52008-11-24 03:54:41 +00001149 elementName = D->getNameAsCString();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001150 buf += elementName;
1151 buf += ";\n\t";
1152 }
Chris Lattner06767512008-04-08 05:52:18 +00001153 else {
1154 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner8ec03f52008-11-24 03:54:41 +00001155 elementName = DR->getDecl()->getNameAsCString();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001156 elementTypeAsString
1157 = cast<ValueDecl>(DR->getDecl())->getType().getAsString();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001158 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001159
1160 // struct __objcFastEnumerationState enumState = { 0 };
1161 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1162 // id items[16];
1163 buf += "id items[16];\n\t";
1164 // id l_collection = (id)
1165 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001166 // Find start location of 'collection' the hard way!
1167 const char *startCollectionBuf = startBuf;
1168 startCollectionBuf += 3; // skip 'for'
1169 startCollectionBuf = strchr(startCollectionBuf, '(');
1170 startCollectionBuf++; // skip '('
1171 // find 'in' and skip it.
1172 while (*startCollectionBuf != ' ' ||
1173 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1174 (*(startCollectionBuf+3) != ' ' &&
1175 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1176 startCollectionBuf++;
1177 startCollectionBuf += 3;
1178
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001179 // Replace: "for (type element in" with string constructed thus far.
Chris Lattneraadaf782008-01-31 19:51:04 +00001180 ReplaceText(startLoc, startCollectionBuf - startBuf,
1181 buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001182 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001183 SourceLocation rightParenLoc = S->getRParenLoc();
1184 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1185 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001186 buf = ";\n\t";
1187
1188 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1189 // objects:items count:16];
1190 // which is synthesized into:
1191 // unsigned int limit =
1192 // ((unsigned int (*)
1193 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1194 // (void *)objc_msgSend)((id)l_collection,
1195 // sel_registerName(
1196 // "countByEnumeratingWithState:objects:count:"),
1197 // (struct __objcFastEnumerationState *)&state,
1198 // (id *)items, (unsigned int)16);
1199 buf += "unsigned long limit =\n\t\t";
1200 SynthCountByEnumWithState(buf);
1201 buf += ";\n\t";
1202 /// if (limit) {
1203 /// unsigned long startMutations = *enumState.mutationsPtr;
1204 /// do {
1205 /// unsigned long counter = 0;
1206 /// do {
1207 /// if (startMutations != *enumState.mutationsPtr)
1208 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001209 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001210 buf += "if (limit) {\n\t";
1211 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1212 buf += "do {\n\t\t";
1213 buf += "unsigned long counter = 0;\n\t\t";
1214 buf += "do {\n\t\t\t";
1215 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1216 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1217 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001218 buf += " = (";
1219 buf += elementTypeAsString;
1220 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001221 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattneraadaf782008-01-31 19:51:04 +00001222 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001223
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001224 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001225 /// } while (counter < limit);
1226 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1227 /// objects:items count:16]);
1228 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001229 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001230 /// }
1231 /// else
1232 /// elem = nil;
1233 /// }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001234 ///
1235 buf = ";\n\t";
1236 buf += "__continue_label_";
1237 buf += utostr(ObjCBcLabelNo.back());
1238 buf += ": ;";
1239 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001240 buf += "} while (counter < limit);\n\t";
1241 buf += "} while (limit = ";
1242 SynthCountByEnumWithState(buf);
1243 buf += ");\n\t";
1244 buf += elementName;
1245 buf += " = nil;\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001246 buf += "__break_label_";
1247 buf += utostr(ObjCBcLabelNo.back());
1248 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001249 buf += "}\n\t";
1250 buf += "else\n\t\t";
1251 buf += elementName;
1252 buf += " = nil;\n";
1253 buf += "}\n";
Steve Naroff600e4e82008-07-21 18:26:02 +00001254
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001255 // Insert all these *after* the statement body.
Steve Naroff600e4e82008-07-21 18:26:02 +00001256 if (isa<CompoundStmt>(S->getBody())) {
1257 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1258 InsertText(endBodyLoc, buf.c_str(), buf.size());
1259 } else {
1260 /* Need to treat single statements specially. For example:
1261 *
1262 * for (A *a in b) if (stuff()) break;
1263 * for (A *a in b) xxxyy;
1264 *
1265 * The following code simply scans ahead to the semi to find the actual end.
1266 */
1267 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1268 const char *semiBuf = strchr(stmtBuf, ';');
1269 assert(semiBuf && "Can't find ';'");
1270 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1271 InsertText(endBodyLoc, buf.c_str(), buf.size());
1272 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001273 Stmts.pop_back();
1274 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001275 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001276}
1277
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001278/// RewriteObjCSynchronizedStmt -
1279/// This routine rewrites @synchronized(expr) stmt;
1280/// into:
1281/// objc_sync_enter(expr);
1282/// @try stmt @finally { objc_sync_exit(expr); }
1283///
Steve Naroffb29b4272008-04-14 22:03:09 +00001284Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001285 // Get the start location and compute the semi location.
1286 SourceLocation startLoc = S->getLocStart();
1287 const char *startBuf = SM->getCharacterData(startLoc);
1288
1289 assert((*startBuf == '@') && "bogus @synchronized location");
1290
1291 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001292 buf = "objc_sync_enter((id)";
1293 const char *lparenBuf = startBuf;
1294 while (*lparenBuf != '(') lparenBuf++;
1295 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Steve Naroffc7089f12008-08-19 13:04:19 +00001296 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1297 // the sync expression is typically a message expression that's already
1298 // been rewritten! (which implies the SourceLocation's are invalid).
1299 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001300 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001301 while (*endBuf != ')') endBuf--;
1302 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001303 buf = ");\n";
1304 // declare a new scope with two variables, _stack and _rethrow.
1305 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1306 buf += "int buf[18/*32-bit i386*/];\n";
1307 buf += "char *pointers[4];} _stack;\n";
1308 buf += "id volatile _rethrow = 0;\n";
1309 buf += "objc_exception_try_enter(&_stack);\n";
1310 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00001311 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001312 startLoc = S->getSynchBody()->getLocEnd();
1313 startBuf = SM->getCharacterData(startLoc);
1314
Steve Naroffc7089f12008-08-19 13:04:19 +00001315 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001316 SourceLocation lastCurlyLoc = startLoc;
1317 buf = "}\nelse {\n";
1318 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1319 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb2a39452008-07-16 19:47:39 +00001320 buf += " objc_sync_exit(";
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001321 Expr *syncExpr = new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00001322 S->getSynchExpr(),
1323 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00001324 SourceLocation(), SourceLocation());
Ted Kremeneka95d3752008-09-13 05:16:45 +00001325 std::string syncExprBufS;
1326 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Steve Naroff3498cc92008-08-21 13:03:03 +00001327 syncExpr->printPretty(syncExprBuf);
Steve Naroffb2a39452008-07-16 19:47:39 +00001328 buf += syncExprBuf.str();
1329 buf += ");\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001330 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1331 buf += "}\n";
1332 buf += "}";
1333
Chris Lattneraadaf782008-01-31 19:51:04 +00001334 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001335 return 0;
1336}
1337
Steve Naroffb29b4272008-04-14 22:03:09 +00001338Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001339 // Get the start location and compute the semi location.
1340 SourceLocation startLoc = S->getLocStart();
1341 const char *startBuf = SM->getCharacterData(startLoc);
1342
1343 assert((*startBuf == '@') && "bogus @try location");
1344
1345 std::string buf;
1346 // declare a new scope with two variables, _stack and _rethrow.
1347 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1348 buf += "int buf[18/*32-bit i386*/];\n";
1349 buf += "char *pointers[4];} _stack;\n";
1350 buf += "id volatile _rethrow = 0;\n";
1351 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001352 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001353
Chris Lattneraadaf782008-01-31 19:51:04 +00001354 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001355
1356 startLoc = S->getTryBody()->getLocEnd();
1357 startBuf = SM->getCharacterData(startLoc);
1358
1359 assert((*startBuf == '}') && "bogus @try block");
Steve Naroffc9ba1722008-07-16 15:31:30 +00001360
Steve Naroff75730982007-11-07 04:08:17 +00001361 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffc9ba1722008-07-16 15:31:30 +00001362 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1363 if (catchList) {
1364 startLoc = startLoc.getFileLocWithOffset(1);
1365 buf = " /* @catch begin */ else {\n";
1366 buf += " id _caught = objc_exception_extract(&_stack);\n";
1367 buf += " objc_exception_try_enter (&_stack);\n";
1368 buf += " if (_setjmp(_stack.buf))\n";
1369 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1370 buf += " else { /* @catch continue */";
1371
1372 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001373 } else { /* no catch list */
1374 buf = "}\nelse {\n";
1375 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1376 buf += "}";
1377 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffc9ba1722008-07-16 15:31:30 +00001378 }
Steve Naroff75730982007-11-07 04:08:17 +00001379 bool sawIdTypedCatch = false;
1380 Stmt *lastCatchBody = 0;
Steve Naroff75730982007-11-07 04:08:17 +00001381 while (catchList) {
1382 Stmt *catchStmt = catchList->getCatchParamStmt();
1383
1384 if (catchList == S->getCatchStmts())
1385 buf = "if ("; // we are generating code for the first catch clause
1386 else
1387 buf = "else if (";
1388 startLoc = catchList->getLocStart();
1389 startBuf = SM->getCharacterData(startLoc);
1390
1391 assert((*startBuf == '@') && "bogus @catch location");
1392
1393 const char *lParenLoc = strchr(startBuf, '(');
1394
Steve Naroffbe4b3332008-02-01 22:08:12 +00001395 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001396 // Now rewrite the body...
1397 lastCatchBody = catchList->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001398 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1399 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner06767512008-04-08 05:52:18 +00001400 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1401 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001402 assert((*bodyBuf == '{') && "bogus @catch body location");
1403
1404 buf += "1) { id _tmp = _caught;";
1405 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1406 buf.c_str(), buf.size());
1407 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Ted Kremenek50a25e22008-10-06 22:39:38 +00001408 QualType t = dyn_cast<ValueDecl>(declStmt->getSolitaryDecl())->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001409 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001410 buf += "1) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001411 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001412 sawIdTypedCatch = true;
1413 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001414 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroff75730982007-11-07 04:08:17 +00001415
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001416 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001417 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001418 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001419 buf += cls->getDecl()->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001420 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001421 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001422 }
1423 }
1424 // Now rewrite the body...
1425 lastCatchBody = catchList->getCatchBody();
1426 SourceLocation rParenLoc = catchList->getRParenLoc();
1427 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1428 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1429 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1430 assert((*rParenBuf == ')') && "bogus @catch paren location");
1431 assert((*bodyBuf == '{') && "bogus @catch body location");
1432
1433 buf = " = _caught;";
1434 // Here we replace ") {" with "= _caught;" (which initializes and
1435 // declares the @catch parameter).
Chris Lattneraadaf782008-01-31 19:51:04 +00001436 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001437 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001438 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001439 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001440 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001441 catchList = catchList->getNextCatchStmt();
1442 }
1443 // Complete the catch list...
1444 if (lastCatchBody) {
1445 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001446 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1447 "bogus @catch body location");
Steve Naroff75730982007-11-07 04:08:17 +00001448
Steve Naroff378f47a2008-09-11 15:29:03 +00001449 // Insert the last (implicit) else clause *before* the right curly brace.
1450 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1451 buf = "} /* last catch end */\n";
1452 buf += "else {\n";
1453 buf += " _rethrow = _caught;\n";
1454 buf += " objc_exception_try_exit(&_stack);\n";
1455 buf += "} } /* @catch end */\n";
1456 if (!S->getFinallyStmt())
1457 buf += "}\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001458 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001459
1460 // Set lastCurlyLoc
1461 lastCurlyLoc = lastCatchBody->getLocEnd();
1462 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001463 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001464 startLoc = finalStmt->getLocStart();
1465 startBuf = SM->getCharacterData(startLoc);
1466 assert((*startBuf == '@') && "bogus @finally start");
1467
1468 buf = "/* @finally */";
Chris Lattneraadaf782008-01-31 19:51:04 +00001469 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001470
1471 Stmt *body = finalStmt->getFinallyBody();
1472 SourceLocation startLoc = body->getLocStart();
1473 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001474 assert(*SM->getCharacterData(startLoc) == '{' &&
1475 "bogus @finally body location");
1476 assert(*SM->getCharacterData(endLoc) == '}' &&
1477 "bogus @finally body location");
Steve Naroff75730982007-11-07 04:08:17 +00001478
1479 startLoc = startLoc.getFileLocWithOffset(1);
1480 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001481 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001482 endLoc = endLoc.getFileLocWithOffset(-1);
1483 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001484 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001485
1486 // Set lastCurlyLoc
1487 lastCurlyLoc = body->getLocEnd();
Steve Naroff378f47a2008-09-11 15:29:03 +00001488 } else { /* no finally clause - make sure we synthesize an implicit one */
1489 buf = "{ /* implicit finally clause */\n";
1490 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1491 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1492 buf += "}";
1493 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001494 }
1495 // Now emit the final closing curly brace...
1496 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1497 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001498 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001499 return 0;
1500}
1501
Steve Naroffb29b4272008-04-14 22:03:09 +00001502Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001503 return 0;
1504}
1505
Steve Naroffb29b4272008-04-14 22:03:09 +00001506Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001507 return 0;
1508}
1509
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001510// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff2bd03922007-11-07 15:32:26 +00001511// the throw expression is typically a message expression that's already
1512// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001513Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001514 // Get the start location and compute the semi location.
1515 SourceLocation startLoc = S->getLocStart();
1516 const char *startBuf = SM->getCharacterData(startLoc);
1517
1518 assert((*startBuf == '@') && "bogus @throw location");
1519
1520 std::string buf;
1521 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001522 if (S->getThrowExpr())
1523 buf = "objc_exception_throw(";
1524 else // add an implicit argument
1525 buf = "objc_exception_throw(_caught";
Steve Naroff4ba0acb2008-07-25 15:41:30 +00001526
1527 // handle "@ throw" correctly.
1528 const char *wBuf = strchr(startBuf, 'w');
1529 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1530 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
1531
Steve Naroff2bd03922007-11-07 15:32:26 +00001532 const char *semiBuf = strchr(startBuf, ';');
1533 assert((*semiBuf == ';') && "@throw: can't find ';'");
1534 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1535 buf = ");";
Chris Lattneraadaf782008-01-31 19:51:04 +00001536 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001537 return 0;
1538}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001539
Steve Naroffb29b4272008-04-14 22:03:09 +00001540Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001541 // Create a new string expression.
1542 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001543 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001544 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001545 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1546 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +00001547 SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001548 ReplaceStmt(Exp, Replacement);
Chris Lattnere365c502007-11-30 22:25:36 +00001549
Chris Lattner07506182007-11-30 22:53:43 +00001550 // Replace this subexpr in the parent.
Chris Lattnere64b7772007-10-24 16:57:36 +00001551 delete Exp;
1552 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001553}
1554
Steve Naroffb29b4272008-04-14 22:03:09 +00001555Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroffb42f8412007-11-05 14:50:49 +00001556 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1557 // Create a call to sel_registerName("selName").
1558 llvm::SmallVector<Expr*, 8> SelExprs;
1559 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner077bf5e2008-11-24 03:33:13 +00001560 SelExprs.push_back(new StringLiteral(Exp->getSelector().getAsString().c_str(),
1561 Exp->getSelector().getAsString().size(),
Steve Naroffb42f8412007-11-05 14:50:49 +00001562 false, argType, SourceLocation(),
1563 SourceLocation()));
1564 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1565 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001566 ReplaceStmt(Exp, SelExp);
Steve Naroffb42f8412007-11-05 14:50:49 +00001567 delete Exp;
1568 return SelExp;
1569}
1570
Steve Naroffb29b4272008-04-14 22:03:09 +00001571CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff934f2762007-10-24 22:48:43 +00001572 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001573 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001574 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +00001575
1576 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +00001577 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +00001578
1579 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001580 QualType pToFunc = Context->getPointerType(msgSendType);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001581 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE,
1582 /*isLvalue=*/false);
Steve Naroffebf2b562007-10-23 23:50:29 +00001583
1584 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +00001585
Steve Naroff934f2762007-10-24 22:48:43 +00001586 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1587}
1588
Steve Naroffd5255f52007-11-01 13:24:47 +00001589static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1590 const char *&startRef, const char *&endRef) {
1591 while (startBuf < endBuf) {
1592 if (*startBuf == '<')
1593 startRef = startBuf; // mark the start.
1594 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001595 if (startRef && *startRef == '<') {
1596 endRef = startBuf; // mark the end.
1597 return true;
1598 }
1599 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001600 }
1601 startBuf++;
1602 }
1603 return false;
1604}
1605
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001606static void scanToNextArgument(const char *&argRef) {
1607 int angle = 0;
1608 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1609 if (*argRef == '<')
1610 angle++;
1611 else if (*argRef == '>')
1612 angle--;
1613 argRef++;
1614 }
1615 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1616}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001617
Steve Naroffb29b4272008-04-14 22:03:09 +00001618bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001619
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001620 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001621 return true;
1622
Steve Naroffd5255f52007-11-01 13:24:47 +00001623 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +00001624 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001625 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff9165ad32007-10-31 04:38:33 +00001626 return true; // we have "Class <Protocol> *".
1627 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001628 return false;
1629}
1630
Steve Naroff4f95b752008-07-29 18:15:38 +00001631void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1632 QualType Type = E->getType();
1633 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00001634 SourceLocation Loc, EndLoc;
1635
1636 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
1637 Loc = ECE->getLParenLoc();
1638 EndLoc = ECE->getRParenLoc();
1639 } else {
1640 Loc = E->getLocStart();
1641 EndLoc = E->getLocEnd();
1642 }
1643 // This will defend against trying to rewrite synthesized expressions.
1644 if (Loc.isInvalid() || EndLoc.isInvalid())
1645 return;
1646
Steve Naroff4f95b752008-07-29 18:15:38 +00001647 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00001648 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00001649 const char *startRef = 0, *endRef = 0;
1650 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1651 // Get the locations of the startRef, endRef.
1652 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1653 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1654 // Comment out the protocol references.
1655 InsertText(LessLoc, "/*", 2);
1656 InsertText(GreaterLoc, "*/", 2);
1657 }
1658 }
1659}
1660
Steve Naroffb29b4272008-04-14 22:03:09 +00001661void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001662 SourceLocation Loc;
1663 QualType Type;
1664 const FunctionTypeProto *proto = 0;
1665 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1666 Loc = VD->getLocation();
1667 Type = VD->getType();
1668 }
1669 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1670 Loc = FD->getLocation();
1671 // Check for ObjC 'id' and class types that have been adorned with protocol
1672 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1673 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1674 assert(funcType && "missing function type");
1675 proto = dyn_cast<FunctionTypeProto>(funcType);
1676 if (!proto)
1677 return;
1678 Type = proto->getResultType();
1679 }
1680 else
1681 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001682
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001683 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001684 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001685
1686 const char *endBuf = SM->getCharacterData(Loc);
1687 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00001688 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001689 startBuf--; // scan backward (from the decl location) for return type.
1690 const char *startRef = 0, *endRef = 0;
1691 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1692 // Get the locations of the startRef, endRef.
1693 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1694 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1695 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001696 InsertText(LessLoc, "/*", 2);
1697 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001698 }
1699 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001700 if (!proto)
1701 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001702 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001703 const char *startBuf = SM->getCharacterData(Loc);
1704 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001705 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1706 if (needToScanForQualifiers(proto->getArgType(i))) {
1707 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001708
Steve Naroffd5255f52007-11-01 13:24:47 +00001709 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001710 // scan forward (from the decl location) for argument types.
1711 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001712 const char *startRef = 0, *endRef = 0;
1713 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1714 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001715 SourceLocation LessLoc =
1716 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1717 SourceLocation GreaterLoc =
1718 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001719 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001720 InsertText(LessLoc, "/*", 2);
1721 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001722 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001723 startBuf = ++endBuf;
1724 }
1725 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00001726 // If the function name is derived from a macro expansion, then the
1727 // argument buffer will not follow the name. Need to speak with Chris.
1728 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001729 startBuf++; // scan forward (from the decl location) for argument types.
1730 startBuf++;
1731 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001732 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001733}
1734
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001735// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00001736void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001737 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1738 llvm::SmallVector<QualType, 16> ArgTys;
1739 ArgTys.push_back(Context->getPointerType(
1740 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001741 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001742 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001743 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001744 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001745 SourceLocation(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001746 SelGetUidIdent, getFuncType,
1747 FunctionDecl::Extern, false, 0);
1748}
1749
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001750// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
Steve Naroffb29b4272008-04-14 22:03:09 +00001751void RewriteObjC::SynthGetProtocolFunctionDecl() {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001752 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1753 llvm::SmallVector<QualType, 16> ArgTys;
1754 ArgTys.push_back(Context->getPointerType(
1755 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001756 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001757 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001758 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001759 GetProtocolFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001760 SourceLocation(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001761 SelGetProtoIdent, getFuncType,
1762 FunctionDecl::Extern, false, 0);
1763}
1764
Steve Naroffb29b4272008-04-14 22:03:09 +00001765void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001766 // declared in <objc/objc.h>
Chris Lattner8ec03f52008-11-24 03:54:41 +00001767 if (strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001768 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001769 return;
1770 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001771 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001772}
1773
Steve Naroffc0a123c2008-03-11 17:37:02 +00001774// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00001775void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00001776 if (SuperContructorFunctionDecl)
1777 return;
1778 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_super");
1779 llvm::SmallVector<QualType, 16> ArgTys;
1780 QualType argT = Context->getObjCIdType();
1781 assert(!argT.isNull() && "Can't find 'id' type");
1782 ArgTys.push_back(argT);
1783 ArgTys.push_back(argT);
1784 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1785 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001786 false, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001787 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001788 SourceLocation(),
Steve Naroffc0a123c2008-03-11 17:37:02 +00001789 msgSendIdent, msgSendType,
1790 FunctionDecl::Extern, false, 0);
1791}
1792
Steve Naroff09b266e2007-10-30 23:14:51 +00001793// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001794void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00001795 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1796 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001797 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001798 assert(!argT.isNull() && "Can't find 'id' type");
1799 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001800 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001801 assert(!argT.isNull() && "Can't find 'SEL' type");
1802 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001803 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001804 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001805 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001806 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001807 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001808 msgSendIdent, msgSendType,
1809 FunctionDecl::Extern, false, 0);
1810}
1811
Steve Naroff874e2322007-11-15 10:28:18 +00001812// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001813void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00001814 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1815 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001816 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001817 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00001818 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00001819 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1820 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1821 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001822 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00001823 assert(!argT.isNull() && "Can't find 'SEL' type");
1824 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001825 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00001826 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001827 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001828 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001829 SourceLocation(),
Steve Naroff874e2322007-11-15 10:28:18 +00001830 msgSendIdent, msgSendType,
1831 FunctionDecl::Extern, false, 0);
1832}
1833
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001834// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001835void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001836 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1837 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001838 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001839 assert(!argT.isNull() && "Can't find 'id' type");
1840 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001841 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001842 assert(!argT.isNull() && "Can't find 'SEL' type");
1843 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001844 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001845 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001846 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001847 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001848 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001849 msgSendIdent, msgSendType,
1850 FunctionDecl::Extern, false, 0);
1851}
1852
1853// SynthMsgSendSuperStretFunctionDecl -
1854// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001855void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001856 IdentifierInfo *msgSendIdent =
1857 &Context->Idents.get("objc_msgSendSuper_stret");
1858 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001859 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001860 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00001861 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001862 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1863 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1864 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001865 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001866 assert(!argT.isNull() && "Can't find 'SEL' type");
1867 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001868 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001869 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001870 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001871 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnera98e58d2008-03-15 21:24:04 +00001872 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001873 msgSendIdent, msgSendType,
1874 FunctionDecl::Extern, false, 0);
1875}
1876
Steve Naroff1284db82008-05-08 22:02:18 +00001877// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001878void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001879 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1880 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001881 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001882 assert(!argT.isNull() && "Can't find 'id' type");
1883 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001884 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001885 assert(!argT.isNull() && "Can't find 'SEL' type");
1886 ArgTys.push_back(argT);
Steve Naroff1284db82008-05-08 22:02:18 +00001887 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001888 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001889 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001890 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001891 SourceLocation(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001892 msgSendIdent, msgSendType,
1893 FunctionDecl::Extern, false, 0);
1894}
1895
Steve Naroff09b266e2007-10-30 23:14:51 +00001896// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00001897void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00001898 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1899 llvm::SmallVector<QualType, 16> ArgTys;
1900 ArgTys.push_back(Context->getPointerType(
1901 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001902 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001903 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001904 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001905 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001906 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001907 getClassIdent, getClassType,
1908 FunctionDecl::Extern, false, 0);
1909}
1910
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001911// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00001912void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001913 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1914 llvm::SmallVector<QualType, 16> ArgTys;
1915 ArgTys.push_back(Context->getPointerType(
1916 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001917 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001918 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001919 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001920 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001921 SourceLocation(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001922 getClassIdent, getClassType,
1923 FunctionDecl::Extern, false, 0);
1924}
1925
Steve Naroffb29b4272008-04-14 22:03:09 +00001926Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001927 QualType strType = getConstantStringStructType();
1928
1929 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00001930
1931 std::string tmpName = InFileName;
1932 unsigned i;
1933 for (i=0; i < tmpName.length(); i++) {
1934 char c = tmpName.at(i);
1935 // replace any non alphanumeric characters with '_'.
1936 if (!isalpha(c) && (c < '0' || c > '9'))
1937 tmpName[i] = '_';
1938 }
1939 S += tmpName;
1940 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001941 S += utostr(NumObjCStringLiterals++);
1942
Steve Naroffba92b2e2008-03-27 22:29:16 +00001943 Preamble += "static __NSConstantStringImpl " + S;
1944 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
1945 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001946 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00001947 std::string prettyBufS;
1948 llvm::raw_string_ostream prettyBuf(prettyBufS);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001949 Exp->getString()->printPretty(prettyBuf);
Steve Naroffba92b2e2008-03-27 22:29:16 +00001950 Preamble += prettyBuf.str();
1951 Preamble += ",";
Steve Naroff3652c2d2008-03-15 01:36:04 +00001952 // The minus 2 removes the begin/end double quotes.
Steve Naroffba92b2e2008-03-27 22:29:16 +00001953 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001954
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001955 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Steve Naroff248a7532008-04-15 22:42:06 +00001956 &Context->Idents.get(S.c_str()), strType,
1957 VarDecl::Static, NULL);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00001958 DeclRefExpr *DRE = new DeclRefExpr(NewVD, strType, SourceLocation());
1959 Expr *Unop = new UnaryOperator(DRE, UnaryOperator::AddrOf,
1960 Context->getPointerType(DRE->getType()),
1961 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00001962 // cast to NSConstantString *
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001963 CastExpr *cast = new CStyleCastExpr(Exp->getType(), Unop,
Steve Naroffb2f9e512008-11-03 23:29:32 +00001964 Exp->getType(), SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001965 ReplaceStmt(Exp, cast);
Steve Naroff96984642007-11-08 14:30:50 +00001966 delete Exp;
1967 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00001968}
1969
Steve Naroffb29b4272008-04-14 22:03:09 +00001970ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001971 // check if we are sending a message to 'super'
Steve Naroff54055232008-10-27 17:20:55 +00001972 if (!CurMethodDef || !CurMethodDef->isInstance()) return 0;
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001973
Douglas Gregorcd9b46e2008-11-04 14:56:14 +00001974 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
1975 const PointerType *PT = Super->getType()->getAsPointerType();
Chris Lattner0d17f6f2008-06-21 18:04:54 +00001976 assert(PT);
1977 ObjCInterfaceType *IT = cast<ObjCInterfaceType>(PT->getPointeeType());
1978 return IT->getDecl();
1979 }
1980 return 0;
Steve Naroff874e2322007-11-15 10:28:18 +00001981}
1982
1983// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00001984QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00001985 if (!SuperStructDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001986 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00001987 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00001988 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00001989 QualType FieldTypes[2];
1990
1991 // struct objc_object *receiver;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001992 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00001993 // struct objc_class *super;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001994 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff874e2322007-11-15 10:28:18 +00001995 // Create fields
1996 FieldDecl *FieldDecls[2];
1997
1998 for (unsigned i = 0; i < 2; ++i)
Chris Lattnerb048c982008-04-06 04:47:34 +00001999 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00002000 FieldTypes[i]);
Steve Naroff874e2322007-11-15 10:28:18 +00002001
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002002 SuperStructDecl->defineBody(*Context, FieldDecls, 4);
Steve Naroff874e2322007-11-15 10:28:18 +00002003 }
2004 return Context->getTagDeclType(SuperStructDecl);
2005}
2006
Steve Naroffb29b4272008-04-14 22:03:09 +00002007QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002008 if (!ConstantStringDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002009 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002010 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002011 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002012 QualType FieldTypes[4];
2013
2014 // struct objc_object *receiver;
2015 FieldTypes[0] = Context->getObjCIdType();
2016 // int flags;
2017 FieldTypes[1] = Context->IntTy;
2018 // char *str;
2019 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2020 // long length;
2021 FieldTypes[3] = Context->LongTy;
2022 // Create fields
Steve Naroff9630ec52008-03-27 22:59:54 +00002023 FieldDecl *FieldDecls[4];
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002024
2025 for (unsigned i = 0; i < 4; ++i)
Chris Lattnerb048c982008-04-06 04:47:34 +00002026 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00002027 FieldTypes[i]);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002028
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002029 ConstantStringDecl->defineBody(*Context, FieldDecls, 4);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002030 }
2031 return Context->getTagDeclType(ConstantStringDecl);
2032}
2033
Steve Naroffb29b4272008-04-14 22:03:09 +00002034Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002035 if (!SelGetUidFunctionDecl)
2036 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002037 if (!MsgSendFunctionDecl)
2038 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002039 if (!MsgSendSuperFunctionDecl)
2040 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002041 if (!MsgSendStretFunctionDecl)
2042 SynthMsgSendStretFunctionDecl();
2043 if (!MsgSendSuperStretFunctionDecl)
2044 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002045 if (!MsgSendFpretFunctionDecl)
2046 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002047 if (!GetClassFunctionDecl)
2048 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002049 if (!GetMetaClassFunctionDecl)
2050 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002051
Steve Naroff874e2322007-11-15 10:28:18 +00002052 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002053 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2054 // May need to use objc_msgSend_stret() as well.
2055 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002056 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002057 QualType resultType = mDecl->getResultType();
Chris Lattner8b51fd72008-07-26 22:36:27 +00002058 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002059 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002060 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002061 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002062 }
Steve Naroff874e2322007-11-15 10:28:18 +00002063
Steve Naroff934f2762007-10-24 22:48:43 +00002064 // Synthesize a call to objc_msgSend().
2065 llvm::SmallVector<Expr*, 8> MsgExprs;
2066 IdentifierInfo *clsName = Exp->getClassName();
2067
2068 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2069 if (clsName) { // class message.
Steve Narofffc93d522008-07-24 19:44:33 +00002070 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2071 // the 'super' idiom within a class method.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002072 if (!strcmp(clsName->getName(), "super")) {
2073 MsgSendFlavor = MsgSendSuperFunctionDecl;
2074 if (MsgSendStretFlavor)
2075 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2076 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2077
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002078 ObjCInterfaceDecl *SuperDecl =
Steve Naroff54055232008-10-27 17:20:55 +00002079 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002080
2081 llvm::SmallVector<Expr*, 4> InitExprs;
2082
2083 // set the receiver to self, the first argument to all methods.
Chris Lattner41110242008-06-17 18:05:57 +00002084 InitExprs.push_back(new DeclRefExpr(
Steve Naroff54055232008-10-27 17:20:55 +00002085 CurMethodDef->getSelfDecl(),
Chris Lattner41110242008-06-17 18:05:57 +00002086 Context->getObjCIdType(),
2087 SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002088 llvm::SmallVector<Expr*, 8> ClsExprs;
2089 QualType argType = Context->getPointerType(Context->CharTy);
2090 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2091 SuperDecl->getIdentifier()->getLength(),
2092 false, argType, SourceLocation(),
2093 SourceLocation()));
2094 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2095 &ClsExprs[0],
2096 ClsExprs.size());
2097 // To turn off a warning, type-cast to 'id'
Douglas Gregor49badde2008-10-27 19:41:14 +00002098 InitExprs.push_back( // set 'super class', using objc_getClass().
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002099 new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002100 Cls, Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002101 SourceLocation(), SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002102 // struct objc_super
2103 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00002104 Expr *SuperRep;
Steve Naroffc0a123c2008-03-11 17:37:02 +00002105
Steve Naroff23f41272008-03-11 18:14:26 +00002106 if (LangOpts.Microsoft) {
2107 SynthSuperContructorFunctionDecl();
2108 // Simulate a contructor call...
2109 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2110 superType, SourceLocation());
2111 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2112 superType, SourceLocation());
2113 } else {
2114 // (struct objc_super) { <exprs from above> }
2115 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2116 &InitExprs[0], InitExprs.size(),
Chris Lattner418f6c72008-10-26 23:43:26 +00002117 SourceLocation(), false);
2118 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE,
2119 false);
Steve Naroff23f41272008-03-11 18:14:26 +00002120 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002121 // struct objc_super *
2122 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2123 Context->getPointerType(SuperRep->getType()),
2124 SourceLocation());
2125 MsgExprs.push_back(Unop);
2126 } else {
2127 llvm::SmallVector<Expr*, 8> ClsExprs;
2128 QualType argType = Context->getPointerType(Context->CharTy);
2129 ClsExprs.push_back(new StringLiteral(clsName->getName(),
2130 clsName->getLength(),
2131 false, argType, SourceLocation(),
2132 SourceLocation()));
2133 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2134 &ClsExprs[0],
2135 ClsExprs.size());
2136 MsgExprs.push_back(Cls);
2137 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002138 } else { // instance message.
2139 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00002140
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002141 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00002142 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002143 if (MsgSendStretFlavor)
2144 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00002145 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2146
2147 llvm::SmallVector<Expr*, 4> InitExprs;
2148
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002149 InitExprs.push_back(
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002150 new CStyleCastExpr(Context->getObjCIdType(),
Steve Naroff54055232008-10-27 17:20:55 +00002151 new DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Narofff616ebb2008-07-16 22:35:27 +00002152 Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002153 SourceLocation()),
2154 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002155 SourceLocation(), SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00002156
2157 llvm::SmallVector<Expr*, 8> ClsExprs;
2158 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002159 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2160 SuperDecl->getIdentifier()->getLength(),
Steve Naroff874e2322007-11-15 10:28:18 +00002161 false, argType, SourceLocation(),
2162 SourceLocation()));
2163 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002164 &ClsExprs[0],
2165 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00002166 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002167 InitExprs.push_back(
Douglas Gregor49badde2008-10-27 19:41:14 +00002168 // set 'super class', using objc_getClass().
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002169 new CStyleCastExpr(Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002170 Cls, Context->getObjCIdType(), SourceLocation(), SourceLocation()));
Steve Naroff874e2322007-11-15 10:28:18 +00002171 // struct objc_super
2172 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00002173 Expr *SuperRep;
2174
2175 if (LangOpts.Microsoft) {
2176 SynthSuperContructorFunctionDecl();
2177 // Simulate a contructor call...
2178 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2179 superType, SourceLocation());
2180 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2181 superType, SourceLocation());
2182 } else {
2183 // (struct objc_super) { <exprs from above> }
2184 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2185 &InitExprs[0], InitExprs.size(),
Chris Lattner418f6c72008-10-26 23:43:26 +00002186 SourceLocation(), false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002187 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
2188 }
Steve Naroff874e2322007-11-15 10:28:18 +00002189 // struct objc_super *
2190 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2191 Context->getPointerType(SuperRep->getType()),
2192 SourceLocation());
2193 MsgExprs.push_back(Unop);
2194 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002195 // Remove all type-casts because it may contain objc-style types; e.g.
2196 // Foo<Proto> *.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002197 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002198 recExpr = CE->getSubExpr();
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002199 recExpr = new CStyleCastExpr(Context->getObjCIdType(), recExpr,
Douglas Gregor49badde2008-10-27 19:41:14 +00002200 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002201 SourceLocation(), SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00002202 MsgExprs.push_back(recExpr);
2203 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002204 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00002205 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002206 llvm::SmallVector<Expr*, 8> SelExprs;
2207 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner077bf5e2008-11-24 03:33:13 +00002208 SelExprs.push_back(new StringLiteral(Exp->getSelector().getAsString().c_str(),
2209 Exp->getSelector().getAsString().size(),
Steve Naroff934f2762007-10-24 22:48:43 +00002210 false, argType, SourceLocation(),
2211 SourceLocation()));
2212 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2213 &SelExprs[0], SelExprs.size());
2214 MsgExprs.push_back(SelExp);
2215
2216 // Now push any user supplied arguments.
2217 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002218 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002219 // Make all implicit casts explicit...ICE comes in handy:-)
2220 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2221 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregor49badde2008-10-27 19:41:14 +00002222 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002223 ? Context->getObjCIdType()
Douglas Gregor49badde2008-10-27 19:41:14 +00002224 : ICE->getType();
Steve Naroffb2f9e512008-11-03 23:29:32 +00002225 userExpr = new CStyleCastExpr(type, userExpr, type, SourceLocation(), SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002226 }
2227 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002228 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002229 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002230 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002231 userExpr = CE->getSubExpr();
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002232 userExpr = new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002233 userExpr, Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002234 SourceLocation(), SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002235 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00002236 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002237 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00002238 // We've transferred the ownership to MsgExprs. Null out the argument in
2239 // the original expression, since we will delete it below.
2240 Exp->setArg(i, 0);
2241 }
Steve Naroffab972d32007-11-04 22:37:50 +00002242 // Generate the funky cast.
2243 CastExpr *cast;
2244 llvm::SmallVector<QualType, 8> ArgTypes;
2245 QualType returnType;
2246
2247 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002248 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2249 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2250 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002251 ArgTypes.push_back(Context->getObjCIdType());
2252 ArgTypes.push_back(Context->getObjCSelType());
2253 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002254 // Push any user argument types.
Chris Lattner58cce3b2008-03-16 01:07:14 +00002255 for (unsigned i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002256 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
2257 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002258 : mDecl->getParamDecl(i)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00002259 // Make sure we convert "t (^)(...)" to "t (*)(...)".
2260 if (isBlockPointerType(t)) {
2261 const BlockPointerType *BPT = t->getAsBlockPointerType();
2262 t = Context->getPointerType(BPT->getPointeeType());
2263 }
Steve Naroff352336b2007-11-05 14:36:37 +00002264 ArgTypes.push_back(t);
2265 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002266 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
2267 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00002268 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002269 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002270 }
2271 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002272 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00002273
2274 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002275 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
2276 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002277
2278 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2279 // If we don't do this cast, we get the following bizarre warning/note:
2280 // xx.m:13: warning: function called through a non-compatible type
2281 // xx.m:13: note: if this code is reached, the program will abort
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002282 cast = new CStyleCastExpr(Context->getPointerType(Context->VoidTy), DRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002283 Context->getPointerType(Context->VoidTy),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002284 SourceLocation(), SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00002285
Steve Naroffab972d32007-11-04 22:37:50 +00002286 // Now do the "normal" pointer to function cast.
2287 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002288 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00002289 // If we don't have a method decl, force a variadic cast.
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002290 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Naroffab972d32007-11-04 22:37:50 +00002291 castType = Context->getPointerType(castType);
Steve Naroffb2f9e512008-11-03 23:29:32 +00002292 cast = new CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002293
2294 // Don't forget the parens to enforce the proper binding.
2295 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2296
2297 const FunctionType *FT = msgSendType->getAsFunctionType();
2298 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2299 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002300 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002301 if (MsgSendStretFlavor) {
2302 // We have the method which returns a struct/union. Must also generate
2303 // call to objc_msgSend_stret and hang both varieties on a conditional
2304 // expression which dictate which one to envoke depending on size of
2305 // method's return type.
2306
2307 // Create a reference to the objc_msgSend_stret() declaration.
2308 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
2309 SourceLocation());
2310 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002311 cast = new CStyleCastExpr(Context->getPointerType(Context->VoidTy), STDRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002312 Context->getPointerType(Context->VoidTy),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002313 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002314 // Now do the "normal" pointer to function cast.
2315 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002316 &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002317 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002318 castType = Context->getPointerType(castType);
Steve Naroffb2f9e512008-11-03 23:29:32 +00002319 cast = new CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002320
2321 // Don't forget the parens to enforce the proper binding.
2322 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2323
2324 FT = msgSendType->getAsFunctionType();
2325 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2326 FT->getResultType(), SourceLocation());
2327
2328 // Build sizeof(returnType)
Sebastian Redl05189992008-11-11 17:56:53 +00002329 SizeOfAlignOfExpr *sizeofExpr = new SizeOfAlignOfExpr(true, true,
2330 returnType.getAsOpaquePtr(),
2331 Context->getSizeType(),
2332 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002333 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2334 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2335 // For X86 it is more complicated and some kind of target specific routine
2336 // is needed to decide what to do.
Chris Lattner98be4942008-03-05 18:54:05 +00002337 unsigned IntSize =
2338 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002339 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2340 Context->IntTy,
2341 SourceLocation());
2342 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2343 BinaryOperator::LE,
2344 Context->IntTy,
2345 SourceLocation());
2346 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2347 ConditionalOperator *CondExpr =
2348 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002349 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002350 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002351 return ReplacingStmt;
2352}
2353
Steve Naroffb29b4272008-04-14 22:03:09 +00002354Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002355 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff80c28552008-10-27 20:54:44 +00002356
Steve Naroff934f2762007-10-24 22:48:43 +00002357 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002358 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff934f2762007-10-24 22:48:43 +00002359
Chris Lattnere64b7772007-10-24 16:57:36 +00002360 delete Exp;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002361 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002362}
2363
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002364/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2365/// call to objc_getProtocol("proto-name").
Steve Naroffb29b4272008-04-14 22:03:09 +00002366Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002367 if (!GetProtocolFunctionDecl)
2368 SynthGetProtocolFunctionDecl();
2369 // Create a call to objc_getProtocol("ProtocolName").
2370 llvm::SmallVector<Expr*, 8> ProtoExprs;
2371 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner8ec03f52008-11-24 03:54:41 +00002372 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getNameAsCString(),
2373 strlen(Exp->getProtocol()->getNameAsCString()),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002374 false, argType, SourceLocation(),
2375 SourceLocation()));
2376 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2377 &ProtoExprs[0],
2378 ProtoExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002379 ReplaceStmt(Exp, ProtoExp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002380 delete Exp;
2381 return ProtoExp;
2382
2383}
2384
Steve Naroffbaf58c32008-05-31 14:15:04 +00002385bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
2386 const char *endBuf) {
2387 while (startBuf < endBuf) {
2388 if (*startBuf == '#') {
2389 // Skip whitespace.
2390 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2391 ;
2392 if (!strncmp(startBuf, "if", strlen("if")) ||
2393 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2394 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2395 !strncmp(startBuf, "define", strlen("define")) ||
2396 !strncmp(startBuf, "undef", strlen("undef")) ||
2397 !strncmp(startBuf, "else", strlen("else")) ||
2398 !strncmp(startBuf, "elif", strlen("elif")) ||
2399 !strncmp(startBuf, "endif", strlen("endif")) ||
2400 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2401 !strncmp(startBuf, "include", strlen("include")) ||
2402 !strncmp(startBuf, "import", strlen("import")) ||
2403 !strncmp(startBuf, "include_next", strlen("include_next")))
2404 return true;
2405 }
2406 startBuf++;
2407 }
2408 return false;
2409}
2410
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002411/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002412/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00002413void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002414 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002415 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Chris Lattner8ec03f52008-11-24 03:54:41 +00002416 assert(CDecl->getNameAsCString() &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002417 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002418 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002419 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002420 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002421 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002422 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00002423 SourceLocation LocStart = CDecl->getLocStart();
2424 SourceLocation LocEnd = CDecl->getLocEnd();
2425
2426 const char *startBuf = SM->getCharacterData(LocStart);
2427 const char *endBuf = SM->getCharacterData(LocEnd);
Steve Naroffbaf58c32008-05-31 14:15:04 +00002428
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002429 // If no ivars and no root or if its root, directly or indirectly,
2430 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002431 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2432 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002433 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattneraadaf782008-01-31 19:51:04 +00002434 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002435 return;
2436 }
2437
2438 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002439 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002440 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002441 Result += CDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002442 if (LangOpts.Microsoft)
2443 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00002444
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002445 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002446 const char *cursor = strchr(startBuf, '{');
2447 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002448 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00002449 // If the buffer contains preprocessor directives, we do more fine-grained
2450 // rewrites. This is intended to fix code that looks like (which occurs in
2451 // NSURL.h, for example):
2452 //
2453 // #ifdef XYZ
2454 // @interface Foo : NSObject
2455 // #else
2456 // @interface FooBar : NSObject
2457 // #endif
2458 // {
2459 // int i;
2460 // }
2461 // @end
2462 //
2463 // This clause is segregated to avoid breaking the common case.
2464 if (BufferContainsPPDirectives(startBuf, cursor)) {
2465 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
2466 CDecl->getClassLoc();
2467 const char *endHeader = SM->getCharacterData(L);
2468 endHeader += Lexer::MeasureTokenLength(L, *SM);
2469
Chris Lattner3db6cae2008-07-21 18:19:38 +00002470 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00002471 // advance to the end of the referenced protocols.
2472 while (endHeader < cursor && *endHeader != '>') endHeader++;
2473 endHeader++;
2474 }
2475 // rewrite the original header
2476 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2477 } else {
2478 // rewrite the original header *without* disturbing the '{'
2479 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
2480 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002481 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002482 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002483 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002484 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002485 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00002486 Result += "_IVARS;\n";
Steve Narofffea763e82007-11-14 19:25:57 +00002487
2488 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002489 SourceLocation OnePastCurly =
2490 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2491 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002492 }
2493 cursor++; // past '{'
2494
2495 // Now comment out any visibility specifiers.
2496 while (cursor < endBuf) {
2497 if (*cursor == '@') {
2498 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002499 // Skip whitespace.
2500 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2501 /*scan*/;
2502
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002503 // FIXME: presence of @public, etc. inside comment results in
2504 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002505 if (!strncmp(cursor, "public", strlen("public")) ||
2506 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00002507 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002508 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002509 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002510 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002511 // FIXME: If there are cases where '<' is used in ivar declaration part
2512 // of user code, then scan the ivar list and use needToScanForQualifiers
2513 // for type checking.
2514 else if (*cursor == '<') {
2515 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002516 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002517 cursor = strchr(cursor, '>');
2518 cursor++;
2519 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002520 InsertText(atLoc, " */", 3);
Steve Naroffced80a82008-10-30 12:09:33 +00002521 } else if (*cursor == '^') { // rewrite block specifier.
2522 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2523 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002524 }
Steve Narofffea763e82007-11-14 19:25:57 +00002525 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002526 }
Steve Narofffea763e82007-11-14 19:25:57 +00002527 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002528 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00002529 } else { // we don't have any instance variables - insert super struct.
2530 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2531 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002532 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002533 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002534 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00002535 Result += "_IVARS;\n};\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00002536 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002537 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002538 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002539 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00002540 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002541}
2542
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002543// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002544/// class methods.
Steve Naroffb29b4272008-04-14 22:03:09 +00002545void RewriteObjC::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002546 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002547 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002548 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002549 const char *ClassName,
2550 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002551 if (MethodBegin == MethodEnd) return;
2552
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002553 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002554 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002555 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002556 SEL _cmd;
2557 char *method_types;
2558 void *_imp;
2559 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002560 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002561 Result += "\nstruct _objc_method {\n";
2562 Result += "\tSEL _cmd;\n";
2563 Result += "\tchar *method_types;\n";
2564 Result += "\tvoid *_imp;\n";
2565 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002566
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002567 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002568 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002569
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002570 // Build _objc_method_list for class's methods if needed
Steve Naroff946a6932008-03-11 00:12:29 +00002571
2572 /* struct {
2573 struct _objc_method_list *next_method;
2574 int method_count;
2575 struct _objc_method method_list[];
2576 }
2577 */
2578 Result += "\nstatic struct {\n";
2579 Result += "\tstruct _objc_method_list *next_method;\n";
2580 Result += "\tint method_count;\n";
2581 Result += "\tstruct _objc_method method_list[";
2582 Result += utostr(MethodEnd-MethodBegin);
2583 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002584 Result += prefix;
2585 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2586 Result += "_METHODS_";
2587 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002588 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002589 Result += IsInstanceMethod ? "inst" : "cls";
2590 Result += "_meth\")))= ";
2591 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002592
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002593 Result += "\t,{{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002594 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002595 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002596 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002597 Result += "\", \"";
2598 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002599 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002600 Result += MethodInternalNames[*MethodBegin];
2601 Result += "}\n";
2602 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2603 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002604 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002605 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002606 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002607 Result += "\", \"";
2608 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002609 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002610 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002611 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002612 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002613 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002614}
2615
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002616/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00002617void RewriteObjC::
2618RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
2619 const char *prefix,
2620 const char *ClassName,
2621 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002622 static bool objc_protocol_methods = false;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002623 if (Protocols.empty()) return;
2624
2625 for (unsigned i = 0; i != Protocols.size(); i++) {
2626 ObjCProtocolDecl *PDecl = Protocols[i];
2627 // Output struct protocol_methods holder of method selector and type.
2628 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
2629 /* struct protocol_methods {
2630 SEL _cmd;
2631 char *method_types;
2632 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002633 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002634 Result += "\nstruct protocol_methods {\n";
2635 Result += "\tSEL _cmd;\n";
2636 Result += "\tchar *method_types;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002637 Result += "};\n";
Steve Narofffbfe8252008-05-06 18:26:51 +00002638
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002639 objc_protocol_methods = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002640 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002641 // Do not synthesize the protocol more than once.
2642 if (ObjCSynthesizedProtocols.count(PDecl))
2643 continue;
2644
2645 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2646 unsigned NumMethods = PDecl->getNumInstanceMethods();
2647 /* struct _objc_protocol_method_list {
2648 int protocol_method_count;
2649 struct protocol_methods protocols[];
2650 }
2651 */
2652 Result += "\nstatic struct {\n";
2653 Result += "\tint protocol_method_count;\n";
2654 Result += "\tstruct protocol_methods protocols[";
2655 Result += utostr(NumMethods);
2656 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002657 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002658 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
2659 "{\n\t" + utostr(NumMethods) + "\n";
2660
2661 // Output instance methods declared in this protocol.
2662 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
2663 E = PDecl->instmeth_end(); I != E; ++I) {
2664 if (I == PDecl->instmeth_begin())
2665 Result += "\t ,{{(SEL)\"";
2666 else
2667 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002668 Result += (*I)->getSelector().getAsString().c_str();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002669 std::string MethodTypeString;
2670 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2671 Result += "\", \"";
2672 Result += MethodTypeString;
2673 Result += "\"}\n";
2674 }
2675 Result += "\t }\n};\n";
2676 }
2677
2678 // Output class methods declared in this protocol.
2679 int NumMethods = PDecl->getNumClassMethods();
2680 if (NumMethods > 0) {
2681 /* struct _objc_protocol_method_list {
2682 int protocol_method_count;
2683 struct protocol_methods protocols[];
2684 }
2685 */
2686 Result += "\nstatic struct {\n";
2687 Result += "\tint protocol_method_count;\n";
2688 Result += "\tstruct protocol_methods protocols[";
2689 Result += utostr(NumMethods);
2690 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002691 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002692 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2693 "{\n\t";
2694 Result += utostr(NumMethods);
2695 Result += "\n";
2696
2697 // Output instance methods declared in this protocol.
2698 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
2699 E = PDecl->classmeth_end(); I != E; ++I) {
2700 if (I == PDecl->classmeth_begin())
2701 Result += "\t ,{{(SEL)\"";
2702 else
2703 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002704 Result += (*I)->getSelector().getAsString().c_str();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002705 std::string MethodTypeString;
2706 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2707 Result += "\", \"";
2708 Result += MethodTypeString;
2709 Result += "\"}\n";
2710 }
2711 Result += "\t }\n};\n";
2712 }
2713
2714 // Output:
2715 /* struct _objc_protocol {
2716 // Objective-C 1.0 extensions
2717 struct _objc_protocol_extension *isa;
2718 char *protocol_name;
2719 struct _objc_protocol **protocol_list;
2720 struct _objc_protocol_method_list *instance_methods;
2721 struct _objc_protocol_method_list *class_methods;
2722 };
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002723 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002724 static bool objc_protocol = false;
2725 if (!objc_protocol) {
2726 Result += "\nstruct _objc_protocol {\n";
2727 Result += "\tstruct _objc_protocol_extension *isa;\n";
2728 Result += "\tchar *protocol_name;\n";
2729 Result += "\tstruct _objc_protocol **protocol_list;\n";
2730 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2731 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2732 Result += "};\n";
2733
2734 objc_protocol = true;
2735 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002736
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002737 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002738 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002739 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
2740 "{\n\t0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002741 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002742 Result += "\", 0, ";
2743 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2744 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002745 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002746 Result += ", ";
2747 }
2748 else
2749 Result += "0, ";
2750 if (PDecl->getNumClassMethods() > 0) {
2751 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002752 Result += PDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002753 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002754 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002755 else
2756 Result += "0\n";
2757 Result += "};\n";
2758
2759 // Mark this protocol as having been generated.
2760 if (!ObjCSynthesizedProtocols.insert(PDecl))
2761 assert(false && "protocol already synthesized");
2762 }
2763 // Output the top lovel protocol meta-data for the class.
2764 /* struct _objc_protocol_list {
2765 struct _objc_protocol_list *next;
2766 int protocol_count;
2767 struct _objc_protocol *class_protocols[];
2768 }
2769 */
2770 Result += "\nstatic struct {\n";
2771 Result += "\tstruct _objc_protocol_list *next;\n";
2772 Result += "\tint protocol_count;\n";
2773 Result += "\tstruct _objc_protocol *class_protocols[";
2774 Result += utostr(Protocols.size());
2775 Result += "];\n} _OBJC_";
2776 Result += prefix;
2777 Result += "_PROTOCOLS_";
2778 Result += ClassName;
2779 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2780 "{\n\t0, ";
2781 Result += utostr(Protocols.size());
2782 Result += "\n";
2783
2784 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002785 Result += Protocols[0]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002786 Result += " \n";
2787
2788 for (unsigned i = 1; i != Protocols.size(); i++) {
2789 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002790 Result += Protocols[i]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002791 Result += "\n";
2792 }
2793 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002794}
2795
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002796/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002797/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00002798void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002799 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002800 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002801 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002802 ObjCCategoryDecl *CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002803 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2804 CDecl = CDecl->getNextClassCategory())
2805 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2806 break;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002807
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002808 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00002809 FullCategoryName += '_';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002810 FullCategoryName += IDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00002811
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002812 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002813 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002814 true, "CATEGORY_", FullCategoryName.c_str(),
2815 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002816
2817 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002818 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002819 false, "CATEGORY_", FullCategoryName.c_str(),
2820 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002821
2822 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002823 // Null CDecl is case of a category implementation with no category interface
2824 if (CDecl)
Chris Lattner780f3292008-07-21 21:32:27 +00002825 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Chris Lattnereb44eee2007-12-23 01:40:15 +00002826 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002827
2828 /* struct _objc_category {
2829 char *category_name;
2830 char *class_name;
2831 struct _objc_method_list *instance_methods;
2832 struct _objc_method_list *class_methods;
2833 struct _objc_protocol_list *protocols;
2834 // Objective-C 1.0 extensions
2835 uint32_t size; // sizeof (struct _objc_category)
2836 struct _objc_property_list *instance_properties; // category's own
2837 // @property decl.
2838 };
2839 */
2840
2841 static bool objc_category = false;
2842 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002843 Result += "\nstruct _objc_category {\n";
2844 Result += "\tchar *category_name;\n";
2845 Result += "\tchar *class_name;\n";
2846 Result += "\tstruct _objc_method_list *instance_methods;\n";
2847 Result += "\tstruct _objc_method_list *class_methods;\n";
2848 Result += "\tstruct _objc_protocol_list *protocols;\n";
2849 Result += "\tunsigned int size;\n";
2850 Result += "\tstruct _objc_property_list *instance_properties;\n";
2851 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002852 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002853 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002854 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2855 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002856 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002857 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002858 Result += "\"\n\t, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002859 Result += ClassDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002860 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002861
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002862 if (IDecl->getNumInstanceMethods() > 0) {
2863 Result += "\t, (struct _objc_method_list *)"
2864 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2865 Result += FullCategoryName;
2866 Result += "\n";
2867 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002868 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002869 Result += "\t, 0\n";
2870 if (IDecl->getNumClassMethods() > 0) {
2871 Result += "\t, (struct _objc_method_list *)"
2872 "&_OBJC_CATEGORY_CLASS_METHODS_";
2873 Result += FullCategoryName;
2874 Result += "\n";
2875 }
2876 else
2877 Result += "\t, 0\n";
2878
Chris Lattner780f3292008-07-21 21:32:27 +00002879 if (CDecl && !CDecl->getReferencedProtocols().empty()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002880 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2881 Result += FullCategoryName;
2882 Result += "\n";
2883 }
2884 else
2885 Result += "\t, 0\n";
2886 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002887}
2888
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002889/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2890/// ivar offset.
Steve Naroffb29b4272008-04-14 22:03:09 +00002891void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002892 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002893 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00002894 if (ivar->isBitField()) {
2895 // FIXME: The hack below doesn't work for bitfields. For now, we simply
2896 // place all bitfields at offset 0.
2897 Result += "0";
2898 } else {
2899 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002900 Result += IDecl->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00002901 if (LangOpts.Microsoft)
2902 Result += "_IMPL";
2903 Result += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002904 Result += ivar->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00002905 Result += ")";
2906 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002907}
2908
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002909//===----------------------------------------------------------------------===//
2910// Meta Data Emission
2911//===----------------------------------------------------------------------===//
2912
Steve Naroffb29b4272008-04-14 22:03:09 +00002913void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002914 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002915 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002916
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002917 // Explictly declared @interface's are already synthesized.
2918 if (CDecl->ImplicitInterfaceDecl()) {
2919 // FIXME: Implementation of a class with no @interface (legacy) doese not
2920 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002921 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002922 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002923
Chris Lattnerbe6df082007-12-12 07:56:42 +00002924 // Build _objc_ivar_list metadata for classes ivars if needed
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002925 unsigned NumIvars = !IDecl->ivar_empty()
2926 ? IDecl->ivar_size()
2927 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002928 if (NumIvars > 0) {
2929 static bool objc_ivar = false;
2930 if (!objc_ivar) {
2931 /* struct _objc_ivar {
2932 char *ivar_name;
2933 char *ivar_type;
2934 int ivar_offset;
2935 };
2936 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002937 Result += "\nstruct _objc_ivar {\n";
2938 Result += "\tchar *ivar_name;\n";
2939 Result += "\tchar *ivar_type;\n";
2940 Result += "\tint ivar_offset;\n";
2941 Result += "};\n";
2942
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002943 objc_ivar = true;
2944 }
2945
Steve Naroff946a6932008-03-11 00:12:29 +00002946 /* struct {
2947 int ivar_count;
2948 struct _objc_ivar ivar_list[nIvars];
2949 };
2950 */
2951 Result += "\nstatic struct {\n";
2952 Result += "\tint ivar_count;\n";
2953 Result += "\tstruct _objc_ivar ivar_list[";
2954 Result += utostr(NumIvars);
2955 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002956 Result += IDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00002957 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002958 "{\n\t";
2959 Result += utostr(NumIvars);
2960 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002961
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002962 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002963 if (!IDecl->ivar_empty()) {
Chris Lattnerbe6df082007-12-12 07:56:42 +00002964 IVI = IDecl->ivar_begin();
2965 IVE = IDecl->ivar_end();
2966 } else {
2967 IVI = CDecl->ivar_begin();
2968 IVE = CDecl->ivar_end();
2969 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002970 Result += "\t,{{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002971 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002972 Result += "\", \"";
2973 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002974 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002975 Result += StrEncoding;
2976 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002977 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002978 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002979 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002980 Result += "\t ,{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002981 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002982 Result += "\", \"";
2983 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002984 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002985 Result += StrEncoding;
2986 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002987 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002988 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002989 }
2990
2991 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002992 }
2993
2994 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002995 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00002996 true, "", IDecl->getNameAsCString(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002997
2998 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002999 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003000 false, "", IDecl->getNameAsCString(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003001
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003002 // Protocols referenced in class declaration?
Chris Lattner780f3292008-07-21 21:32:27 +00003003 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003004 "CLASS", CDecl->getNameAsCString(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003005
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003006
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003007 // Declaration of class/meta-class metadata
3008 /* struct _objc_class {
3009 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003010 const char *super_class_name;
3011 char *name;
3012 long version;
3013 long info;
3014 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003015 struct _objc_ivar_list *ivars;
3016 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003017 struct objc_cache *cache;
3018 struct objc_protocol_list *protocols;
3019 const char *ivar_layout;
3020 struct _objc_class_ext *ext;
3021 };
3022 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003023 static bool objc_class = false;
3024 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003025 Result += "\nstruct _objc_class {\n";
3026 Result += "\tstruct _objc_class *isa;\n";
3027 Result += "\tconst char *super_class_name;\n";
3028 Result += "\tchar *name;\n";
3029 Result += "\tlong version;\n";
3030 Result += "\tlong info;\n";
3031 Result += "\tlong instance_size;\n";
3032 Result += "\tstruct _objc_ivar_list *ivars;\n";
3033 Result += "\tstruct _objc_method_list *methods;\n";
3034 Result += "\tstruct objc_cache *cache;\n";
3035 Result += "\tstruct _objc_protocol_list *protocols;\n";
3036 Result += "\tconst char *ivar_layout;\n";
3037 Result += "\tstruct _objc_class_ext *ext;\n";
3038 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003039 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003040 }
3041
3042 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003043 ObjCInterfaceDecl *RootClass = 0;
3044 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003045 while (SuperClass) {
3046 RootClass = SuperClass;
3047 SuperClass = SuperClass->getSuperClass();
3048 }
3049 SuperClass = CDecl->getSuperClass();
3050
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003051 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003052 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003053 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003054 "{\n\t(struct _objc_class *)\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003055 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003056 Result += "\"";
3057
3058 if (SuperClass) {
3059 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003060 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003061 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003062 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003063 Result += "\"";
3064 }
3065 else {
3066 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003067 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003068 Result += "\"";
3069 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003070 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003071 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003072 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffb26d7132007-12-05 21:49:40 +00003073 if (IDecl->getNumClassMethods() > 0) {
Steve Naroff23f41272008-03-11 18:14:26 +00003074 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003075 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003076 Result += "\n";
3077 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003078 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003079 Result += ", 0\n";
Chris Lattner3db6cae2008-07-21 18:19:38 +00003080 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003081 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003082 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003083 Result += ",0,0\n";
3084 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003085 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003086 Result += "\t,0,0,0,0\n";
3087 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003088
3089 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003090 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003091 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003092 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003093 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003094 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003095 if (SuperClass) {
3096 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003097 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003098 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003099 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003100 Result += "\"";
3101 }
3102 else {
3103 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003104 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003105 Result += "\"";
3106 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003107 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003108 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003109 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003110 Result += ",0";
3111 else {
3112 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003113 Result += ",sizeof(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003114 Result += CDecl->getNameAsString();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003115 if (LangOpts.Microsoft)
3116 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003117 Result += ")";
3118 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003119 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00003120 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003121 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003122 Result += "\n\t";
3123 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003124 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003125 Result += ",0";
3126 if (IDecl->getNumInstanceMethods() > 0) {
Steve Naroff946a6932008-03-11 00:12:29 +00003127 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003128 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003129 Result += ", 0\n\t";
3130 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003131 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003132 Result += ",0,0";
Chris Lattner3db6cae2008-07-21 18:19:38 +00003133 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003134 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003135 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003136 Result += ", 0,0\n";
3137 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003138 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003139 Result += ",0,0,0\n";
3140 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003141}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003142
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003143/// RewriteImplementations - This routine rewrites all method implementations
3144/// and emits meta-data.
3145
Steve Narofface66252008-11-13 20:07:04 +00003146void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003147 int ClsDefCount = ClassImplementation.size();
3148 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003149
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003150 // Rewrite implemented methods
3151 for (int i = 0; i < ClsDefCount; i++)
3152 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003153
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003154 for (int i = 0; i < CatDefCount; i++)
3155 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00003156}
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003157
Steve Narofface66252008-11-13 20:07:04 +00003158void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3159 int ClsDefCount = ClassImplementation.size();
3160 int CatDefCount = CategoryImplementation.size();
3161
Steve Naroff5df5b762008-05-07 21:23:49 +00003162 // This is needed for determining instance variable offsets.
Steve Naroffa11440b2008-08-05 18:47:23 +00003163 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003164 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003165 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003166 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003167
3168 // For each implemented category, write out all its meta data.
3169 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003170 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003171
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003172 // Write objc_symtab metadata
3173 /*
3174 struct _objc_symtab
3175 {
3176 long sel_ref_cnt;
3177 SEL *refs;
3178 short cls_def_cnt;
3179 short cat_def_cnt;
3180 void *defs[cls_def_cnt + cat_def_cnt];
3181 };
3182 */
3183
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003184 Result += "\nstruct _objc_symtab {\n";
3185 Result += "\tlong sel_ref_cnt;\n";
3186 Result += "\tSEL *refs;\n";
3187 Result += "\tshort cls_def_cnt;\n";
3188 Result += "\tshort cat_def_cnt;\n";
3189 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3190 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003191
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003192 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00003193 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003194 Result += "\t0, 0, " + utostr(ClsDefCount)
3195 + ", " + utostr(CatDefCount) + "\n";
3196 for (int i = 0; i < ClsDefCount; i++) {
3197 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003198 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003199 Result += "\n";
3200 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003201
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003202 for (int i = 0; i < CatDefCount; i++) {
3203 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003204 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003205 Result += "_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003206 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003207 Result += "\n";
3208 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003209
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003210 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003211
3212 // Write objc_module metadata
3213
3214 /*
3215 struct _objc_module {
3216 long version;
3217 long size;
3218 const char *name;
3219 struct _objc_symtab *symtab;
3220 }
3221 */
3222
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003223 Result += "\nstruct _objc_module {\n";
3224 Result += "\tlong version;\n";
3225 Result += "\tlong size;\n";
3226 Result += "\tconst char *name;\n";
3227 Result += "\tstruct _objc_symtab *symtab;\n";
3228 Result += "};\n\n";
3229 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00003230 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003231 Result += "\t" + utostr(OBJC_ABI_VERSION) +
3232 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003233 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003234
3235 if (LangOpts.Microsoft) {
3236 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00003237 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003238 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3239 Result += "&_OBJC_MODULES;\n";
3240 Result += "#pragma data_seg(pop)\n\n";
3241 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003242}
Chris Lattner311ff022007-10-16 22:36:42 +00003243
Steve Naroff54055232008-10-27 17:20:55 +00003244std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3245 const char *funcName,
3246 std::string Tag) {
3247 const FunctionType *AFT = CE->getFunctionType();
3248 QualType RT = AFT->getResultType();
3249 std::string StructRef = "struct " + Tag;
3250 std::string S = "static " + RT.getAsString() + " __" +
3251 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003252
Steve Naroff54055232008-10-27 17:20:55 +00003253 BlockDecl *BD = CE->getBlockDecl();
3254
3255 if (isa<FunctionTypeNoProto>(AFT)) {
3256 S += "()";
3257 } else if (BD->param_empty()) {
3258 S += "(" + StructRef + " *__cself)";
3259 } else {
3260 const FunctionTypeProto *FT = cast<FunctionTypeProto>(AFT);
3261 assert(FT && "SynthesizeBlockFunc: No function proto");
3262 S += '(';
3263 // first add the implicit argument.
3264 S += StructRef + " *__cself, ";
3265 std::string ParamStr;
3266 for (BlockDecl::param_iterator AI = BD->param_begin(),
3267 E = BD->param_end(); AI != E; ++AI) {
3268 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003269 ParamStr = (*AI)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003270 (*AI)->getType().getAsStringInternal(ParamStr);
3271 S += ParamStr;
3272 }
3273 if (FT->isVariadic()) {
3274 if (!BD->param_empty()) S += ", ";
3275 S += "...";
3276 }
3277 S += ')';
3278 }
3279 S += " {\n";
3280
3281 // Create local declarations to avoid rewriting all closure decl ref exprs.
3282 // First, emit a declaration for all "by ref" decls.
3283 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3284 E = BlockByRefDecls.end(); I != E; ++I) {
3285 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003286 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003287 Context->getPointerType((*I)->getType()).getAsStringInternal(Name);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003288 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Steve Naroff54055232008-10-27 17:20:55 +00003289 }
3290 // Next, emit a declaration for all "by copy" declarations.
3291 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3292 E = BlockByCopyDecls.end(); I != E; ++I) {
3293 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003294 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003295 // Handle nested closure invocation. For example:
3296 //
3297 // void (^myImportedClosure)(void);
3298 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3299 //
3300 // void (^anotherClosure)(void);
3301 // anotherClosure = ^(void) {
3302 // myImportedClosure(); // import and invoke the closure
3303 // };
3304 //
3305 if (isBlockPointerType((*I)->getType()))
3306 S += "struct __block_impl *";
3307 else
3308 (*I)->getType().getAsStringInternal(Name);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003309 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff54055232008-10-27 17:20:55 +00003310 }
3311 std::string RewrittenStr = RewrittenBlockExprs[CE];
3312 const char *cstr = RewrittenStr.c_str();
3313 while (*cstr++ != '{') ;
3314 S += cstr;
3315 S += "\n";
3316 return S;
3317}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003318
Steve Naroff54055232008-10-27 17:20:55 +00003319std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3320 const char *funcName,
3321 std::string Tag) {
3322 std::string StructRef = "struct " + Tag;
3323 std::string S = "static void __";
3324
3325 S += funcName;
3326 S += "_block_copy_" + utostr(i);
3327 S += "(" + StructRef;
3328 S += "*dst, " + StructRef;
3329 S += "*src) {";
3330 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3331 E = ImportedBlockDecls.end(); I != E; ++I) {
3332 S += "_Block_copy_assign(&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003333 S += (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003334 S += ", src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003335 S += (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003336 S += ");}";
3337 }
3338 S += "\nstatic void __";
3339 S += funcName;
3340 S += "_block_dispose_" + utostr(i);
3341 S += "(" + StructRef;
3342 S += "*src) {";
3343 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3344 E = ImportedBlockDecls.end(); I != E; ++I) {
3345 S += "_Block_destroy(src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003346 S += (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003347 S += ");";
3348 }
3349 S += "}\n";
3350 return S;
3351}
3352
3353std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3354 bool hasCopyDisposeHelpers) {
Steve Naroffced80a82008-10-30 12:09:33 +00003355 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00003356 std::string Constructor = " " + Tag;
3357
3358 S += " {\n struct __block_impl impl;\n";
3359
3360 if (hasCopyDisposeHelpers)
3361 S += " void *copy;\n void *dispose;\n";
3362
3363 Constructor += "(void *fp";
3364
3365 if (hasCopyDisposeHelpers)
3366 Constructor += ", void *copyHelp, void *disposeHelp";
3367
3368 if (BlockDeclRefs.size()) {
3369 // Output all "by copy" declarations.
3370 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3371 E = BlockByCopyDecls.end(); I != E; ++I) {
3372 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003373 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003374 std::string ArgName = "_" + FieldName;
3375 // Handle nested closure invocation. For example:
3376 //
3377 // void (^myImportedBlock)(void);
3378 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3379 //
3380 // void (^anotherBlock)(void);
3381 // anotherBlock = ^(void) {
3382 // myImportedBlock(); // import and invoke the closure
3383 // };
3384 //
3385 if (isBlockPointerType((*I)->getType())) {
3386 S += "struct __block_impl *";
3387 Constructor += ", void *" + ArgName;
3388 } else {
3389 (*I)->getType().getAsStringInternal(FieldName);
3390 (*I)->getType().getAsStringInternal(ArgName);
3391 Constructor += ", " + ArgName;
3392 }
3393 S += FieldName + ";\n";
3394 }
3395 // Output all "by ref" declarations.
3396 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3397 E = BlockByRefDecls.end(); I != E; ++I) {
3398 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003399 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003400 std::string ArgName = "_" + FieldName;
3401 // Handle nested closure invocation. For example:
3402 //
3403 // void (^myImportedBlock)(void);
3404 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3405 //
3406 // void (^anotherBlock)(void);
3407 // anotherBlock = ^(void) {
3408 // myImportedBlock(); // import and invoke the closure
3409 // };
3410 //
3411 if (isBlockPointerType((*I)->getType())) {
3412 S += "struct __block_impl *";
3413 Constructor += ", void *" + ArgName;
3414 } else {
3415 Context->getPointerType((*I)->getType()).getAsStringInternal(FieldName);
3416 Context->getPointerType((*I)->getType()).getAsStringInternal(ArgName);
3417 Constructor += ", " + ArgName;
3418 }
3419 S += FieldName + "; // by ref\n";
3420 }
3421 // Finish writing the constructor.
3422 // FIXME: handle NSConcreteGlobalBlock.
3423 Constructor += ", int flags=0) {\n";
3424 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3425 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3426
3427 if (hasCopyDisposeHelpers)
3428 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3429
3430 // Initialize all "by copy" arguments.
3431 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3432 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003433 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003434 Constructor += " ";
3435 if (isBlockPointerType((*I)->getType()))
3436 Constructor += Name + " = (struct __block_impl *)_";
3437 else
3438 Constructor += Name + " = _";
3439 Constructor += Name + ";\n";
3440 }
3441 // Initialize all "by ref" arguments.
3442 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3443 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003444 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003445 Constructor += " ";
3446 if (isBlockPointerType((*I)->getType()))
3447 Constructor += Name + " = (struct __block_impl *)_";
3448 else
3449 Constructor += Name + " = _";
3450 Constructor += Name + ";\n";
3451 }
3452 } else {
3453 // Finish writing the constructor.
3454 // FIXME: handle NSConcreteGlobalBlock.
3455 Constructor += ", int flags=0) {\n";
3456 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3457 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3458 if (hasCopyDisposeHelpers)
3459 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3460 }
3461 Constructor += " ";
3462 Constructor += "}\n";
3463 S += Constructor;
3464 S += "};\n";
3465 return S;
3466}
3467
3468void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3469 const char *FunName) {
3470 // Insert closures that were part of the function.
3471 for (unsigned i = 0; i < Blocks.size(); i++) {
3472
3473 CollectBlockDeclRefInfo(Blocks[i]);
3474
3475 std::string Tag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
3476
3477 std::string CI = SynthesizeBlockImpl(Blocks[i], Tag,
3478 ImportedBlockDecls.size() > 0);
3479
3480 InsertText(FunLocStart, CI.c_str(), CI.size());
3481
3482 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, Tag);
3483
3484 InsertText(FunLocStart, CF.c_str(), CF.size());
3485
3486 if (ImportedBlockDecls.size()) {
3487 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, Tag);
3488 InsertText(FunLocStart, HF.c_str(), HF.size());
3489 }
3490
3491 BlockDeclRefs.clear();
3492 BlockByRefDecls.clear();
3493 BlockByCopyDecls.clear();
3494 BlockCallExprs.clear();
3495 ImportedBlockDecls.clear();
3496 }
3497 Blocks.clear();
3498 RewrittenBlockExprs.clear();
3499}
3500
3501void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3502 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner8ec03f52008-11-24 03:54:41 +00003503 const char *FuncName = FD->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003504
3505 SynthesizeBlockLiterals(FunLocStart, FuncName);
3506}
3507
3508void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00003509 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3510 //SourceLocation FunLocStart = MD->getLocStart();
3511 // FIXME: This hack works around a bug in Rewrite.InsertText().
3512 SourceLocation FunLocStart = MD->getLocStart().getFileLocWithOffset(-1);
Chris Lattner077bf5e2008-11-24 03:33:13 +00003513 std::string FuncName = MD->getSelector().getAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003514 // Convert colons to underscores.
3515 std::string::size_type loc = 0;
3516 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3517 FuncName.replace(loc, 1, "_");
3518
3519 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
3520}
3521
3522void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
3523 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3524 CI != E; ++CI)
3525 if (*CI) {
3526 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3527 GetBlockDeclRefExprs(CBE->getBody());
3528 else
3529 GetBlockDeclRefExprs(*CI);
3530 }
3531 // Handle specific things.
3532 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
3533 // FIXME: Handle enums.
3534 if (!isa<FunctionDecl>(CDRE->getDecl()))
3535 BlockDeclRefs.push_back(CDRE);
3536 return;
3537}
3538
3539void RewriteObjC::GetBlockCallExprs(Stmt *S) {
3540 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3541 CI != E; ++CI)
3542 if (*CI) {
3543 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3544 GetBlockCallExprs(CBE->getBody());
3545 else
3546 GetBlockCallExprs(*CI);
3547 }
3548
3549 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
3550 if (CE->getCallee()->getType()->isBlockPointerType()) {
3551 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
3552 }
3553 }
3554 return;
3555}
3556
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003557Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00003558 // Navigate to relevant type information.
3559 const char *closureName = 0;
3560 const BlockPointerType *CPT = 0;
3561
3562 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003563 closureName = DRE->getDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003564 CPT = DRE->getType()->getAsBlockPointerType();
3565 } else if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003566 closureName = CDRE->getDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003567 CPT = CDRE->getType()->getAsBlockPointerType();
3568 } else if (MemberExpr *MExpr = dyn_cast<MemberExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003569 closureName = MExpr->getMemberDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003570 CPT = MExpr->getType()->getAsBlockPointerType();
3571 } else {
3572 assert(1 && "RewriteBlockClass: Bad type");
3573 }
3574 assert(CPT && "RewriteBlockClass: Bad type");
3575 const FunctionType *FT = CPT->getPointeeType()->getAsFunctionType();
3576 assert(FT && "RewriteBlockClass: Bad type");
3577 const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(FT);
3578 // FTP will be null for closures that don't take arguments.
3579
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003580 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
3581 SourceLocation(),
3582 &Context->Idents.get("__block_impl"));
3583 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00003584
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003585 // Generate a funky cast.
3586 llvm::SmallVector<QualType, 8> ArgTypes;
3587
3588 // Push the block argument type.
3589 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00003590 if (FTP) {
3591 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003592 E = FTP->arg_type_end(); I && (I != E); ++I) {
3593 QualType t = *I;
3594 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3595 if (isBlockPointerType(t)) {
3596 const BlockPointerType *BPT = t->getAsBlockPointerType();
3597 t = Context->getPointerType(BPT->getPointeeType());
3598 }
3599 ArgTypes.push_back(t);
3600 }
Steve Naroff54055232008-10-27 17:20:55 +00003601 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003602 // Now do the pointer to function cast.
3603 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
3604 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
3605
3606 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Steve Naroff54055232008-10-27 17:20:55 +00003607
Steve Naroffb2f9e512008-11-03 23:29:32 +00003608 CastExpr *BlkCast = new CStyleCastExpr(PtrBlock, Exp->getCallee(), PtrBlock, SourceLocation(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003609 // Don't forget the parens to enforce the proper binding.
3610 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), BlkCast);
3611 //PE->dump();
Steve Naroff54055232008-10-27 17:20:55 +00003612
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003613 FieldDecl *FD = FieldDecl::Create(*Context, SourceLocation(),
3614 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy);
3615 MemberExpr *ME = new MemberExpr(PE, true, FD, SourceLocation(), FD->getType());
3616
Steve Naroffb2f9e512008-11-03 23:29:32 +00003617 CastExpr *FunkCast = new CStyleCastExpr(PtrToFuncCastType, ME, PtrToFuncCastType, SourceLocation(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003618 PE = new ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
3619
3620 llvm::SmallVector<Expr*, 8> BlkExprs;
3621 // Add the implicit argument.
3622 BlkExprs.push_back(BlkCast);
3623 // Add the user arguments.
Steve Naroff54055232008-10-27 17:20:55 +00003624 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3625 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003626 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00003627 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003628 CallExpr *CE = new CallExpr(PE, &BlkExprs[0], BlkExprs.size(), Exp->getType(), SourceLocation());
3629 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00003630}
3631
3632void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003633 Stmt *BlockCall = SynthesizeBlockCall(Exp);
3634 ReplaceStmt(Exp, BlockCall);
Steve Naroff54055232008-10-27 17:20:55 +00003635}
3636
3637void RewriteObjC::RewriteBlockDeclRefExpr(BlockDeclRefExpr *BDRE) {
3638 // FIXME: Add more elaborate code generation required by the ABI.
3639 InsertText(BDRE->getLocStart(), "*", 1);
3640}
3641
Steve Naroffb2f9e512008-11-03 23:29:32 +00003642void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3643 SourceLocation LocStart = CE->getLParenLoc();
3644 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00003645
3646 // Need to avoid trying to rewrite synthesized casts.
3647 if (LocStart.isInvalid())
3648 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00003649 // Need to avoid trying to rewrite casts contained in macros.
3650 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3651 return;
Steve Narofffa15fd92008-10-28 20:29:00 +00003652
Steve Naroff54055232008-10-27 17:20:55 +00003653 const char *startBuf = SM->getCharacterData(LocStart);
3654 const char *endBuf = SM->getCharacterData(LocEnd);
3655
3656 // advance the location to startArgList.
3657 const char *argPtr = startBuf;
3658
3659 while (*argPtr++ && (argPtr < endBuf)) {
3660 switch (*argPtr) {
3661 case '^':
3662 // Replace the '^' with '*'.
3663 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
3664 ReplaceText(LocStart, 1, "*", 1);
3665 break;
3666 }
3667 }
3668 return;
3669}
3670
3671void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
3672 SourceLocation DeclLoc = FD->getLocation();
3673 unsigned parenCount = 0;
3674
3675 // We have 1 or more arguments that have closure pointers.
3676 const char *startBuf = SM->getCharacterData(DeclLoc);
3677 const char *startArgList = strchr(startBuf, '(');
3678
3679 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
3680
3681 parenCount++;
3682 // advance the location to startArgList.
3683 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
3684 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
3685
3686 const char *argPtr = startArgList;
3687
3688 while (*argPtr++ && parenCount) {
3689 switch (*argPtr) {
3690 case '^':
3691 // Replace the '^' with '*'.
3692 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
3693 ReplaceText(DeclLoc, 1, "*", 1);
3694 break;
3695 case '(':
3696 parenCount++;
3697 break;
3698 case ')':
3699 parenCount--;
3700 break;
3701 }
3702 }
3703 return;
3704}
3705
3706bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
3707 const FunctionTypeProto *FTP;
3708 const PointerType *PT = QT->getAsPointerType();
3709 if (PT) {
3710 FTP = PT->getPointeeType()->getAsFunctionTypeProto();
3711 } else {
3712 const BlockPointerType *BPT = QT->getAsBlockPointerType();
3713 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
3714 FTP = BPT->getPointeeType()->getAsFunctionTypeProto();
3715 }
3716 if (FTP) {
3717 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
3718 E = FTP->arg_type_end(); I != E; ++I)
3719 if (isBlockPointerType(*I))
3720 return true;
3721 }
3722 return false;
3723}
3724
3725void RewriteObjC::GetExtentOfArgList(const char *Name,
3726 const char *&LParen, const char *&RParen) {
3727 const char *argPtr = strchr(Name, '(');
3728 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
3729
3730 LParen = argPtr; // output the start.
3731 argPtr++; // skip past the left paren.
3732 unsigned parenCount = 1;
3733
3734 while (*argPtr && parenCount) {
3735 switch (*argPtr) {
3736 case '(': parenCount++; break;
3737 case ')': parenCount--; break;
3738 default: break;
3739 }
3740 if (parenCount) argPtr++;
3741 }
3742 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
3743 RParen = argPtr; // output the end
3744}
3745
3746void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
3747 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3748 RewriteBlockPointerFunctionArgs(FD);
3749 return;
3750 }
3751 // Handle Variables and Typedefs.
3752 SourceLocation DeclLoc = ND->getLocation();
3753 QualType DeclT;
3754 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3755 DeclT = VD->getType();
3756 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
3757 DeclT = TDD->getUnderlyingType();
3758 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
3759 DeclT = FD->getType();
3760 else
3761 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
3762
3763 const char *startBuf = SM->getCharacterData(DeclLoc);
3764 const char *endBuf = startBuf;
3765 // scan backward (from the decl location) for the end of the previous decl.
3766 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
3767 startBuf--;
3768
3769 // *startBuf != '^' if we are dealing with a pointer to function that
3770 // may take block argument types (which will be handled below).
3771 if (*startBuf == '^') {
3772 // Replace the '^' with '*', computing a negative offset.
3773 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
3774 ReplaceText(DeclLoc, 1, "*", 1);
3775 }
3776 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
3777 // Replace the '^' with '*' for arguments.
3778 DeclLoc = ND->getLocation();
3779 startBuf = SM->getCharacterData(DeclLoc);
3780 const char *argListBegin, *argListEnd;
3781 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
3782 while (argListBegin < argListEnd) {
3783 if (*argListBegin == '^') {
3784 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
3785 ReplaceText(CaretLoc, 1, "*", 1);
3786 }
3787 argListBegin++;
3788 }
3789 }
3790 return;
3791}
3792
3793void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
3794 // Add initializers for any closure decl refs.
3795 GetBlockDeclRefExprs(Exp->getBody());
3796 if (BlockDeclRefs.size()) {
3797 // Unique all "by copy" declarations.
3798 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3799 if (!BlockDeclRefs[i]->isByRef())
3800 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
3801 // Unique all "by ref" declarations.
3802 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3803 if (BlockDeclRefs[i]->isByRef()) {
3804 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
3805 }
3806 // Find any imported blocks...they will need special attention.
3807 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3808 if (isBlockPointerType(BlockDeclRefs[i]->getType())) {
Steve Naroff00072682008-11-13 17:40:07 +00003809 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff54055232008-10-27 17:20:55 +00003810 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
3811 }
3812 }
3813}
3814
Steve Narofffa15fd92008-10-28 20:29:00 +00003815FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
3816 IdentifierInfo *ID = &Context->Idents.get(name);
3817 QualType FType = Context->getFunctionTypeNoProto(Context->VoidPtrTy);
3818 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
3819 ID, FType, FunctionDecl::Extern, false, 0);
3820}
3821
Steve Naroff8e2f57a2008-10-29 18:15:37 +00003822Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Narofffa15fd92008-10-28 20:29:00 +00003823 Blocks.push_back(Exp);
3824
3825 CollectBlockDeclRefInfo(Exp);
3826 std::string FuncName;
3827
3828 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00003829 FuncName = CurFunctionDef->getNameAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00003830 else if (CurMethodDef) {
Chris Lattner077bf5e2008-11-24 03:33:13 +00003831 FuncName = CurMethodDef->getSelector().getAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00003832 // Convert colons to underscores.
3833 std::string::size_type loc = 0;
3834 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3835 FuncName.replace(loc, 1, "_");
Steve Naroff8e2f57a2008-10-29 18:15:37 +00003836 } else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003837 FuncName = std::string(GlobalVarDecl->getNameAsString());
Steve Narofffa15fd92008-10-28 20:29:00 +00003838
3839 std::string BlockNumber = utostr(Blocks.size()-1);
3840
3841 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
3842 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
3843
3844 // Get a pointer to the function type so we can cast appropriately.
3845 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
3846
3847 FunctionDecl *FD;
3848 Expr *NewRep;
3849
3850 // Simulate a contructor call...
3851 FD = SynthBlockInitFunctionDecl(Tag.c_str());
3852 DeclRefExpr *DRE = new DeclRefExpr(FD, FType, SourceLocation());
3853
3854 llvm::SmallVector<Expr*, 4> InitExprs;
3855
Steve Narofffdc03722008-10-29 21:23:59 +00003856 // Initialize the block function.
Steve Narofffa15fd92008-10-28 20:29:00 +00003857 FD = SynthBlockInitFunctionDecl(Func.c_str());
3858 DeclRefExpr *Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3859 CastExpr *castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00003860 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00003861 InitExprs.push_back(castExpr);
Steve Narofffa15fd92008-10-28 20:29:00 +00003862
3863 if (ImportedBlockDecls.size()) {
3864 std::string Buf = "__" + FuncName + "_block_copy_" + BlockNumber;
Steve Narofffdc03722008-10-29 21:23:59 +00003865 FD = SynthBlockInitFunctionDecl(Buf.c_str());
3866 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3867 castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00003868 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffdc03722008-10-29 21:23:59 +00003869 InitExprs.push_back(castExpr);
3870
Steve Narofffa15fd92008-10-28 20:29:00 +00003871 Buf = "__" + FuncName + "_block_dispose_" + BlockNumber;
Steve Narofffdc03722008-10-29 21:23:59 +00003872 FD = SynthBlockInitFunctionDecl(Buf.c_str());
3873 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3874 castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00003875 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffdc03722008-10-29 21:23:59 +00003876 InitExprs.push_back(castExpr);
Steve Narofffa15fd92008-10-28 20:29:00 +00003877 }
3878 // Add initializers for any closure decl refs.
3879 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00003880 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00003881 // Output all "by copy" declarations.
3882 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3883 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00003884 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00003885 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner8ec03f52008-11-24 03:54:41 +00003886 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00003887 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00003888 } else if (isBlockPointerType((*I)->getType())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003889 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00003890 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3891 Exp = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00003892 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00003893 } else {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003894 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00003895 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00003896 }
Steve Narofffdc03722008-10-29 21:23:59 +00003897 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00003898 }
3899 // Output all "by ref" declarations.
3900 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3901 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003902 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00003903 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3904 Exp = new UnaryOperator(Exp, UnaryOperator::AddrOf,
3905 Context->getPointerType(Exp->getType()),
3906 SourceLocation());
Steve Naroff707b0fe2008-11-14 21:36:12 +00003907 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00003908 }
3909 }
Steve Narofffa15fd92008-10-28 20:29:00 +00003910 NewRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
3911 FType, SourceLocation());
3912 NewRep = new UnaryOperator(NewRep, UnaryOperator::AddrOf,
3913 Context->getPointerType(NewRep->getType()),
3914 SourceLocation());
Steve Naroffb2f9e512008-11-03 23:29:32 +00003915 NewRep = new CStyleCastExpr(FType, NewRep, FType, SourceLocation(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00003916 BlockDeclRefs.clear();
3917 BlockByRefDecls.clear();
3918 BlockByCopyDecls.clear();
3919 ImportedBlockDecls.clear();
3920 return NewRep;
3921}
3922
3923//===----------------------------------------------------------------------===//
3924// Function Body / Expression rewriting
3925//===----------------------------------------------------------------------===//
3926
3927Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
3928 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
3929 isa<DoStmt>(S) || isa<ForStmt>(S))
3930 Stmts.push_back(S);
3931 else if (isa<ObjCForCollectionStmt>(S)) {
3932 Stmts.push_back(S);
3933 ObjCBcLabelNo.push_back(++BcLabelCount);
3934 }
3935
3936 SourceRange OrigStmtRange = S->getSourceRange();
3937
3938 // Perform a bottom up rewrite of all children.
3939 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3940 CI != E; ++CI)
3941 if (*CI) {
3942 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
3943 if (newStmt)
3944 *CI = newStmt;
3945 }
3946
3947 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
3948 // Rewrite the block body in place.
3949 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
3950
3951 // Now we snarf the rewritten text and stash it away for later use.
Steve Naroff8e2f57a2008-10-29 18:15:37 +00003952 std::string Str = Rewrite.getRewritenText(BE->getSourceRange());
3953 RewrittenBlockExprs[BE] = Str;
Steve Narofffa15fd92008-10-28 20:29:00 +00003954
3955 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
3956 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00003957 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00003958 return blockTranscribed;
3959 }
3960 // Handle specific things.
3961 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
3962 return RewriteAtEncode(AtEncode);
3963
3964 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
3965 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
3966
3967 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
3968 return RewriteAtSelector(AtSelector);
3969
3970 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
3971 return RewriteObjCStringLiteral(AtString);
3972
3973 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
3974 // Before we rewrite it, put the original message expression in a comment.
3975 SourceLocation startLoc = MessExpr->getLocStart();
3976 SourceLocation endLoc = MessExpr->getLocEnd();
3977
3978 const char *startBuf = SM->getCharacterData(startLoc);
3979 const char *endBuf = SM->getCharacterData(endLoc);
3980
3981 std::string messString;
3982 messString += "// ";
3983 messString.append(startBuf, endBuf-startBuf+1);
3984 messString += "\n";
3985
3986 // FIXME: Missing definition of
3987 // InsertText(clang::SourceLocation, char const*, unsigned int).
3988 // InsertText(startLoc, messString.c_str(), messString.size());
3989 // Tried this, but it didn't work either...
3990 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
3991 return RewriteMessageExpr(MessExpr);
3992 }
3993
3994 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
3995 return RewriteObjCTryStmt(StmtTry);
3996
3997 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
3998 return RewriteObjCSynchronizedStmt(StmtTry);
3999
4000 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4001 return RewriteObjCThrowStmt(StmtThrow);
4002
4003 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4004 return RewriteObjCProtocolExpr(ProtocolExp);
4005
4006 if (ObjCForCollectionStmt *StmtForCollection =
4007 dyn_cast<ObjCForCollectionStmt>(S))
4008 return RewriteObjCForCollectionStmt(StmtForCollection,
4009 OrigStmtRange.getEnd());
4010 if (BreakStmt *StmtBreakStmt =
4011 dyn_cast<BreakStmt>(S))
4012 return RewriteBreakStmt(StmtBreakStmt);
4013 if (ContinueStmt *StmtContinueStmt =
4014 dyn_cast<ContinueStmt>(S))
4015 return RewriteContinueStmt(StmtContinueStmt);
4016
4017 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
4018 // and cast exprs.
4019 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4020 // FIXME: What we're doing here is modifying the type-specifier that
4021 // precedes the first Decl. In the future the DeclGroup should have
4022 // a separate type-specifier that we can rewrite.
4023 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
4024
4025 // Blocks rewrite rules.
4026 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4027 DI != DE; ++DI) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004028 ScopedDecl *SD = *DI;
4029 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
4030 if (isBlockPointerType(ND->getType()))
4031 RewriteBlockPointerDecl(ND);
4032 else if (ND->getType()->isFunctionPointerType())
4033 CheckFunctionPointerDecl(ND->getType(), ND);
4034 }
4035 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
4036 if (isBlockPointerType(TD->getUnderlyingType()))
4037 RewriteBlockPointerDecl(TD);
4038 else if (TD->getUnderlyingType()->isFunctionPointerType())
4039 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4040 }
4041 }
4042 }
4043
4044 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4045 RewriteObjCQualifiedInterfaceTypes(CE);
4046
4047 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4048 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4049 assert(!Stmts.empty() && "Statement stack is empty");
4050 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4051 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
4052 && "Statement stack mismatch");
4053 Stmts.pop_back();
4054 }
4055 // Handle blocks rewriting.
4056 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4057 if (BDRE->isByRef())
4058 RewriteBlockDeclRefExpr(BDRE);
4059 }
4060 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004061 if (CE->getCallee()->getType()->isBlockPointerType()) {
4062 Stmt *BlockCall = SynthesizeBlockCall(CE);
4063 ReplaceStmt(S, BlockCall);
4064 return BlockCall;
4065 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004066 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00004067 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004068 RewriteCastExpr(CE);
4069 }
4070#if 0
4071 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
4072 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
4073 // Get the new text.
4074 std::string SStr;
4075 llvm::raw_string_ostream Buf(SStr);
4076 Replacement->printPretty(Buf);
4077 const std::string &Str = Buf.str();
4078
4079 printf("CAST = %s\n", &Str[0]);
4080 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4081 delete S;
4082 return Replacement;
4083 }
4084#endif
4085 // Return this stmt unmodified.
4086 return S;
4087}
4088
4089/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4090/// main file of the input.
4091void RewriteObjC::HandleDeclInMainFile(Decl *D) {
4092 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4093 // Since function prototypes don't have ParmDecl's, we check the function
4094 // prototype. This enables us to rewrite function declarations and
4095 // definitions using the same code.
4096 RewriteBlocksInFunctionTypeProto(FD->getType(), FD);
4097
4098 if (Stmt *Body = FD->getBody()) {
4099 CurFunctionDef = FD;
4100 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
4101 // This synthesizes and inserts the block "impl" struct, invoke function,
4102 // and any copy/dispose helper functions.
4103 InsertBlockLiteralsWithinFunction(FD);
4104 CurFunctionDef = 0;
4105 }
4106 return;
4107 }
4108 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4109 if (Stmt *Body = MD->getBody()) {
4110 //Body->dump();
4111 CurMethodDef = MD;
4112 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
4113 InsertBlockLiteralsWithinMethod(MD);
4114 CurMethodDef = 0;
4115 }
4116 }
4117 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
4118 ClassImplementation.push_back(CI);
4119 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
4120 CategoryImplementation.push_back(CI);
4121 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
4122 RewriteForwardClassDecl(CD);
4123 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4124 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004125 if (isBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004126 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004127 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004128 CheckFunctionPointerDecl(VD->getType(), VD);
4129 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00004130 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004131 RewriteCastExpr(CE);
4132 }
4133 }
4134 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004135 if (VD->getInit()) {
4136 GlobalVarDecl = VD;
4137 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Douglas Gregor2e1cd422008-11-17 14:58:09 +00004138 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00004139 VD->getNameAsCString());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004140 GlobalVarDecl = 0;
4141
4142 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00004143 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004144 RewriteCastExpr(CE);
4145 }
4146 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004147 return;
4148 }
4149 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
4150 if (isBlockPointerType(TD->getUnderlyingType()))
4151 RewriteBlockPointerDecl(TD);
4152 else if (TD->getUnderlyingType()->isFunctionPointerType())
4153 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4154 return;
4155 }
4156 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
4157 if (RD->isDefinition()) {
4158 for (RecordDecl::field_const_iterator i = RD->field_begin(),
4159 e = RD->field_end(); i != e; ++i) {
4160 FieldDecl *FD = *i;
4161 if (isBlockPointerType(FD->getType()))
4162 RewriteBlockPointerDecl(FD);
4163 }
4164 }
4165 return;
4166 }
4167 // Nothing yet.
4168}
4169
4170void RewriteObjC::HandleTranslationUnit(TranslationUnit& TU) {
4171 // Get the top-level buffer that this corresponds to.
4172
4173 // Rewrite tabs if we care.
4174 //RewriteTabs();
4175
4176 if (Diags.hasErrorOccurred())
4177 return;
4178
4179 // Create the output file.
4180
4181 llvm::OwningPtr<llvm::raw_ostream> OwnedStream;
4182 llvm::raw_ostream *OutFile;
4183 if (OutFileName == "-") {
4184 OutFile = &llvm::outs();
4185 } else if (!OutFileName.empty()) {
4186 std::string Err;
Daniel Dunbar26fb2722008-11-13 05:09:21 +00004187 OutFile = new llvm::raw_fd_ostream(OutFileName.c_str(), false, Err);
Steve Narofffa15fd92008-10-28 20:29:00 +00004188 OwnedStream.reset(OutFile);
4189 } else if (InFileName == "-") {
4190 OutFile = &llvm::outs();
4191 } else {
4192 llvm::sys::Path Path(InFileName);
4193 Path.eraseSuffix();
4194 Path.appendSuffix("cpp");
4195 std::string Err;
Daniel Dunbar26fb2722008-11-13 05:09:21 +00004196 OutFile = new llvm::raw_fd_ostream(Path.toString().c_str(), false, Err);
Steve Narofffa15fd92008-10-28 20:29:00 +00004197 OwnedStream.reset(OutFile);
4198 }
4199
4200 RewriteInclude();
4201
4202 InsertText(SourceLocation::getFileLoc(MainFileID, 0),
4203 Preamble.c_str(), Preamble.size(), false);
4204
Steve Naroff0aab7962008-11-14 14:10:01 +00004205 if (ClassImplementation.size() || CategoryImplementation.size())
4206 RewriteImplementations();
Steve Narofffa15fd92008-10-28 20:29:00 +00004207
4208 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
4209 // we are done.
4210 if (const RewriteBuffer *RewriteBuf =
4211 Rewrite.getRewriteBufferFor(MainFileID)) {
4212 //printf("Changed:\n");
4213 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4214 } else {
4215 fprintf(stderr, "No changes\n");
4216 }
Steve Narofface66252008-11-13 20:07:04 +00004217
Steve Naroff0aab7962008-11-14 14:10:01 +00004218 if (ClassImplementation.size() || CategoryImplementation.size()) {
4219 // Rewrite Objective-c meta data*
4220 std::string ResultStr;
4221 SynthesizeMetaDataIntoBuffer(ResultStr);
4222 // Emit metadata.
4223 *OutFile << ResultStr;
4224 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004225 OutFile->flush();
4226}
4227