blob: d08633f728b3706b850ac99ac7df0c37486c3a63 [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;
Steve Naroff8c565152008-12-05 17:03:39 +000044 unsigned TryFinallyContainsReturnDiag;
45
Chris Lattner01c57482007-10-17 22:35:30 +000046 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000047 SourceManager *SM;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000048 TranslationUnitDecl *TUDecl;
Chris Lattner8a12c272007-10-11 18:38:32 +000049 unsigned MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000050 const char *MainFileStart, *MainFileEnd;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000051 SourceLocation LastIncLoc;
Steve Naroffba92b2e2008-03-27 22:29:16 +000052
Ted Kremeneka526c5c2008-01-07 19:49:32 +000053 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
54 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
55 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Narofffbfe8252008-05-06 18:26:51 +000056 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000057 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
58 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000059 llvm::SmallVector<Stmt *, 32> Stmts;
60 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroffebf2b562007-10-23 23:50:29 +000061
Steve Naroffd82a9ab2008-03-15 00:55:56 +000062 unsigned NumObjCStringLiterals;
63
Steve Naroffebf2b562007-10-23 23:50:29 +000064 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000065 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000066 FunctionDecl *MsgSendStretFunctionDecl;
67 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000068 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000069 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000070 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000071 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000072 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +000073 FunctionDecl *GetProtocolFunctionDecl;
Steve Naroffc0a123c2008-03-11 17:37:02 +000074 FunctionDecl *SuperContructorFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000075
Steve Naroffbeaf2992007-11-03 11:27:19 +000076 // ObjC string constant support.
Steve Naroff248a7532008-04-15 22:42:06 +000077 VarDecl *ConstantStringClassReference;
Steve Naroffbeaf2992007-11-03 11:27:19 +000078 RecordDecl *NSStringRecord;
Steve Naroffab972d32007-11-04 22:37:50 +000079
Fariborz Jahanianb586cce2008-01-16 00:09:11 +000080 // ObjC foreach break/continue generation support.
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000081 int BcLabelCount;
82
Steve Naroff874e2322007-11-15 10:28:18 +000083 // Needed for super.
Steve Naroff54055232008-10-27 17:20:55 +000084 ObjCMethodDecl *CurMethodDef;
Steve Naroff874e2322007-11-15 10:28:18 +000085 RecordDecl *SuperStructDecl;
Steve Naroffd82a9ab2008-03-15 00:55:56 +000086 RecordDecl *ConstantStringDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000087
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +000088 // Needed for header files being rewritten
89 bool IsHeader;
90
Steve Naroffa7b402d2008-03-28 22:26:09 +000091 std::string InFileName;
92 std::string OutFileName;
93
Steve Naroffba92b2e2008-03-27 22:29:16 +000094 std::string Preamble;
Steve Naroff54055232008-10-27 17:20:55 +000095
96 // Block expressions.
97 llvm::SmallVector<BlockExpr *, 32> Blocks;
98 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
99 llvm::DenseMap<BlockDeclRefExpr *, CallExpr *> BlockCallExprs;
Steve Naroffba92b2e2008-03-27 22:29:16 +0000100
Steve Naroff54055232008-10-27 17:20:55 +0000101 // Block related declarations.
102 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDecls;
103 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDecls;
104 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
105
106 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
107
Steve Naroffc77a6362008-12-04 16:24:46 +0000108 // This maps a property to it's assignment statement.
109 llvm::DenseMap<ObjCPropertyRefExpr *, BinaryOperator *> PropSetters;
Steve Naroff4c3580e2008-12-04 23:50:32 +0000110 // This maps an original source AST to it's rewritten form. This allows
111 // us to avoid rewriting the same node twice (which is very uncommon).
112 // This is needed to support some of the exotic property rewriting.
113 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Naroff15f081d2008-12-03 00:56:33 +0000114
Steve Naroff54055232008-10-27 17:20:55 +0000115 FunctionDecl *CurFunctionDef;
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000116 VarDecl *GlobalVarDecl;
117
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000118 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +0000119 public:
Ted Kremeneke3a61982008-05-31 20:11:04 +0000120 virtual void Initialize(ASTContext &context);
121
122 virtual void InitializeTU(TranslationUnit &TU) {
123 TU.SetOwnsDecls(false);
124 Initialize(TU.getContext());
125 }
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000126
Chris Lattner8a12c272007-10-11 18:38:32 +0000127
Chris Lattnerf04da132007-10-24 17:06:59 +0000128 // Top Level Driver code.
129 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000130 void HandleDeclInMainFile(Decl *D);
Steve Naroffb29b4272008-04-14 22:03:09 +0000131 RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000132 Diagnostic &D, const LangOptions &LOpts);
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000133
134 ~RewriteObjC() {}
135
136 virtual void HandleTranslationUnit(TranslationUnit& TU);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000137
138 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000139 Stmt *ReplacingStmt = ReplacedNodes[Old];
140
141 if (ReplacingStmt)
142 return; // We can't rewrite the same node twice.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000143
Steve Naroff4c3580e2008-12-04 23:50:32 +0000144 // If replacement succeeded or warning disabled return with no warning.
145 if (!Rewrite.ReplaceStmt(Old, New)) {
146 ReplacedNodes[Old] = New;
147 return;
148 }
149 if (SilenceRewriteMacroWarning)
150 return;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000151 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
152 << Old->getSourceRange();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000153 }
154
Steve Naroffba92b2e2008-03-27 22:29:16 +0000155 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
156 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000157 // If insertion succeeded or warning disabled return with no warning.
Steve Naroffba92b2e2008-03-27 22:29:16 +0000158 if (!Rewrite.InsertText(Loc, StrData, StrLen, InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000159 SilenceRewriteMacroWarning)
160 return;
161
162 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
163 }
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000164
Chris Lattneraadaf782008-01-31 19:51:04 +0000165 void RemoveText(SourceLocation Loc, unsigned StrLen) {
166 // If removal succeeded or warning disabled return with no warning.
167 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
168 return;
169
170 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
171 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000172
Chris Lattneraadaf782008-01-31 19:51:04 +0000173 void ReplaceText(SourceLocation Start, unsigned OrigLength,
174 const char *NewStr, unsigned NewLength) {
175 // If removal succeeded or warning disabled return with no warning.
176 if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength) ||
177 SilenceRewriteMacroWarning)
178 return;
179
180 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
181 }
182
Chris Lattnerf04da132007-10-24 17:06:59 +0000183 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000184 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000185 void RewriteInclude();
Chris Lattnerf04da132007-10-24 17:06:59 +0000186 void RewriteTabs();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000187 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffa0876e82008-12-02 17:36:43 +0000188 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
189 ObjCImplementationDecl *IMD,
190 ObjCCategoryImplDecl *CID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000191 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000192 void RewriteImplementationDecl(NamedDecl *Dcl);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000193 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
194 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
195 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
196 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
197 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Chris Lattner55d13b42008-03-16 21:23:50 +0000198 void RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +0000199 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000200 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroff4f95b752008-07-29 18:15:38 +0000201 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffd5255f52007-11-01 13:24:47 +0000202 bool needToScanForQualifiers(QualType T);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000203 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000204 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000205 QualType getConstantStringStructType();
Steve Naroffbaf58c32008-05-31 14:15:04 +0000206 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Chris Lattner311ff022007-10-16 22:36:42 +0000207
Chris Lattnerf04da132007-10-24 17:06:59 +0000208 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000209 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroffc77a6362008-12-04 16:24:46 +0000210 void CollectPropertySetters(Stmt *S);
211
Chris Lattnere64b7772007-10-24 16:57:36 +0000212 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000213 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart);
Steve Naroffc77a6362008-12-04 16:24:46 +0000214 Stmt *RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr);
215 Stmt *RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt);
Steve Naroffb42f8412007-11-05 14:50:49 +0000216 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000217 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000218 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000219 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroff8c565152008-12-05 17:03:39 +0000220 void WarnAboutReturnGotoContinueOrBreakStmts(Stmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000221 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000222 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000223 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
224 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
225 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000226 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
227 SourceLocation OrigEnd);
Steve Naroff934f2762007-10-24 22:48:43 +0000228 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
229 Expr **args, unsigned nargs);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000230 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000231 Stmt *RewriteBreakStmt(BreakStmt *S);
232 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000233 void SynthCountByEnumWithState(std::string &buf);
234
Steve Naroff09b266e2007-10-30 23:14:51 +0000235 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000236 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000237 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000238 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000239 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000240 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000241 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000242 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000243 void SynthGetProtocolFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000244 void SynthSuperContructorFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000245
Chris Lattnerf04da132007-10-24 17:06:59 +0000246 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000247 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000248 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000249
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000250 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000251 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000252
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000253 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
254 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000255 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000256 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000257 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000258 const char *ClassName,
259 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000260
Chris Lattner780f3292008-07-21 21:32:27 +0000261 void RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl>
262 &Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000263 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000264 const char *ClassName,
265 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000266 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000267 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000268 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
269 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000270 std::string &Result);
Steve Narofface66252008-11-13 20:07:04 +0000271 void RewriteImplementations();
272 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Steve Naroff54055232008-10-27 17:20:55 +0000273
274 // Block rewriting.
275 void RewriteBlocksInFunctionTypeProto(QualType funcType, NamedDecl *D);
276 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
277
278 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
279 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
280
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000281 // Block specific rewrite rules.
Steve Naroff54055232008-10-27 17:20:55 +0000282 void RewriteBlockCall(CallExpr *Exp);
283 void RewriteBlockPointerDecl(NamedDecl *VD);
284 void RewriteBlockDeclRefExpr(BlockDeclRefExpr *VD);
285 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
286
287 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
288 const char *funcName, std::string Tag);
289 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
290 const char *funcName, std::string Tag);
291 std::string SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
292 bool hasCopyDisposeHelpers);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +0000293 Stmt *SynthesizeBlockCall(CallExpr *Exp);
Steve Naroff54055232008-10-27 17:20:55 +0000294 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
295 const char *FunName);
296
297 void CollectBlockDeclRefInfo(BlockExpr *Exp);
298 void GetBlockCallExprs(Stmt *S);
299 void GetBlockDeclRefExprs(Stmt *S);
300
301 // We avoid calling Type::isBlockPointerType(), since it operates on the
302 // canonical type. We only care if the top-level type is a closure pointer.
303 bool isBlockPointerType(QualType T) { return isa<BlockPointerType>(T); }
304
305 // FIXME: This predicate seems like it would be useful to add to ASTContext.
306 bool isObjCType(QualType T) {
307 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
308 return false;
309
310 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
311
312 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
313 OCT == Context->getCanonicalType(Context->getObjCClassType()))
314 return true;
315
316 if (const PointerType *PT = OCT->getAsPointerType()) {
317 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
318 isa<ObjCQualifiedIdType>(PT->getPointeeType()))
319 return true;
320 }
321 return false;
322 }
323 bool PointerTypeTakesAnyBlockArguments(QualType QT);
324 void GetExtentOfArgList(const char *Name, const char *&LParen, const char *&RParen);
Steve Naroffb2f9e512008-11-03 23:29:32 +0000325 void RewriteCastExpr(CStyleCastExpr *CE);
Steve Narofffa15fd92008-10-28 20:29:00 +0000326
327 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000328 Stmt *SynthBlockInitExpr(BlockExpr *Exp);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000329 };
330}
331
Steve Naroff54055232008-10-27 17:20:55 +0000332void RewriteObjC::RewriteBlocksInFunctionTypeProto(QualType funcType,
333 NamedDecl *D) {
334 if (FunctionTypeProto *fproto = dyn_cast<FunctionTypeProto>(funcType)) {
335 for (FunctionTypeProto::arg_type_iterator I = fproto->arg_type_begin(),
336 E = fproto->arg_type_end(); I && (I != E); ++I)
337 if (isBlockPointerType(*I)) {
338 // All the args are checked/rewritten. Don't call twice!
339 RewriteBlockPointerDecl(D);
340 break;
341 }
342 }
343}
344
345void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
346 const PointerType *PT = funcType->getAsPointerType();
347 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
348 RewriteBlocksInFunctionTypeProto(PT->getPointeeType(), ND);
349}
350
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000351static bool IsHeaderFile(const std::string &Filename) {
352 std::string::size_type DotPos = Filename.rfind('.');
353
354 if (DotPos == std::string::npos) {
355 // no file extension
356 return false;
357 }
358
359 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
360 // C header: .h
361 // C++ header: .hh or .H;
362 return Ext == "h" || Ext == "hh" || Ext == "H";
363}
364
Steve Naroffb29b4272008-04-14 22:03:09 +0000365RewriteObjC::RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000366 Diagnostic &D, const LangOptions &LOpts)
367 : Diags(D), LangOpts(LOpts) {
368 IsHeader = IsHeaderFile(inFile);
369 InFileName = inFile;
370 OutFileName = outFile;
371 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
372 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff8c565152008-12-05 17:03:39 +0000373 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
374 "rewriter doesn't support user-specified control flow semantics for @try/@finally (code may not execute properly)");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000375}
376
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000377ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
Chris Lattnerc68ab772008-03-22 00:08:40 +0000378 const std::string& OutFile,
Steve Naroff4f943c22008-03-10 20:43:59 +0000379 Diagnostic &Diags,
380 const LangOptions &LOpts) {
Steve Naroffb29b4272008-04-14 22:03:09 +0000381 return new RewriteObjC(InFile, OutFile, Diags, LOpts);
Chris Lattnere365c502007-11-30 22:25:36 +0000382}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000383
Steve Naroffb29b4272008-04-14 22:03:09 +0000384void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000385 Context = &context;
386 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000387 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000388 MsgSendFunctionDecl = 0;
389 MsgSendSuperFunctionDecl = 0;
390 MsgSendStretFunctionDecl = 0;
391 MsgSendSuperStretFunctionDecl = 0;
392 MsgSendFpretFunctionDecl = 0;
393 GetClassFunctionDecl = 0;
394 GetMetaClassFunctionDecl = 0;
395 SelGetUidFunctionDecl = 0;
396 CFStringFunctionDecl = 0;
397 GetProtocolFunctionDecl = 0;
398 ConstantStringClassReference = 0;
399 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000400 CurMethodDef = 0;
401 CurFunctionDef = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000402 SuperStructDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000403 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000404 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000405 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000406 NumObjCStringLiterals = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000407
408 // Get the ID and start/end of the main file.
409 MainFileID = SM->getMainFileID();
410 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
411 MainFileStart = MainBuf->getBufferStart();
412 MainFileEnd = MainBuf->getBufferEnd();
Steve Naroffba92b2e2008-03-27 22:29:16 +0000413
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000414 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000415
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000416 // declaring objc_selector outside the parameter list removes a silly
417 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000418 if (IsHeader)
419 Preamble = "#pragma once\n";
420 Preamble += "struct objc_selector; struct objc_class;\n";
421 Preamble += "#ifndef OBJC_SUPER\n";
422 Preamble += "struct objc_super { struct objc_object *object; ";
423 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000424 if (LangOpts.Microsoft) {
425 // Add a constructor for creating temporary objects.
Steve Naroffba92b2e2008-03-27 22:29:16 +0000426 Preamble += "objc_super(struct objc_object *o, struct objc_object *s) : ";
427 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000428 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000429 Preamble += "};\n";
430 Preamble += "#define OBJC_SUPER\n";
431 Preamble += "#endif\n";
432 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
433 Preamble += "typedef struct objc_object Protocol;\n";
434 Preamble += "#define _REWRITER_typedef_Protocol\n";
435 Preamble += "#endif\n";
Steve Naroff3c64d9e2008-03-12 13:19:12 +0000436 if (LangOpts.Microsoft)
Steve Naroff69c827f2008-05-06 22:45:19 +0000437 Preamble += "#define __OBJC_RW_EXTERN extern \"C\" __declspec(dllimport)\n";
438 else
439 Preamble += "#define __OBJC_RW_EXTERN extern\n";
440 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000441 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000442 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000443 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000444 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000445 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000446 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000447 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff1284db82008-05-08 22:02:18 +0000448 Preamble += "__OBJC_RW_EXTERN double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000449 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff0757612008-05-08 17:52:16 +0000450 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000451 Preamble += "(const char *);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000452 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000453 Preamble += "(const char *);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000454 Preamble += "__OBJC_RW_EXTERN void objc_exception_throw(struct objc_object *);\n";
455 Preamble += "__OBJC_RW_EXTERN void objc_exception_try_enter(void *);\n";
456 Preamble += "__OBJC_RW_EXTERN void objc_exception_try_exit(void *);\n";
457 Preamble += "__OBJC_RW_EXTERN struct objc_object *objc_exception_extract(void *);\n";
458 Preamble += "__OBJC_RW_EXTERN int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000459 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000460 // @synchronized hooks.
461 Preamble += "__OBJC_RW_EXTERN void objc_sync_enter(struct objc_object *);\n";
462 Preamble += "__OBJC_RW_EXTERN void objc_sync_exit(struct objc_object *);\n";
Steve Naroff69c827f2008-05-06 22:45:19 +0000463 Preamble += "__OBJC_RW_EXTERN Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000464 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
465 Preamble += "struct __objcFastEnumerationState {\n\t";
466 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000467 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000468 Preamble += "unsigned long *mutationsPtr;\n\t";
469 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff73ebd6d2008-06-02 20:23:21 +0000470 Preamble += "__OBJC_RW_EXTERN void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000471 Preamble += "#define __FASTENUMERATIONSTATE\n";
472 Preamble += "#endif\n";
473 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
474 Preamble += "struct __NSConstantStringImpl {\n";
475 Preamble += " int *isa;\n";
476 Preamble += " int flags;\n";
477 Preamble += " char *str;\n";
478 Preamble += " long length;\n";
479 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000480 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
481 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
482 Preamble += "#else\n";
Steve Naroff73b17cd2008-05-15 21:12:10 +0000483 Preamble += "__OBJC_RW_EXTERN int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000484 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000485 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
486 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000487 // Blocks preamble.
488 Preamble += "#ifndef BLOCK_IMPL\n";
489 Preamble += "#define BLOCK_IMPL\n";
490 Preamble += "struct __block_impl {\n";
491 Preamble += " void *isa;\n";
492 Preamble += " int Flags;\n";
493 Preamble += " int Size;\n";
494 Preamble += " void *FuncPtr;\n";
495 Preamble += "};\n";
496 Preamble += "enum {\n";
497 Preamble += " BLOCK_HAS_COPY_DISPOSE = (1<<25),\n";
498 Preamble += " BLOCK_IS_GLOBAL = (1<<28)\n";
499 Preamble += "};\n";
Steve Naroff54055232008-10-27 17:20:55 +0000500 Preamble += "// Runtime copy/destroy helper functions\n";
501 Preamble += "__OBJC_RW_EXTERN void _Block_copy_assign(void *, void *);\n";
502 Preamble += "__OBJC_RW_EXTERN void _Block_byref_assign_copy(void *, void *);\n";
503 Preamble += "__OBJC_RW_EXTERN void _Block_destroy(void *);\n";
504 Preamble += "__OBJC_RW_EXTERN void _Block_byref_release(void *);\n";
505 Preamble += "__OBJC_RW_EXTERN void *_NSConcreteGlobalBlock;\n";
506 Preamble += "__OBJC_RW_EXTERN void *_NSConcreteStackBlock;\n";
507 Preamble += "#endif\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000508 if (LangOpts.Microsoft) {
509 Preamble += "#undef __OBJC_RW_EXTERN\n";
510 Preamble += "#define __attribute__(X)\n";
511 }
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000512}
513
514
Chris Lattnerf04da132007-10-24 17:06:59 +0000515//===----------------------------------------------------------------------===//
516// Top Level Driver Code
517//===----------------------------------------------------------------------===//
518
Steve Naroffb29b4272008-04-14 22:03:09 +0000519void RewriteObjC::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000520 // Two cases: either the decl could be in the main file, or it could be in a
521 // #included file. If the former, rewrite it now. If the later, check to see
522 // if we rewrote the #include/#import.
523 SourceLocation Loc = D->getLocation();
524 Loc = SM->getLogicalLoc(Loc);
525
526 // If this is for a builtin, ignore it.
527 if (Loc.isInvalid()) return;
528
Steve Naroffebf2b562007-10-23 23:50:29 +0000529 // Look for built-in declarations that we need to refer during the rewrite.
530 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000531 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000532 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000533 // declared in <Foundation/NSString.h>
Chris Lattner8ec03f52008-11-24 03:54:41 +0000534 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000535 ConstantStringClassReference = FVD;
536 return;
537 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000538 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000539 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000540 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000541 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000542 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000543 RewriteProtocolDecl(PD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000544 } else if (ObjCForwardProtocolDecl *FP =
545 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000546 RewriteForwardProtocolDecl(FP);
Steve Naroffebf2b562007-10-23 23:50:29 +0000547 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000548 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000549 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000550 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000551}
552
Chris Lattnerf04da132007-10-24 17:06:59 +0000553//===----------------------------------------------------------------------===//
554// Syntactic (non-AST) Rewriting Code
555//===----------------------------------------------------------------------===//
556
Steve Naroffb29b4272008-04-14 22:03:09 +0000557void RewriteObjC::RewriteInclude() {
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000558 SourceLocation LocStart = SourceLocation::getFileLoc(MainFileID, 0);
559 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
560 const char *MainBufStart = MainBuf.first;
561 const char *MainBufEnd = MainBuf.second;
562 size_t ImportLen = strlen("import");
563 size_t IncludeLen = strlen("include");
564
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000565 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000566 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
567 if (*BufPtr == '#') {
568 if (++BufPtr == MainBufEnd)
569 return;
570 while (*BufPtr == ' ' || *BufPtr == '\t')
571 if (++BufPtr == MainBufEnd)
572 return;
573 if (!strncmp(BufPtr, "import", ImportLen)) {
574 // replace import with include
575 SourceLocation ImportLoc =
576 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattneraadaf782008-01-31 19:51:04 +0000577 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000578 BufPtr += ImportLen;
579 }
580 }
581 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000582}
583
Steve Naroffb29b4272008-04-14 22:03:09 +0000584void RewriteObjC::RewriteTabs() {
Chris Lattnerf04da132007-10-24 17:06:59 +0000585 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
586 const char *MainBufStart = MainBuf.first;
587 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000588
Chris Lattnerf04da132007-10-24 17:06:59 +0000589 // Loop over the whole file, looking for tabs.
590 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
591 if (*BufPtr != '\t')
592 continue;
593
594 // Okay, we found a tab. This tab will turn into at least one character,
595 // but it depends on which 'virtual column' it is in. Compute that now.
596 unsigned VCol = 0;
597 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
598 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
599 ++VCol;
600
601 // Okay, now that we know the virtual column, we know how many spaces to
602 // insert. We assume 8-character tab-stops.
603 unsigned Spaces = 8-(VCol & 7);
604
605 // Get the location of the tab.
606 SourceLocation TabLoc =
607 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
608
609 // Rewrite the single tab character into a sequence of spaces.
Chris Lattneraadaf782008-01-31 19:51:04 +0000610 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerf04da132007-10-24 17:06:59 +0000611 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000612}
613
Steve Naroffeb0646c2008-12-02 15:48:25 +0000614static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
615 ObjCIvarDecl *OID) {
616 std::string S;
617 S = "((struct ";
618 S += ClassDecl->getIdentifier()->getName();
619 S += "_IMPL *)self)->";
620 S += OID->getNameAsCString();
621 return S;
622}
623
Steve Naroffa0876e82008-12-02 17:36:43 +0000624void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
625 ObjCImplementationDecl *IMD,
626 ObjCCategoryImplDecl *CID) {
Steve Naroffd40910b2008-12-01 20:33:01 +0000627 SourceLocation startLoc = PID->getLocStart();
628 InsertText(startLoc, "// ", 3);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000629 const char *startBuf = SM->getCharacterData(startLoc);
630 assert((*startBuf == '@') && "bogus @synthesize location");
631 const char *semiBuf = strchr(startBuf, ';');
632 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
633 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
634
635 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
636 return; // FIXME: is this correct?
637
638 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000639 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000640 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000641 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000642
643 if (!OID)
644 return;
645
646 std::string Getr;
647 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
648 Getr += "{ ";
649 // Synthesize an explicit cast to gain access to the ivar.
Steve Naroff3539cdb2008-12-02 17:54:50 +0000650 // FIXME: deal with code generation implications for various property
651 // attributes (copy, retain, nonatomic).
652 // See objc-act.c:objc_synthesize_new_getter() for details.
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000653 Getr += "return " + getIvarAccessString(ClassDecl, OID);
654 Getr += "; }";
Steve Naroffeb0646c2008-12-02 15:48:25 +0000655 InsertText(onePastSemiLoc, Getr.c_str(), Getr.size());
Steve Naroffa0876e82008-12-02 17:36:43 +0000656
657 // Add the rewritten getter to trigger meta data generation. An alternate, and
658 // possibly cleaner approach is to hack RewriteObjCMethodsMetaData() to deal
659 // with properties explicitly. The following addInstanceMethod() required far
660 // less code change (and actually models what the rewriter is doing).
661 if (IMD)
662 IMD->addInstanceMethod(PD->getGetterMethodDecl());
663 else
664 CID->addInstanceMethod(PD->getGetterMethodDecl());
Steve Naroffeb0646c2008-12-02 15:48:25 +0000665
666 if (PD->isReadOnly())
667 return;
668
669 // Generate the 'setter' function.
670 std::string Setr;
671 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000672 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000673 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff3539cdb2008-12-02 17:54:50 +0000674 // FIXME: deal with code generation implications for various property
675 // attributes (copy, retain, nonatomic).
Steve Naroff15f081d2008-12-03 00:56:33 +0000676 // See objc-act.c:objc_synthesize_new_setter() for details.
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000677 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
678 Setr += OID->getNameAsCString();
679 Setr += "; }";
Steve Naroffeb0646c2008-12-02 15:48:25 +0000680 InsertText(onePastSemiLoc, Setr.c_str(), Setr.size());
Steve Naroffa0876e82008-12-02 17:36:43 +0000681
682 // Add the rewritten setter to trigger meta data generation.
683 if (IMD)
684 IMD->addInstanceMethod(PD->getSetterMethodDecl());
685 else
686 CID->addInstanceMethod(PD->getSetterMethodDecl());
Steve Naroffd40910b2008-12-01 20:33:01 +0000687}
Chris Lattner8a12c272007-10-11 18:38:32 +0000688
Steve Naroffb29b4272008-04-14 22:03:09 +0000689void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000690 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000691 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerf04da132007-10-24 17:06:59 +0000692
693 // Get the start location and compute the semi location.
694 SourceLocation startLoc = ClassDecl->getLocation();
695 const char *startBuf = SM->getCharacterData(startLoc);
696 const char *semiPtr = strchr(startBuf, ';');
697
698 // Translate to typedef's that forward reference structs with the same name
699 // as the class. As a convenience, we include the original declaration
700 // as a comment.
701 std::string typedefString;
702 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000703 typedefString.append(startBuf, semiPtr-startBuf+1);
704 typedefString += "\n";
705 for (int i = 0; i < numDecls; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000706 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000707 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000708 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000709 typedefString += "\n";
710 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000711 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000712 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000713 typedefString += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000714 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000715 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000716 }
717
718 // Replace the @class with typedefs corresponding to the classes.
Chris Lattneraadaf782008-01-31 19:51:04 +0000719 ReplaceText(startLoc, semiPtr-startBuf+1,
720 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000721}
722
Steve Naroffb29b4272008-04-14 22:03:09 +0000723void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000724 SourceLocation LocStart = Method->getLocStart();
725 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000726
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000727 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
Steve Naroff94ac21e2008-10-21 13:37:27 +0000728 InsertText(LocStart, "#if 0\n", 6);
729 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000730 } else {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000731 InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000732 }
733}
734
Steve Naroffb29b4272008-04-14 22:03:09 +0000735void RewriteObjC::RewriteProperties(unsigned nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000736{
Chris Lattner55d13b42008-03-16 21:23:50 +0000737 for (unsigned i = 0; i < nProperties; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000738 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000739 SourceLocation Loc = Property->getLocation();
740
Chris Lattneraadaf782008-01-31 19:51:04 +0000741 ReplaceText(Loc, 0, "// ", 3);
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000742
743 // FIXME: handle properties that are declared across multiple lines.
744 }
745}
746
Steve Naroffb29b4272008-04-14 22:03:09 +0000747void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000748 SourceLocation LocStart = CatDecl->getLocStart();
749
750 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000751 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000752
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000753 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000754 E = CatDecl->instmeth_end(); I != E; ++I)
755 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000756 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000757 E = CatDecl->classmeth_end(); I != E; ++I)
758 RewriteMethodDeclaration(*I);
759
Steve Naroff423cb562007-10-30 13:30:57 +0000760 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000761 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000762}
763
Steve Naroffb29b4272008-04-14 22:03:09 +0000764void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000765 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000766
Steve Naroff752d6ef2007-10-30 16:42:30 +0000767 SourceLocation LocStart = PDecl->getLocStart();
768
769 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000770 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000771
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000772 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000773 E = PDecl->instmeth_end(); I != E; ++I)
774 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000775 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000776 E = PDecl->classmeth_end(); I != E; ++I)
777 RewriteMethodDeclaration(*I);
778
Steve Naroff752d6ef2007-10-30 16:42:30 +0000779 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000780 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattneraadaf782008-01-31 19:51:04 +0000781 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000782
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000783 // Must comment out @optional/@required
784 const char *startBuf = SM->getCharacterData(LocStart);
785 const char *endBuf = SM->getCharacterData(LocEnd);
786 for (const char *p = startBuf; p < endBuf; p++) {
787 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
788 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000789 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000790 ReplaceText(OptionalLoc, strlen("@optional"),
791 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000792
793 }
794 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
795 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000796 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000797 ReplaceText(OptionalLoc, strlen("@required"),
798 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000799
800 }
801 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000802}
803
Steve Naroffb29b4272008-04-14 22:03:09 +0000804void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000805 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000806 if (LocStart.isInvalid())
807 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000808 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000809 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000810}
811
Steve Naroffb29b4272008-04-14 22:03:09 +0000812void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000813 std::string &ResultStr) {
Steve Naroffced80a82008-10-30 12:09:33 +0000814 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroff76e429d2008-07-16 14:40:40 +0000815 const FunctionType *FPRetType = 0;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000816 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000817 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000818 ResultStr += "id";
Steve Naroff76e429d2008-07-16 14:40:40 +0000819 else if (OMD->getResultType()->isFunctionPointerType()) {
820 // needs special handling, since pointer-to-functions have special
821 // syntax (where a decaration models use).
822 QualType retType = OMD->getResultType();
823 if (const PointerType* PT = retType->getAsPointerType()) {
824 QualType PointeeTy = PT->getPointeeType();
825 if ((FPRetType = PointeeTy->getAsFunctionType())) {
826 ResultStr += FPRetType->getResultType().getAsString();
827 ResultStr += "(*";
828 }
829 }
830 } else
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000831 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000832 ResultStr += " ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000833
834 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000835 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000836
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000837 if (OMD->isInstance())
838 NameStr += "_I_";
839 else
840 NameStr += "_C_";
841
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000842 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000843 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000844
845 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000846 if (ObjCCategoryImplDecl *CID =
847 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000848 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000849 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000850 }
Steve Naroff563b8282008-04-04 22:23:44 +0000851 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +0000852 {
853 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000854 int len = selString.size();
855 for (int i = 0; i < len; i++)
856 if (selString[i] == ':')
857 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000858 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000859 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000860 // Remember this name for metadata emission
861 MethodInternalNames[OMD] = NameStr;
862 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000863
864 // Rewrite arguments
865 ResultStr += "(";
866
867 // invisible arguments
868 if (OMD->isInstance()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000869 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000870 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +0000871 if (!LangOpts.Microsoft) {
872 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
873 ResultStr += "struct ";
874 }
875 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000876 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000877 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000878 }
879 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000880 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000881
882 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000883 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000884 ResultStr += " _cmd";
885
886 // Method arguments.
Chris Lattner58cce3b2008-03-16 01:07:14 +0000887 for (unsigned i = 0; i < OMD->getNumParams(); i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000888 ParmVarDecl *PDecl = OMD->getParamDecl(i);
889 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +0000890 if (PDecl->getType()->isObjCQualifiedIdType()) {
891 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000892 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +0000893 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000894 std::string Name = PDecl->getNameAsString();
Steve Naroffc8ad87b2008-10-30 14:45:29 +0000895 if (isBlockPointerType(PDecl->getType())) {
896 // Make sure we convert "t (^)(...)" to "t (*)(...)".
897 const BlockPointerType *BPT = PDecl->getType()->getAsBlockPointerType();
898 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name);
899 } else
900 PDecl->getType().getAsStringInternal(Name);
Steve Naroff543409e2008-04-18 21:13:19 +0000901 ResultStr += Name;
902 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000903 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +0000904 if (OMD->isVariadic())
905 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000906 ResultStr += ") ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000907
Steve Naroff76e429d2008-07-16 14:40:40 +0000908 if (FPRetType) {
909 ResultStr += ")"; // close the precedence "scope" for "*".
910
911 // Now, emit the argument types (if any).
912 if (const FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(FPRetType)) {
913 ResultStr += "(";
914 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
915 if (i) ResultStr += ", ";
916 std::string ParamStr = FT->getArgType(i).getAsString();
917 ResultStr += ParamStr;
918 }
919 if (FT->isVariadic()) {
920 if (FT->getNumArgs()) ResultStr += ", ";
921 ResultStr += "...";
922 }
923 ResultStr += ")";
924 } else {
925 ResultStr += "()";
926 }
927 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000928}
Steve Naroffb29b4272008-04-14 22:03:09 +0000929void RewriteObjC::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000930 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
931 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000932
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000933 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000934 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000935 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000936 InsertText(CID->getLocStart(), "// ", 3);
Steve Narofface66252008-11-13 20:07:04 +0000937
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000938 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000939 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
940 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000941 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000942 ObjCMethodDecl *OMD = *I;
943 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000944 SourceLocation LocStart = OMD->getLocStart();
945 SourceLocation LocEnd = OMD->getBody()->getLocStart();
946
947 const char *startBuf = SM->getCharacterData(LocStart);
948 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000949 ReplaceText(LocStart, endBuf-startBuf,
950 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000951 }
952
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000953 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000954 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
955 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000956 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000957 ObjCMethodDecl *OMD = *I;
958 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000959 SourceLocation LocStart = OMD->getLocStart();
960 SourceLocation LocEnd = OMD->getBody()->getLocStart();
961
962 const char *startBuf = SM->getCharacterData(LocStart);
963 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000964 ReplaceText(LocStart, endBuf-startBuf,
965 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000966 }
Steve Naroffd40910b2008-12-01 20:33:01 +0000967 for (ObjCCategoryImplDecl::propimpl_iterator
968 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
969 E = IMD ? IMD->propimpl_end() : CID->propimpl_end(); I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +0000970 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +0000971 }
972
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000973 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000974 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000975 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000976 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000977}
978
Steve Naroffb29b4272008-04-14 22:03:09 +0000979void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000980 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000981 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000982 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +0000983 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000984 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000985 ResultStr += "\n";
986 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000987 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000988 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000989 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000990 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000991 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000992 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000993 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000994 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000995 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Narofff908a872007-10-30 02:23:23 +0000996
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000997 RewriteProperties(ClassDecl->getNumPropertyDecl(),
998 ClassDecl->getPropertyDecl());
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000999 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001000 E = ClassDecl->instmeth_end(); I != E; ++I)
1001 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001002 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001003 E = ClassDecl->classmeth_end(); I != E; ++I)
1004 RewriteMethodDeclaration(*I);
1005
Steve Naroff2feac5e2007-10-30 03:43:13 +00001006 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +00001007 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +00001008}
1009
Steve Naroffc77a6362008-12-04 16:24:46 +00001010Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt) {
1011 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1012 // This allows us to reuse all the fun and games in SynthMessageExpr().
1013 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1014 ObjCMessageExpr *MsgExpr;
1015 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1016 llvm::SmallVector<Expr *, 1> ExprVec;
1017 ExprVec.push_back(newStmt);
1018
1019 MsgExpr = new ObjCMessageExpr(PropRefExpr->getBase(),
1020 PDecl->getSetterName(), PDecl->getType(),
1021 PDecl->getSetterMethodDecl(),
1022 SourceLocation(), SourceLocation(),
1023 &ExprVec[0], 1);
1024 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
1025
1026 // Now do the actual rewrite.
1027 ReplaceStmt(BinOp, ReplacingStmt);
1028 delete BinOp;
1029 delete MsgExpr;
1030 return ReplacingStmt;
Steve Naroff15f081d2008-12-03 00:56:33 +00001031}
1032
Steve Naroffc77a6362008-12-04 16:24:46 +00001033Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Naroff15f081d2008-12-03 00:56:33 +00001034 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1035 // This allows us to reuse all the fun and games in SynthMessageExpr().
1036 ObjCMessageExpr *MsgExpr;
1037 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1038
1039 MsgExpr = new ObjCMessageExpr(PropRefExpr->getBase(),
1040 PDecl->getGetterName(), PDecl->getType(),
1041 PDecl->getGetterMethodDecl(),
1042 SourceLocation(), SourceLocation(),
1043 0, 0);
1044
Steve Naroff4c3580e2008-12-04 23:50:32 +00001045 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroffc77a6362008-12-04 16:24:46 +00001046
Steve Naroff15f081d2008-12-03 00:56:33 +00001047 ReplaceStmt(PropRefExpr, ReplacingStmt);
Steve Naroff4c3580e2008-12-04 23:50:32 +00001048
Steve Naroff15f081d2008-12-03 00:56:33 +00001049 // delete PropRefExpr; elsewhere...
1050 delete MsgExpr;
1051 return ReplacingStmt;
1052}
1053
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001054Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
1055 SourceLocation OrigStart) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001056 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff54055232008-10-27 17:20:55 +00001057 if (CurMethodDef) {
Steve Naroff05b8c782008-03-12 00:25:36 +00001058 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +00001059 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
1060 // lookup which class implements the instance variable.
1061 ObjCInterfaceDecl *clsDeclared = 0;
1062 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
1063 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1064
1065 // Synthesize an explicit cast to gain access to the ivar.
1066 std::string RecName = clsDeclared->getIdentifier()->getName();
1067 RecName += "_IMPL";
1068 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001069 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001070 SourceLocation(), II);
Steve Narofff0757612008-05-08 17:52:16 +00001071 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1072 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001073 CastExpr *castExpr = new CStyleCastExpr(castT, IV->getBase(), castT,
Steve Naroffb2f9e512008-11-03 23:29:32 +00001074 SourceLocation(), SourceLocation());
Steve Narofff0757612008-05-08 17:52:16 +00001075 // Don't forget the parens to enforce the proper binding.
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001076 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
1077 IV->getBase()->getLocEnd(),
1078 castExpr);
Steve Narofff0757612008-05-08 17:52:16 +00001079 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +00001080 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001081 MemberExpr *ME = new MemberExpr(PE, true, D, IV->getLocation(),
1082 D->getType());
Steve Narofff0757612008-05-08 17:52:16 +00001083 ReplaceStmt(IV, ME);
Steve Naroff4c3580e2008-12-04 23:50:32 +00001084 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Narofff0757612008-05-08 17:52:16 +00001085 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001086 }
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001087
1088 ReplaceStmt(IV->getBase(), PE);
1089 // Cannot delete IV->getBase(), since PE points to it.
1090 // Replace the old base with the cast. This is important when doing
1091 // embedded rewrites. For example, [newInv->_container addObject:0].
1092 IV->setBase(PE);
1093 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001094 }
Steve Naroff84472a82008-04-18 21:55:08 +00001095 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001096 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
1097
1098 // Explicit ivar refs need to have a cast inserted.
1099 // FIXME: consider sharing some of this code with the code above.
1100 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +00001101 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001102 // lookup which class implements the instance variable.
1103 ObjCInterfaceDecl *clsDeclared = 0;
Steve Narofff0757612008-05-08 17:52:16 +00001104 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001105 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1106
1107 // Synthesize an explicit cast to gain access to the ivar.
1108 std::string RecName = clsDeclared->getIdentifier()->getName();
1109 RecName += "_IMPL";
1110 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001111 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001112 SourceLocation(), II);
Steve Naroff9f525972008-05-06 23:20:07 +00001113 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1114 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001115 CastExpr *castExpr = new CStyleCastExpr(castT, IV->getBase(), castT,
Steve Naroffb2f9e512008-11-03 23:29:32 +00001116 SourceLocation(), SourceLocation());
Steve Naroff9f525972008-05-06 23:20:07 +00001117 // Don't forget the parens to enforce the proper binding.
Chris Lattner8d366162008-05-28 16:38:23 +00001118 ParenExpr *PE = new ParenExpr(IV->getBase()->getLocStart(),
1119 IV->getBase()->getLocEnd(), castExpr);
Steve Naroff9f525972008-05-06 23:20:07 +00001120 ReplaceStmt(IV->getBase(), PE);
1121 // Cannot delete IV->getBase(), since PE points to it.
1122 // Replace the old base with the cast. This is important when doing
1123 // embedded rewrites. For example, [newInv->_container addObject:0].
1124 IV->setBase(PE);
1125 return IV;
1126 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001127 }
Steve Naroff84472a82008-04-18 21:55:08 +00001128 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +00001129}
1130
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001131/// SynthCountByEnumWithState - To print:
1132/// ((unsigned int (*)
1133/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1134/// (void *)objc_msgSend)((id)l_collection,
1135/// sel_registerName(
1136/// "countByEnumeratingWithState:objects:count:"),
1137/// &enumState,
1138/// (id *)items, (unsigned int)16)
1139///
Steve Naroffb29b4272008-04-14 22:03:09 +00001140void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001141 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1142 "id *, unsigned int))(void *)objc_msgSend)";
1143 buf += "\n\t\t";
1144 buf += "((id)l_collection,\n\t\t";
1145 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1146 buf += "\n\t\t";
1147 buf += "&enumState, "
1148 "(id *)items, (unsigned int)16)";
1149}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001150
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001151/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1152/// statement to exit to its outer synthesized loop.
1153///
Steve Naroffb29b4272008-04-14 22:03:09 +00001154Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001155 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1156 return S;
1157 // replace break with goto __break_label
1158 std::string buf;
1159
1160 SourceLocation startLoc = S->getLocStart();
1161 buf = "goto __break_label_";
1162 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001163 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001164
1165 return 0;
1166}
1167
1168/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1169/// statement to continue with its inner synthesized loop.
1170///
Steve Naroffb29b4272008-04-14 22:03:09 +00001171Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001172 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1173 return S;
1174 // replace continue with goto __continue_label
1175 std::string buf;
1176
1177 SourceLocation startLoc = S->getLocStart();
1178 buf = "goto __continue_label_";
1179 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001180 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001181
1182 return 0;
1183}
1184
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001185/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001186/// It rewrites:
1187/// for ( type elem in collection) { stmts; }
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001188
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001189/// Into:
1190/// {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001191/// type elem;
1192/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001193/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001194/// id l_collection = (id)collection;
1195/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1196/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001197/// if (limit) {
1198/// unsigned long startMutations = *enumState.mutationsPtr;
1199/// do {
1200/// unsigned long counter = 0;
1201/// do {
1202/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001203/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001204/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001205/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001206/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001207/// } while (counter < limit);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001208/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1209/// objects:items count:16]);
1210/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001211/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001212/// }
1213/// else
1214/// elem = nil;
1215/// }
1216///
Steve Naroffb29b4272008-04-14 22:03:09 +00001217Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001218 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001219 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1220 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1221 "ObjCForCollectionStmt Statement stack mismatch");
1222 assert(!ObjCBcLabelNo.empty() &&
1223 "ObjCForCollectionStmt - Label No stack empty");
1224
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001225 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001226 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001227 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001228 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001229 std::string buf;
1230 buf = "\n{\n\t";
1231 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1232 // type elem;
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001233 ScopedDecl* D = DS->getSolitaryDecl();
1234 QualType ElementType = cast<ValueDecl>(D)->getType();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001235 elementTypeAsString = ElementType.getAsString();
1236 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001237 buf += " ";
Chris Lattner8ec03f52008-11-24 03:54:41 +00001238 elementName = D->getNameAsCString();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001239 buf += elementName;
1240 buf += ";\n\t";
1241 }
Chris Lattner06767512008-04-08 05:52:18 +00001242 else {
1243 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner8ec03f52008-11-24 03:54:41 +00001244 elementName = DR->getDecl()->getNameAsCString();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001245 elementTypeAsString
1246 = cast<ValueDecl>(DR->getDecl())->getType().getAsString();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001247 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001248
1249 // struct __objcFastEnumerationState enumState = { 0 };
1250 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1251 // id items[16];
1252 buf += "id items[16];\n\t";
1253 // id l_collection = (id)
1254 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001255 // Find start location of 'collection' the hard way!
1256 const char *startCollectionBuf = startBuf;
1257 startCollectionBuf += 3; // skip 'for'
1258 startCollectionBuf = strchr(startCollectionBuf, '(');
1259 startCollectionBuf++; // skip '('
1260 // find 'in' and skip it.
1261 while (*startCollectionBuf != ' ' ||
1262 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1263 (*(startCollectionBuf+3) != ' ' &&
1264 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1265 startCollectionBuf++;
1266 startCollectionBuf += 3;
1267
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001268 // Replace: "for (type element in" with string constructed thus far.
Chris Lattneraadaf782008-01-31 19:51:04 +00001269 ReplaceText(startLoc, startCollectionBuf - startBuf,
1270 buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001271 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001272 SourceLocation rightParenLoc = S->getRParenLoc();
1273 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1274 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001275 buf = ";\n\t";
1276
1277 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1278 // objects:items count:16];
1279 // which is synthesized into:
1280 // unsigned int limit =
1281 // ((unsigned int (*)
1282 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1283 // (void *)objc_msgSend)((id)l_collection,
1284 // sel_registerName(
1285 // "countByEnumeratingWithState:objects:count:"),
1286 // (struct __objcFastEnumerationState *)&state,
1287 // (id *)items, (unsigned int)16);
1288 buf += "unsigned long limit =\n\t\t";
1289 SynthCountByEnumWithState(buf);
1290 buf += ";\n\t";
1291 /// if (limit) {
1292 /// unsigned long startMutations = *enumState.mutationsPtr;
1293 /// do {
1294 /// unsigned long counter = 0;
1295 /// do {
1296 /// if (startMutations != *enumState.mutationsPtr)
1297 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001298 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001299 buf += "if (limit) {\n\t";
1300 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1301 buf += "do {\n\t\t";
1302 buf += "unsigned long counter = 0;\n\t\t";
1303 buf += "do {\n\t\t\t";
1304 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1305 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1306 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001307 buf += " = (";
1308 buf += elementTypeAsString;
1309 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001310 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattneraadaf782008-01-31 19:51:04 +00001311 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001312
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001313 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001314 /// } while (counter < limit);
1315 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1316 /// objects:items count:16]);
1317 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001318 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001319 /// }
1320 /// else
1321 /// elem = nil;
1322 /// }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001323 ///
1324 buf = ";\n\t";
1325 buf += "__continue_label_";
1326 buf += utostr(ObjCBcLabelNo.back());
1327 buf += ": ;";
1328 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001329 buf += "} while (counter < limit);\n\t";
1330 buf += "} while (limit = ";
1331 SynthCountByEnumWithState(buf);
1332 buf += ");\n\t";
1333 buf += elementName;
1334 buf += " = nil;\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001335 buf += "__break_label_";
1336 buf += utostr(ObjCBcLabelNo.back());
1337 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001338 buf += "}\n\t";
1339 buf += "else\n\t\t";
1340 buf += elementName;
1341 buf += " = nil;\n";
1342 buf += "}\n";
Steve Naroff600e4e82008-07-21 18:26:02 +00001343
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001344 // Insert all these *after* the statement body.
Steve Naroff600e4e82008-07-21 18:26:02 +00001345 if (isa<CompoundStmt>(S->getBody())) {
1346 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1347 InsertText(endBodyLoc, buf.c_str(), buf.size());
1348 } else {
1349 /* Need to treat single statements specially. For example:
1350 *
1351 * for (A *a in b) if (stuff()) break;
1352 * for (A *a in b) xxxyy;
1353 *
1354 * The following code simply scans ahead to the semi to find the actual end.
1355 */
1356 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1357 const char *semiBuf = strchr(stmtBuf, ';');
1358 assert(semiBuf && "Can't find ';'");
1359 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1360 InsertText(endBodyLoc, buf.c_str(), buf.size());
1361 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001362 Stmts.pop_back();
1363 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001364 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001365}
1366
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001367/// RewriteObjCSynchronizedStmt -
1368/// This routine rewrites @synchronized(expr) stmt;
1369/// into:
1370/// objc_sync_enter(expr);
1371/// @try stmt @finally { objc_sync_exit(expr); }
1372///
Steve Naroffb29b4272008-04-14 22:03:09 +00001373Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001374 // Get the start location and compute the semi location.
1375 SourceLocation startLoc = S->getLocStart();
1376 const char *startBuf = SM->getCharacterData(startLoc);
1377
1378 assert((*startBuf == '@') && "bogus @synchronized location");
1379
1380 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001381 buf = "objc_sync_enter((id)";
1382 const char *lparenBuf = startBuf;
1383 while (*lparenBuf != '(') lparenBuf++;
1384 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Steve Naroffc7089f12008-08-19 13:04:19 +00001385 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1386 // the sync expression is typically a message expression that's already
1387 // been rewritten! (which implies the SourceLocation's are invalid).
1388 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001389 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001390 while (*endBuf != ')') endBuf--;
1391 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001392 buf = ");\n";
1393 // declare a new scope with two variables, _stack and _rethrow.
1394 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1395 buf += "int buf[18/*32-bit i386*/];\n";
1396 buf += "char *pointers[4];} _stack;\n";
1397 buf += "id volatile _rethrow = 0;\n";
1398 buf += "objc_exception_try_enter(&_stack);\n";
1399 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00001400 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001401 startLoc = S->getSynchBody()->getLocEnd();
1402 startBuf = SM->getCharacterData(startLoc);
1403
Steve Naroffc7089f12008-08-19 13:04:19 +00001404 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001405 SourceLocation lastCurlyLoc = startLoc;
1406 buf = "}\nelse {\n";
1407 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1408 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb2a39452008-07-16 19:47:39 +00001409 buf += " objc_sync_exit(";
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001410 Expr *syncExpr = new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00001411 S->getSynchExpr(),
1412 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00001413 SourceLocation(), SourceLocation());
Ted Kremeneka95d3752008-09-13 05:16:45 +00001414 std::string syncExprBufS;
1415 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Steve Naroff3498cc92008-08-21 13:03:03 +00001416 syncExpr->printPretty(syncExprBuf);
Steve Naroffb2a39452008-07-16 19:47:39 +00001417 buf += syncExprBuf.str();
1418 buf += ");\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001419 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1420 buf += "}\n";
1421 buf += "}";
1422
Chris Lattneraadaf782008-01-31 19:51:04 +00001423 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001424 return 0;
1425}
1426
Steve Naroff8c565152008-12-05 17:03:39 +00001427void RewriteObjC::WarnAboutReturnGotoContinueOrBreakStmts(Stmt *S) {
1428 // Perform a bottom up traversal of all children.
1429 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1430 CI != E; ++CI)
1431 if (*CI)
1432 WarnAboutReturnGotoContinueOrBreakStmts(*CI);
1433
1434 if (isa<ReturnStmt>(S) || isa<ContinueStmt>(S) ||
1435 isa<BreakStmt>(S) || isa<GotoStmt>(S)) {
1436 Diags.Report(Context->getFullLoc(S->getLocStart()),
1437 TryFinallyContainsReturnDiag);
1438 }
1439 return;
1440}
1441
Steve Naroffb29b4272008-04-14 22:03:09 +00001442Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001443 // Get the start location and compute the semi location.
1444 SourceLocation startLoc = S->getLocStart();
1445 const char *startBuf = SM->getCharacterData(startLoc);
1446
1447 assert((*startBuf == '@') && "bogus @try location");
1448
1449 std::string buf;
1450 // declare a new scope with two variables, _stack and _rethrow.
1451 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1452 buf += "int buf[18/*32-bit i386*/];\n";
1453 buf += "char *pointers[4];} _stack;\n";
1454 buf += "id volatile _rethrow = 0;\n";
1455 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001456 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001457
Chris Lattneraadaf782008-01-31 19:51:04 +00001458 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001459
1460 startLoc = S->getTryBody()->getLocEnd();
1461 startBuf = SM->getCharacterData(startLoc);
1462
1463 assert((*startBuf == '}') && "bogus @try block");
Steve Naroffc9ba1722008-07-16 15:31:30 +00001464
Steve Naroff75730982007-11-07 04:08:17 +00001465 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffc9ba1722008-07-16 15:31:30 +00001466 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1467 if (catchList) {
1468 startLoc = startLoc.getFileLocWithOffset(1);
1469 buf = " /* @catch begin */ else {\n";
1470 buf += " id _caught = objc_exception_extract(&_stack);\n";
1471 buf += " objc_exception_try_enter (&_stack);\n";
1472 buf += " if (_setjmp(_stack.buf))\n";
1473 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1474 buf += " else { /* @catch continue */";
1475
1476 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001477 } else { /* no catch list */
1478 buf = "}\nelse {\n";
1479 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1480 buf += "}";
1481 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffc9ba1722008-07-16 15:31:30 +00001482 }
Steve Naroff75730982007-11-07 04:08:17 +00001483 bool sawIdTypedCatch = false;
1484 Stmt *lastCatchBody = 0;
Steve Naroff75730982007-11-07 04:08:17 +00001485 while (catchList) {
1486 Stmt *catchStmt = catchList->getCatchParamStmt();
1487
1488 if (catchList == S->getCatchStmts())
1489 buf = "if ("; // we are generating code for the first catch clause
1490 else
1491 buf = "else if (";
1492 startLoc = catchList->getLocStart();
1493 startBuf = SM->getCharacterData(startLoc);
1494
1495 assert((*startBuf == '@') && "bogus @catch location");
1496
1497 const char *lParenLoc = strchr(startBuf, '(');
1498
Steve Naroffbe4b3332008-02-01 22:08:12 +00001499 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001500 // Now rewrite the body...
1501 lastCatchBody = catchList->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001502 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1503 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner06767512008-04-08 05:52:18 +00001504 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1505 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001506 assert((*bodyBuf == '{') && "bogus @catch body location");
1507
1508 buf += "1) { id _tmp = _caught;";
1509 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1510 buf.c_str(), buf.size());
1511 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Ted Kremenek50a25e22008-10-06 22:39:38 +00001512 QualType t = dyn_cast<ValueDecl>(declStmt->getSolitaryDecl())->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001513 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001514 buf += "1) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001515 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001516 sawIdTypedCatch = true;
1517 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001518 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroff75730982007-11-07 04:08:17 +00001519
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001520 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001521 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001522 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001523 buf += cls->getDecl()->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001524 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001525 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001526 }
1527 }
1528 // Now rewrite the body...
1529 lastCatchBody = catchList->getCatchBody();
1530 SourceLocation rParenLoc = catchList->getRParenLoc();
1531 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1532 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1533 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1534 assert((*rParenBuf == ')') && "bogus @catch paren location");
1535 assert((*bodyBuf == '{') && "bogus @catch body location");
1536
1537 buf = " = _caught;";
1538 // Here we replace ") {" with "= _caught;" (which initializes and
1539 // declares the @catch parameter).
Chris Lattneraadaf782008-01-31 19:51:04 +00001540 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001541 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001542 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001543 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001544 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001545 catchList = catchList->getNextCatchStmt();
1546 }
1547 // Complete the catch list...
1548 if (lastCatchBody) {
1549 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001550 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1551 "bogus @catch body location");
Steve Naroff75730982007-11-07 04:08:17 +00001552
Steve Naroff378f47a2008-09-11 15:29:03 +00001553 // Insert the last (implicit) else clause *before* the right curly brace.
1554 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1555 buf = "} /* last catch end */\n";
1556 buf += "else {\n";
1557 buf += " _rethrow = _caught;\n";
1558 buf += " objc_exception_try_exit(&_stack);\n";
1559 buf += "} } /* @catch end */\n";
1560 if (!S->getFinallyStmt())
1561 buf += "}\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001562 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001563
1564 // Set lastCurlyLoc
1565 lastCurlyLoc = lastCatchBody->getLocEnd();
1566 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001567 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001568 startLoc = finalStmt->getLocStart();
1569 startBuf = SM->getCharacterData(startLoc);
1570 assert((*startBuf == '@') && "bogus @finally start");
1571
1572 buf = "/* @finally */";
Chris Lattneraadaf782008-01-31 19:51:04 +00001573 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001574
1575 Stmt *body = finalStmt->getFinallyBody();
1576 SourceLocation startLoc = body->getLocStart();
1577 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001578 assert(*SM->getCharacterData(startLoc) == '{' &&
1579 "bogus @finally body location");
1580 assert(*SM->getCharacterData(endLoc) == '}' &&
1581 "bogus @finally body location");
Steve Naroff75730982007-11-07 04:08:17 +00001582
1583 startLoc = startLoc.getFileLocWithOffset(1);
1584 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001585 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001586 endLoc = endLoc.getFileLocWithOffset(-1);
1587 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001588 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001589
1590 // Set lastCurlyLoc
1591 lastCurlyLoc = body->getLocEnd();
Steve Naroff8c565152008-12-05 17:03:39 +00001592
1593 // Now check for any return/continue/go statements within the @try.
1594 WarnAboutReturnGotoContinueOrBreakStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00001595 } else { /* no finally clause - make sure we synthesize an implicit one */
1596 buf = "{ /* implicit finally clause */\n";
1597 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1598 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1599 buf += "}";
1600 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001601 }
1602 // Now emit the final closing curly brace...
1603 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1604 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001605 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001606 return 0;
1607}
1608
Steve Naroffb29b4272008-04-14 22:03:09 +00001609Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001610 return 0;
1611}
1612
Steve Naroffb29b4272008-04-14 22:03:09 +00001613Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001614 return 0;
1615}
1616
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001617// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff2bd03922007-11-07 15:32:26 +00001618// the throw expression is typically a message expression that's already
1619// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001620Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001621 // Get the start location and compute the semi location.
1622 SourceLocation startLoc = S->getLocStart();
1623 const char *startBuf = SM->getCharacterData(startLoc);
1624
1625 assert((*startBuf == '@') && "bogus @throw location");
1626
1627 std::string buf;
1628 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001629 if (S->getThrowExpr())
1630 buf = "objc_exception_throw(";
1631 else // add an implicit argument
1632 buf = "objc_exception_throw(_caught";
Steve Naroff4ba0acb2008-07-25 15:41:30 +00001633
1634 // handle "@ throw" correctly.
1635 const char *wBuf = strchr(startBuf, 'w');
1636 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1637 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
1638
Steve Naroff2bd03922007-11-07 15:32:26 +00001639 const char *semiBuf = strchr(startBuf, ';');
1640 assert((*semiBuf == ';') && "@throw: can't find ';'");
1641 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1642 buf = ");";
Chris Lattneraadaf782008-01-31 19:51:04 +00001643 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001644 return 0;
1645}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001646
Steve Naroffb29b4272008-04-14 22:03:09 +00001647Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001648 // Create a new string expression.
1649 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001650 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001651 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001652 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1653 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +00001654 SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001655 ReplaceStmt(Exp, Replacement);
Chris Lattnere365c502007-11-30 22:25:36 +00001656
Chris Lattner07506182007-11-30 22:53:43 +00001657 // Replace this subexpr in the parent.
Steve Naroff4c3580e2008-12-04 23:50:32 +00001658 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00001659 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001660}
1661
Steve Naroffb29b4272008-04-14 22:03:09 +00001662Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroffb42f8412007-11-05 14:50:49 +00001663 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1664 // Create a call to sel_registerName("selName").
1665 llvm::SmallVector<Expr*, 8> SelExprs;
1666 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner077bf5e2008-11-24 03:33:13 +00001667 SelExprs.push_back(new StringLiteral(Exp->getSelector().getAsString().c_str(),
1668 Exp->getSelector().getAsString().size(),
Steve Naroffb42f8412007-11-05 14:50:49 +00001669 false, argType, SourceLocation(),
1670 SourceLocation()));
1671 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1672 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001673 ReplaceStmt(Exp, SelExp);
Steve Naroff4c3580e2008-12-04 23:50:32 +00001674 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00001675 return SelExp;
1676}
1677
Steve Naroffb29b4272008-04-14 22:03:09 +00001678CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff934f2762007-10-24 22:48:43 +00001679 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001680 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001681 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +00001682
1683 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +00001684 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +00001685
1686 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001687 QualType pToFunc = Context->getPointerType(msgSendType);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001688 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE,
1689 /*isLvalue=*/false);
Steve Naroffebf2b562007-10-23 23:50:29 +00001690
1691 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +00001692
Steve Naroff934f2762007-10-24 22:48:43 +00001693 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1694}
1695
Steve Naroffd5255f52007-11-01 13:24:47 +00001696static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1697 const char *&startRef, const char *&endRef) {
1698 while (startBuf < endBuf) {
1699 if (*startBuf == '<')
1700 startRef = startBuf; // mark the start.
1701 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001702 if (startRef && *startRef == '<') {
1703 endRef = startBuf; // mark the end.
1704 return true;
1705 }
1706 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001707 }
1708 startBuf++;
1709 }
1710 return false;
1711}
1712
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001713static void scanToNextArgument(const char *&argRef) {
1714 int angle = 0;
1715 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1716 if (*argRef == '<')
1717 angle++;
1718 else if (*argRef == '>')
1719 angle--;
1720 argRef++;
1721 }
1722 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1723}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001724
Steve Naroffb29b4272008-04-14 22:03:09 +00001725bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001726
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001727 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001728 return true;
1729
Steve Naroffd5255f52007-11-01 13:24:47 +00001730 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +00001731 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001732 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff9165ad32007-10-31 04:38:33 +00001733 return true; // we have "Class <Protocol> *".
1734 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001735 return false;
1736}
1737
Steve Naroff4f95b752008-07-29 18:15:38 +00001738void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1739 QualType Type = E->getType();
1740 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00001741 SourceLocation Loc, EndLoc;
1742
1743 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
1744 Loc = ECE->getLParenLoc();
1745 EndLoc = ECE->getRParenLoc();
1746 } else {
1747 Loc = E->getLocStart();
1748 EndLoc = E->getLocEnd();
1749 }
1750 // This will defend against trying to rewrite synthesized expressions.
1751 if (Loc.isInvalid() || EndLoc.isInvalid())
1752 return;
1753
Steve Naroff4f95b752008-07-29 18:15:38 +00001754 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00001755 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00001756 const char *startRef = 0, *endRef = 0;
1757 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1758 // Get the locations of the startRef, endRef.
1759 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1760 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1761 // Comment out the protocol references.
1762 InsertText(LessLoc, "/*", 2);
1763 InsertText(GreaterLoc, "*/", 2);
1764 }
1765 }
1766}
1767
Steve Naroffb29b4272008-04-14 22:03:09 +00001768void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001769 SourceLocation Loc;
1770 QualType Type;
1771 const FunctionTypeProto *proto = 0;
1772 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1773 Loc = VD->getLocation();
1774 Type = VD->getType();
1775 }
1776 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1777 Loc = FD->getLocation();
1778 // Check for ObjC 'id' and class types that have been adorned with protocol
1779 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1780 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1781 assert(funcType && "missing function type");
1782 proto = dyn_cast<FunctionTypeProto>(funcType);
1783 if (!proto)
1784 return;
1785 Type = proto->getResultType();
1786 }
1787 else
1788 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001789
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001790 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001791 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001792
1793 const char *endBuf = SM->getCharacterData(Loc);
1794 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00001795 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001796 startBuf--; // scan backward (from the decl location) for return type.
1797 const char *startRef = 0, *endRef = 0;
1798 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1799 // Get the locations of the startRef, endRef.
1800 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1801 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1802 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001803 InsertText(LessLoc, "/*", 2);
1804 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001805 }
1806 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001807 if (!proto)
1808 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001809 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001810 const char *startBuf = SM->getCharacterData(Loc);
1811 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001812 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1813 if (needToScanForQualifiers(proto->getArgType(i))) {
1814 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001815
Steve Naroffd5255f52007-11-01 13:24:47 +00001816 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001817 // scan forward (from the decl location) for argument types.
1818 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001819 const char *startRef = 0, *endRef = 0;
1820 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1821 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001822 SourceLocation LessLoc =
1823 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1824 SourceLocation GreaterLoc =
1825 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001826 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001827 InsertText(LessLoc, "/*", 2);
1828 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001829 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001830 startBuf = ++endBuf;
1831 }
1832 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00001833 // If the function name is derived from a macro expansion, then the
1834 // argument buffer will not follow the name. Need to speak with Chris.
1835 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001836 startBuf++; // scan forward (from the decl location) for argument types.
1837 startBuf++;
1838 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001839 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001840}
1841
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001842// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00001843void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001844 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1845 llvm::SmallVector<QualType, 16> ArgTys;
1846 ArgTys.push_back(Context->getPointerType(
1847 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001848 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001849 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001850 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001851 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001852 SourceLocation(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001853 SelGetUidIdent, getFuncType,
1854 FunctionDecl::Extern, false, 0);
1855}
1856
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001857// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
Steve Naroffb29b4272008-04-14 22:03:09 +00001858void RewriteObjC::SynthGetProtocolFunctionDecl() {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001859 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1860 llvm::SmallVector<QualType, 16> ArgTys;
1861 ArgTys.push_back(Context->getPointerType(
1862 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001863 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001864 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001865 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001866 GetProtocolFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001867 SourceLocation(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001868 SelGetProtoIdent, getFuncType,
1869 FunctionDecl::Extern, false, 0);
1870}
1871
Steve Naroffb29b4272008-04-14 22:03:09 +00001872void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001873 // declared in <objc/objc.h>
Chris Lattner8ec03f52008-11-24 03:54:41 +00001874 if (strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001875 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001876 return;
1877 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001878 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001879}
1880
Steve Naroffc0a123c2008-03-11 17:37:02 +00001881// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00001882void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00001883 if (SuperContructorFunctionDecl)
1884 return;
1885 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_super");
1886 llvm::SmallVector<QualType, 16> ArgTys;
1887 QualType argT = Context->getObjCIdType();
1888 assert(!argT.isNull() && "Can't find 'id' type");
1889 ArgTys.push_back(argT);
1890 ArgTys.push_back(argT);
1891 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1892 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001893 false, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001894 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001895 SourceLocation(),
Steve Naroffc0a123c2008-03-11 17:37:02 +00001896 msgSendIdent, msgSendType,
1897 FunctionDecl::Extern, false, 0);
1898}
1899
Steve Naroff09b266e2007-10-30 23:14:51 +00001900// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001901void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00001902 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1903 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001904 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001905 assert(!argT.isNull() && "Can't find 'id' type");
1906 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001907 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001908 assert(!argT.isNull() && "Can't find 'SEL' type");
1909 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001910 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001911 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001912 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001913 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001914 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001915 msgSendIdent, msgSendType,
1916 FunctionDecl::Extern, false, 0);
1917}
1918
Steve Naroff874e2322007-11-15 10:28:18 +00001919// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001920void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00001921 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1922 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001923 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001924 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00001925 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00001926 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1927 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1928 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001929 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00001930 assert(!argT.isNull() && "Can't find 'SEL' type");
1931 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001932 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00001933 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001934 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001935 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001936 SourceLocation(),
Steve Naroff874e2322007-11-15 10:28:18 +00001937 msgSendIdent, msgSendType,
1938 FunctionDecl::Extern, false, 0);
1939}
1940
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001941// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001942void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001943 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1944 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001945 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001946 assert(!argT.isNull() && "Can't find 'id' type");
1947 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001948 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001949 assert(!argT.isNull() && "Can't find 'SEL' type");
1950 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001951 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001952 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001953 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001954 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001955 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001956 msgSendIdent, msgSendType,
1957 FunctionDecl::Extern, false, 0);
1958}
1959
1960// SynthMsgSendSuperStretFunctionDecl -
1961// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001962void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001963 IdentifierInfo *msgSendIdent =
1964 &Context->Idents.get("objc_msgSendSuper_stret");
1965 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001966 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001967 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00001968 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001969 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1970 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1971 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001972 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001973 assert(!argT.isNull() && "Can't find 'SEL' type");
1974 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001975 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001976 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001977 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001978 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnera98e58d2008-03-15 21:24:04 +00001979 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001980 msgSendIdent, msgSendType,
1981 FunctionDecl::Extern, false, 0);
1982}
1983
Steve Naroff1284db82008-05-08 22:02:18 +00001984// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001985void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001986 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1987 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001988 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001989 assert(!argT.isNull() && "Can't find 'id' type");
1990 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001991 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001992 assert(!argT.isNull() && "Can't find 'SEL' type");
1993 ArgTys.push_back(argT);
Steve Naroff1284db82008-05-08 22:02:18 +00001994 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001995 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001996 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001997 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001998 SourceLocation(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001999 msgSendIdent, msgSendType,
2000 FunctionDecl::Extern, false, 0);
2001}
2002
Steve Naroff09b266e2007-10-30 23:14:51 +00002003// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002004void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002005 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2006 llvm::SmallVector<QualType, 16> ArgTys;
2007 ArgTys.push_back(Context->getPointerType(
2008 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002009 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002010 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002011 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002012 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002013 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002014 getClassIdent, getClassType,
2015 FunctionDecl::Extern, false, 0);
2016}
2017
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002018// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002019void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002020 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2021 llvm::SmallVector<QualType, 16> ArgTys;
2022 ArgTys.push_back(Context->getPointerType(
2023 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002024 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002025 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002026 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002027 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002028 SourceLocation(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002029 getClassIdent, getClassType,
2030 FunctionDecl::Extern, false, 0);
2031}
2032
Steve Naroffb29b4272008-04-14 22:03:09 +00002033Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002034 QualType strType = getConstantStringStructType();
2035
2036 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002037
2038 std::string tmpName = InFileName;
2039 unsigned i;
2040 for (i=0; i < tmpName.length(); i++) {
2041 char c = tmpName.at(i);
2042 // replace any non alphanumeric characters with '_'.
2043 if (!isalpha(c) && (c < '0' || c > '9'))
2044 tmpName[i] = '_';
2045 }
2046 S += tmpName;
2047 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002048 S += utostr(NumObjCStringLiterals++);
2049
Steve Naroffba92b2e2008-03-27 22:29:16 +00002050 Preamble += "static __NSConstantStringImpl " + S;
2051 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2052 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002053 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002054 std::string prettyBufS;
2055 llvm::raw_string_ostream prettyBuf(prettyBufS);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002056 Exp->getString()->printPretty(prettyBuf);
Steve Naroffba92b2e2008-03-27 22:29:16 +00002057 Preamble += prettyBuf.str();
2058 Preamble += ",";
Steve Naroff3652c2d2008-03-15 01:36:04 +00002059 // The minus 2 removes the begin/end double quotes.
Steve Naroffba92b2e2008-03-27 22:29:16 +00002060 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002061
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002062 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Steve Naroff248a7532008-04-15 22:42:06 +00002063 &Context->Idents.get(S.c_str()), strType,
2064 VarDecl::Static, NULL);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002065 DeclRefExpr *DRE = new DeclRefExpr(NewVD, strType, SourceLocation());
2066 Expr *Unop = new UnaryOperator(DRE, UnaryOperator::AddrOf,
2067 Context->getPointerType(DRE->getType()),
2068 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002069 // cast to NSConstantString *
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002070 CastExpr *cast = new CStyleCastExpr(Exp->getType(), Unop,
Steve Naroffb2f9e512008-11-03 23:29:32 +00002071 Exp->getType(), SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002072 ReplaceStmt(Exp, cast);
Steve Naroff4c3580e2008-12-04 23:50:32 +00002073 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002074 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002075}
2076
Steve Naroffb29b4272008-04-14 22:03:09 +00002077ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002078 // check if we are sending a message to 'super'
Steve Naroff54055232008-10-27 17:20:55 +00002079 if (!CurMethodDef || !CurMethodDef->isInstance()) return 0;
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002080
Douglas Gregorcd9b46e2008-11-04 14:56:14 +00002081 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
2082 const PointerType *PT = Super->getType()->getAsPointerType();
Chris Lattner0d17f6f2008-06-21 18:04:54 +00002083 assert(PT);
2084 ObjCInterfaceType *IT = cast<ObjCInterfaceType>(PT->getPointeeType());
2085 return IT->getDecl();
2086 }
2087 return 0;
Steve Naroff874e2322007-11-15 10:28:18 +00002088}
2089
2090// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002091QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002092 if (!SuperStructDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002093 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002094 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002095 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002096 QualType FieldTypes[2];
2097
2098 // struct objc_object *receiver;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002099 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002100 // struct objc_class *super;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002101 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff874e2322007-11-15 10:28:18 +00002102 // Create fields
2103 FieldDecl *FieldDecls[2];
2104
2105 for (unsigned i = 0; i < 2; ++i)
Chris Lattnerb048c982008-04-06 04:47:34 +00002106 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00002107 FieldTypes[i]);
Steve Naroff874e2322007-11-15 10:28:18 +00002108
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002109 SuperStructDecl->defineBody(*Context, FieldDecls, 4);
Steve Naroff874e2322007-11-15 10:28:18 +00002110 }
2111 return Context->getTagDeclType(SuperStructDecl);
2112}
2113
Steve Naroffb29b4272008-04-14 22:03:09 +00002114QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002115 if (!ConstantStringDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002116 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002117 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002118 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002119 QualType FieldTypes[4];
2120
2121 // struct objc_object *receiver;
2122 FieldTypes[0] = Context->getObjCIdType();
2123 // int flags;
2124 FieldTypes[1] = Context->IntTy;
2125 // char *str;
2126 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2127 // long length;
2128 FieldTypes[3] = Context->LongTy;
2129 // Create fields
Steve Naroff9630ec52008-03-27 22:59:54 +00002130 FieldDecl *FieldDecls[4];
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002131
2132 for (unsigned i = 0; i < 4; ++i)
Chris Lattnerb048c982008-04-06 04:47:34 +00002133 FieldDecls[i] = FieldDecl::Create(*Context, SourceLocation(), 0,
Chris Lattner8e25d862008-03-16 00:16:02 +00002134 FieldTypes[i]);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002135
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002136 ConstantStringDecl->defineBody(*Context, FieldDecls, 4);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002137 }
2138 return Context->getTagDeclType(ConstantStringDecl);
2139}
2140
Steve Naroffb29b4272008-04-14 22:03:09 +00002141Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002142 if (!SelGetUidFunctionDecl)
2143 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002144 if (!MsgSendFunctionDecl)
2145 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002146 if (!MsgSendSuperFunctionDecl)
2147 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002148 if (!MsgSendStretFunctionDecl)
2149 SynthMsgSendStretFunctionDecl();
2150 if (!MsgSendSuperStretFunctionDecl)
2151 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002152 if (!MsgSendFpretFunctionDecl)
2153 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002154 if (!GetClassFunctionDecl)
2155 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002156 if (!GetMetaClassFunctionDecl)
2157 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002158
Steve Naroff874e2322007-11-15 10:28:18 +00002159 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002160 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2161 // May need to use objc_msgSend_stret() as well.
2162 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002163 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002164 QualType resultType = mDecl->getResultType();
Chris Lattner8b51fd72008-07-26 22:36:27 +00002165 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002166 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002167 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002168 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002169 }
Steve Naroff874e2322007-11-15 10:28:18 +00002170
Steve Naroff934f2762007-10-24 22:48:43 +00002171 // Synthesize a call to objc_msgSend().
2172 llvm::SmallVector<Expr*, 8> MsgExprs;
2173 IdentifierInfo *clsName = Exp->getClassName();
2174
2175 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2176 if (clsName) { // class message.
Steve Narofffc93d522008-07-24 19:44:33 +00002177 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2178 // the 'super' idiom within a class method.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002179 if (!strcmp(clsName->getName(), "super")) {
2180 MsgSendFlavor = MsgSendSuperFunctionDecl;
2181 if (MsgSendStretFlavor)
2182 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2183 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2184
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002185 ObjCInterfaceDecl *SuperDecl =
Steve Naroff54055232008-10-27 17:20:55 +00002186 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002187
2188 llvm::SmallVector<Expr*, 4> InitExprs;
2189
2190 // set the receiver to self, the first argument to all methods.
Chris Lattner41110242008-06-17 18:05:57 +00002191 InitExprs.push_back(new DeclRefExpr(
Steve Naroff54055232008-10-27 17:20:55 +00002192 CurMethodDef->getSelfDecl(),
Chris Lattner41110242008-06-17 18:05:57 +00002193 Context->getObjCIdType(),
2194 SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002195 llvm::SmallVector<Expr*, 8> ClsExprs;
2196 QualType argType = Context->getPointerType(Context->CharTy);
2197 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2198 SuperDecl->getIdentifier()->getLength(),
2199 false, argType, SourceLocation(),
2200 SourceLocation()));
2201 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2202 &ClsExprs[0],
2203 ClsExprs.size());
2204 // To turn off a warning, type-cast to 'id'
Douglas Gregor49badde2008-10-27 19:41:14 +00002205 InitExprs.push_back( // set 'super class', using objc_getClass().
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002206 new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002207 Cls, Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002208 SourceLocation(), SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002209 // struct objc_super
2210 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00002211 Expr *SuperRep;
Steve Naroffc0a123c2008-03-11 17:37:02 +00002212
Steve Naroff23f41272008-03-11 18:14:26 +00002213 if (LangOpts.Microsoft) {
2214 SynthSuperContructorFunctionDecl();
2215 // Simulate a contructor call...
2216 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2217 superType, SourceLocation());
2218 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2219 superType, SourceLocation());
2220 } else {
2221 // (struct objc_super) { <exprs from above> }
2222 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2223 &InitExprs[0], InitExprs.size(),
Chris Lattner418f6c72008-10-26 23:43:26 +00002224 SourceLocation(), false);
2225 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE,
2226 false);
Steve Naroff23f41272008-03-11 18:14:26 +00002227 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002228 // struct objc_super *
2229 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2230 Context->getPointerType(SuperRep->getType()),
2231 SourceLocation());
2232 MsgExprs.push_back(Unop);
2233 } else {
2234 llvm::SmallVector<Expr*, 8> ClsExprs;
2235 QualType argType = Context->getPointerType(Context->CharTy);
2236 ClsExprs.push_back(new StringLiteral(clsName->getName(),
2237 clsName->getLength(),
2238 false, argType, SourceLocation(),
2239 SourceLocation()));
2240 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2241 &ClsExprs[0],
2242 ClsExprs.size());
2243 MsgExprs.push_back(Cls);
2244 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002245 } else { // instance message.
2246 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00002247
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002248 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00002249 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002250 if (MsgSendStretFlavor)
2251 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00002252 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2253
2254 llvm::SmallVector<Expr*, 4> InitExprs;
2255
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002256 InitExprs.push_back(
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002257 new CStyleCastExpr(Context->getObjCIdType(),
Steve Naroff54055232008-10-27 17:20:55 +00002258 new DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Narofff616ebb2008-07-16 22:35:27 +00002259 Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002260 SourceLocation()),
2261 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002262 SourceLocation(), SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00002263
2264 llvm::SmallVector<Expr*, 8> ClsExprs;
2265 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002266 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
2267 SuperDecl->getIdentifier()->getLength(),
Steve Naroff874e2322007-11-15 10:28:18 +00002268 false, argType, SourceLocation(),
2269 SourceLocation()));
2270 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002271 &ClsExprs[0],
2272 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00002273 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002274 InitExprs.push_back(
Douglas Gregor49badde2008-10-27 19:41:14 +00002275 // set 'super class', using objc_getClass().
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002276 new CStyleCastExpr(Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002277 Cls, Context->getObjCIdType(), SourceLocation(), SourceLocation()));
Steve Naroff874e2322007-11-15 10:28:18 +00002278 // struct objc_super
2279 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00002280 Expr *SuperRep;
2281
2282 if (LangOpts.Microsoft) {
2283 SynthSuperContructorFunctionDecl();
2284 // Simulate a contructor call...
2285 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
2286 superType, SourceLocation());
2287 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
2288 superType, SourceLocation());
2289 } else {
2290 // (struct objc_super) { <exprs from above> }
2291 InitListExpr *ILE = new InitListExpr(SourceLocation(),
2292 &InitExprs[0], InitExprs.size(),
Chris Lattner418f6c72008-10-26 23:43:26 +00002293 SourceLocation(), false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002294 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
2295 }
Steve Naroff874e2322007-11-15 10:28:18 +00002296 // struct objc_super *
2297 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2298 Context->getPointerType(SuperRep->getType()),
2299 SourceLocation());
2300 MsgExprs.push_back(Unop);
2301 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002302 // Remove all type-casts because it may contain objc-style types; e.g.
2303 // Foo<Proto> *.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002304 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002305 recExpr = CE->getSubExpr();
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002306 recExpr = new CStyleCastExpr(Context->getObjCIdType(), recExpr,
Douglas Gregor49badde2008-10-27 19:41:14 +00002307 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002308 SourceLocation(), SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00002309 MsgExprs.push_back(recExpr);
2310 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002311 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00002312 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002313 llvm::SmallVector<Expr*, 8> SelExprs;
2314 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner077bf5e2008-11-24 03:33:13 +00002315 SelExprs.push_back(new StringLiteral(Exp->getSelector().getAsString().c_str(),
2316 Exp->getSelector().getAsString().size(),
Steve Naroff934f2762007-10-24 22:48:43 +00002317 false, argType, SourceLocation(),
2318 SourceLocation()));
2319 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2320 &SelExprs[0], SelExprs.size());
2321 MsgExprs.push_back(SelExp);
2322
2323 // Now push any user supplied arguments.
2324 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002325 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002326 // Make all implicit casts explicit...ICE comes in handy:-)
2327 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2328 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregor49badde2008-10-27 19:41:14 +00002329 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002330 ? Context->getObjCIdType()
Douglas Gregor49badde2008-10-27 19:41:14 +00002331 : ICE->getType();
Steve Naroffb2f9e512008-11-03 23:29:32 +00002332 userExpr = new CStyleCastExpr(type, userExpr, type, SourceLocation(), SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002333 }
2334 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002335 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002336 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002337 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002338 userExpr = CE->getSubExpr();
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002339 userExpr = new CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002340 userExpr, Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002341 SourceLocation(), SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002342 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00002343 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002344 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00002345 // We've transferred the ownership to MsgExprs. Null out the argument in
2346 // the original expression, since we will delete it below.
2347 Exp->setArg(i, 0);
2348 }
Steve Naroffab972d32007-11-04 22:37:50 +00002349 // Generate the funky cast.
2350 CastExpr *cast;
2351 llvm::SmallVector<QualType, 8> ArgTypes;
2352 QualType returnType;
2353
2354 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002355 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2356 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2357 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002358 ArgTypes.push_back(Context->getObjCIdType());
2359 ArgTypes.push_back(Context->getObjCSelType());
2360 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002361 // Push any user argument types.
Chris Lattner58cce3b2008-03-16 01:07:14 +00002362 for (unsigned i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002363 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
2364 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002365 : mDecl->getParamDecl(i)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00002366 // Make sure we convert "t (^)(...)" to "t (*)(...)".
2367 if (isBlockPointerType(t)) {
2368 const BlockPointerType *BPT = t->getAsBlockPointerType();
2369 t = Context->getPointerType(BPT->getPointeeType());
2370 }
Steve Naroff352336b2007-11-05 14:36:37 +00002371 ArgTypes.push_back(t);
2372 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002373 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
2374 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00002375 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002376 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002377 }
2378 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002379 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00002380
2381 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002382 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
2383 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002384
2385 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2386 // If we don't do this cast, we get the following bizarre warning/note:
2387 // xx.m:13: warning: function called through a non-compatible type
2388 // xx.m:13: note: if this code is reached, the program will abort
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002389 cast = new CStyleCastExpr(Context->getPointerType(Context->VoidTy), DRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002390 Context->getPointerType(Context->VoidTy),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002391 SourceLocation(), SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00002392
Steve Naroffab972d32007-11-04 22:37:50 +00002393 // Now do the "normal" pointer to function cast.
2394 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002395 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00002396 // If we don't have a method decl, force a variadic cast.
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002397 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Naroffab972d32007-11-04 22:37:50 +00002398 castType = Context->getPointerType(castType);
Steve Naroffb2f9e512008-11-03 23:29:32 +00002399 cast = new CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002400
2401 // Don't forget the parens to enforce the proper binding.
2402 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2403
2404 const FunctionType *FT = msgSendType->getAsFunctionType();
2405 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2406 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002407 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002408 if (MsgSendStretFlavor) {
2409 // We have the method which returns a struct/union. Must also generate
2410 // call to objc_msgSend_stret and hang both varieties on a conditional
2411 // expression which dictate which one to envoke depending on size of
2412 // method's return type.
2413
2414 // Create a reference to the objc_msgSend_stret() declaration.
2415 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
2416 SourceLocation());
2417 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002418 cast = new CStyleCastExpr(Context->getPointerType(Context->VoidTy), STDRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002419 Context->getPointerType(Context->VoidTy),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002420 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002421 // Now do the "normal" pointer to function cast.
2422 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002423 &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002424 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002425 castType = Context->getPointerType(castType);
Steve Naroffb2f9e512008-11-03 23:29:32 +00002426 cast = new CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002427
2428 // Don't forget the parens to enforce the proper binding.
2429 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2430
2431 FT = msgSendType->getAsFunctionType();
2432 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2433 FT->getResultType(), SourceLocation());
2434
2435 // Build sizeof(returnType)
Sebastian Redl05189992008-11-11 17:56:53 +00002436 SizeOfAlignOfExpr *sizeofExpr = new SizeOfAlignOfExpr(true, true,
2437 returnType.getAsOpaquePtr(),
2438 Context->getSizeType(),
2439 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002440 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2441 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2442 // For X86 it is more complicated and some kind of target specific routine
2443 // is needed to decide what to do.
Chris Lattner98be4942008-03-05 18:54:05 +00002444 unsigned IntSize =
2445 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002446 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2447 Context->IntTy,
2448 SourceLocation());
2449 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2450 BinaryOperator::LE,
2451 Context->IntTy,
2452 SourceLocation());
2453 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2454 ConditionalOperator *CondExpr =
2455 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002456 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002457 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002458 return ReplacingStmt;
2459}
2460
Steve Naroffb29b4272008-04-14 22:03:09 +00002461Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002462 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff80c28552008-10-27 20:54:44 +00002463
Steve Naroffc77a6362008-12-04 16:24:46 +00002464 //ReplacingStmt->dump();
Steve Naroff934f2762007-10-24 22:48:43 +00002465 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002466 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff934f2762007-10-24 22:48:43 +00002467
Steve Naroff4c3580e2008-12-04 23:50:32 +00002468 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002469 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002470}
2471
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002472/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2473/// call to objc_getProtocol("proto-name").
Steve Naroffb29b4272008-04-14 22:03:09 +00002474Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002475 if (!GetProtocolFunctionDecl)
2476 SynthGetProtocolFunctionDecl();
2477 // Create a call to objc_getProtocol("ProtocolName").
2478 llvm::SmallVector<Expr*, 8> ProtoExprs;
2479 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner8ec03f52008-11-24 03:54:41 +00002480 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getNameAsCString(),
2481 strlen(Exp->getProtocol()->getNameAsCString()),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002482 false, argType, SourceLocation(),
2483 SourceLocation()));
2484 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2485 &ProtoExprs[0],
2486 ProtoExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002487 ReplaceStmt(Exp, ProtoExp);
Steve Naroff4c3580e2008-12-04 23:50:32 +00002488 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002489 return ProtoExp;
2490
2491}
2492
Steve Naroffbaf58c32008-05-31 14:15:04 +00002493bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
2494 const char *endBuf) {
2495 while (startBuf < endBuf) {
2496 if (*startBuf == '#') {
2497 // Skip whitespace.
2498 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2499 ;
2500 if (!strncmp(startBuf, "if", strlen("if")) ||
2501 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2502 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2503 !strncmp(startBuf, "define", strlen("define")) ||
2504 !strncmp(startBuf, "undef", strlen("undef")) ||
2505 !strncmp(startBuf, "else", strlen("else")) ||
2506 !strncmp(startBuf, "elif", strlen("elif")) ||
2507 !strncmp(startBuf, "endif", strlen("endif")) ||
2508 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2509 !strncmp(startBuf, "include", strlen("include")) ||
2510 !strncmp(startBuf, "import", strlen("import")) ||
2511 !strncmp(startBuf, "include_next", strlen("include_next")))
2512 return true;
2513 }
2514 startBuf++;
2515 }
2516 return false;
2517}
2518
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002519/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002520/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00002521void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002522 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002523 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Chris Lattner8ec03f52008-11-24 03:54:41 +00002524 assert(CDecl->getNameAsCString() &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002525 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002526 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002527 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002528 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002529 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002530 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00002531 SourceLocation LocStart = CDecl->getLocStart();
2532 SourceLocation LocEnd = CDecl->getLocEnd();
2533
2534 const char *startBuf = SM->getCharacterData(LocStart);
2535 const char *endBuf = SM->getCharacterData(LocEnd);
Steve Naroffbaf58c32008-05-31 14:15:04 +00002536
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002537 // If no ivars and no root or if its root, directly or indirectly,
2538 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002539 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2540 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002541 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattneraadaf782008-01-31 19:51:04 +00002542 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002543 return;
2544 }
2545
2546 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002547 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002548 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002549 Result += CDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002550 if (LangOpts.Microsoft)
2551 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00002552
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002553 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002554 const char *cursor = strchr(startBuf, '{');
2555 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002556 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00002557 // If the buffer contains preprocessor directives, we do more fine-grained
2558 // rewrites. This is intended to fix code that looks like (which occurs in
2559 // NSURL.h, for example):
2560 //
2561 // #ifdef XYZ
2562 // @interface Foo : NSObject
2563 // #else
2564 // @interface FooBar : NSObject
2565 // #endif
2566 // {
2567 // int i;
2568 // }
2569 // @end
2570 //
2571 // This clause is segregated to avoid breaking the common case.
2572 if (BufferContainsPPDirectives(startBuf, cursor)) {
2573 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
2574 CDecl->getClassLoc();
2575 const char *endHeader = SM->getCharacterData(L);
2576 endHeader += Lexer::MeasureTokenLength(L, *SM);
2577
Chris Lattner3db6cae2008-07-21 18:19:38 +00002578 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00002579 // advance to the end of the referenced protocols.
2580 while (endHeader < cursor && *endHeader != '>') endHeader++;
2581 endHeader++;
2582 }
2583 // rewrite the original header
2584 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2585 } else {
2586 // rewrite the original header *without* disturbing the '{'
2587 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
2588 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002589 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002590 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002591 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002592 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002593 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00002594 Result += "_IVARS;\n";
Steve Narofffea763e82007-11-14 19:25:57 +00002595
2596 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002597 SourceLocation OnePastCurly =
2598 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2599 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002600 }
2601 cursor++; // past '{'
2602
2603 // Now comment out any visibility specifiers.
2604 while (cursor < endBuf) {
2605 if (*cursor == '@') {
2606 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002607 // Skip whitespace.
2608 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2609 /*scan*/;
2610
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002611 // FIXME: presence of @public, etc. inside comment results in
2612 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002613 if (!strncmp(cursor, "public", strlen("public")) ||
2614 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00002615 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002616 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002617 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002618 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002619 // FIXME: If there are cases where '<' is used in ivar declaration part
2620 // of user code, then scan the ivar list and use needToScanForQualifiers
2621 // for type checking.
2622 else if (*cursor == '<') {
2623 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002624 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002625 cursor = strchr(cursor, '>');
2626 cursor++;
2627 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002628 InsertText(atLoc, " */", 3);
Steve Naroffced80a82008-10-30 12:09:33 +00002629 } else if (*cursor == '^') { // rewrite block specifier.
2630 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2631 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002632 }
Steve Narofffea763e82007-11-14 19:25:57 +00002633 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002634 }
Steve Narofffea763e82007-11-14 19:25:57 +00002635 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002636 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00002637 } else { // we don't have any instance variables - insert super struct.
2638 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2639 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002640 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002641 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002642 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00002643 Result += "_IVARS;\n};\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00002644 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002645 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002646 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002647 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00002648 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002649}
2650
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002651// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002652/// class methods.
Steve Naroffb29b4272008-04-14 22:03:09 +00002653void RewriteObjC::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002654 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002655 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002656 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002657 const char *ClassName,
2658 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002659 if (MethodBegin == MethodEnd) return;
2660
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002661 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002662 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002663 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002664 SEL _cmd;
2665 char *method_types;
2666 void *_imp;
2667 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002668 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002669 Result += "\nstruct _objc_method {\n";
2670 Result += "\tSEL _cmd;\n";
2671 Result += "\tchar *method_types;\n";
2672 Result += "\tvoid *_imp;\n";
2673 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002674
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002675 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002676 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002677
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002678 // Build _objc_method_list for class's methods if needed
Steve Naroff946a6932008-03-11 00:12:29 +00002679
2680 /* struct {
2681 struct _objc_method_list *next_method;
2682 int method_count;
2683 struct _objc_method method_list[];
2684 }
2685 */
2686 Result += "\nstatic struct {\n";
2687 Result += "\tstruct _objc_method_list *next_method;\n";
2688 Result += "\tint method_count;\n";
2689 Result += "\tstruct _objc_method method_list[";
2690 Result += utostr(MethodEnd-MethodBegin);
2691 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002692 Result += prefix;
2693 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2694 Result += "_METHODS_";
2695 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002696 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002697 Result += IsInstanceMethod ? "inst" : "cls";
2698 Result += "_meth\")))= ";
2699 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002700
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002701 Result += "\t,{{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002702 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002703 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002704 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002705 Result += "\", \"";
2706 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002707 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002708 Result += MethodInternalNames[*MethodBegin];
2709 Result += "}\n";
2710 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2711 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002712 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002713 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002714 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002715 Result += "\", \"";
2716 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002717 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002718 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002719 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002720 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002721 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002722}
2723
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002724/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00002725void RewriteObjC::
2726RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
2727 const char *prefix,
2728 const char *ClassName,
2729 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002730 static bool objc_protocol_methods = false;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002731 if (Protocols.empty()) return;
2732
2733 for (unsigned i = 0; i != Protocols.size(); i++) {
2734 ObjCProtocolDecl *PDecl = Protocols[i];
2735 // Output struct protocol_methods holder of method selector and type.
2736 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
2737 /* struct protocol_methods {
2738 SEL _cmd;
2739 char *method_types;
2740 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002741 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002742 Result += "\nstruct protocol_methods {\n";
2743 Result += "\tSEL _cmd;\n";
2744 Result += "\tchar *method_types;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002745 Result += "};\n";
Steve Narofffbfe8252008-05-06 18:26:51 +00002746
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002747 objc_protocol_methods = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002748 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002749 // Do not synthesize the protocol more than once.
2750 if (ObjCSynthesizedProtocols.count(PDecl))
2751 continue;
2752
2753 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2754 unsigned NumMethods = PDecl->getNumInstanceMethods();
2755 /* struct _objc_protocol_method_list {
2756 int protocol_method_count;
2757 struct protocol_methods protocols[];
2758 }
2759 */
2760 Result += "\nstatic struct {\n";
2761 Result += "\tint protocol_method_count;\n";
2762 Result += "\tstruct protocol_methods protocols[";
2763 Result += utostr(NumMethods);
2764 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002765 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002766 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
2767 "{\n\t" + utostr(NumMethods) + "\n";
2768
2769 // Output instance methods declared in this protocol.
2770 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
2771 E = PDecl->instmeth_end(); I != E; ++I) {
2772 if (I == PDecl->instmeth_begin())
2773 Result += "\t ,{{(SEL)\"";
2774 else
2775 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002776 Result += (*I)->getSelector().getAsString().c_str();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002777 std::string MethodTypeString;
2778 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2779 Result += "\", \"";
2780 Result += MethodTypeString;
2781 Result += "\"}\n";
2782 }
2783 Result += "\t }\n};\n";
2784 }
2785
2786 // Output class methods declared in this protocol.
2787 int NumMethods = PDecl->getNumClassMethods();
2788 if (NumMethods > 0) {
2789 /* struct _objc_protocol_method_list {
2790 int protocol_method_count;
2791 struct protocol_methods protocols[];
2792 }
2793 */
2794 Result += "\nstatic struct {\n";
2795 Result += "\tint protocol_method_count;\n";
2796 Result += "\tstruct protocol_methods protocols[";
2797 Result += utostr(NumMethods);
2798 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002799 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002800 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2801 "{\n\t";
2802 Result += utostr(NumMethods);
2803 Result += "\n";
2804
2805 // Output instance methods declared in this protocol.
2806 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
2807 E = PDecl->classmeth_end(); I != E; ++I) {
2808 if (I == PDecl->classmeth_begin())
2809 Result += "\t ,{{(SEL)\"";
2810 else
2811 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002812 Result += (*I)->getSelector().getAsString().c_str();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002813 std::string MethodTypeString;
2814 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2815 Result += "\", \"";
2816 Result += MethodTypeString;
2817 Result += "\"}\n";
2818 }
2819 Result += "\t }\n};\n";
2820 }
2821
2822 // Output:
2823 /* struct _objc_protocol {
2824 // Objective-C 1.0 extensions
2825 struct _objc_protocol_extension *isa;
2826 char *protocol_name;
2827 struct _objc_protocol **protocol_list;
2828 struct _objc_protocol_method_list *instance_methods;
2829 struct _objc_protocol_method_list *class_methods;
2830 };
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002831 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002832 static bool objc_protocol = false;
2833 if (!objc_protocol) {
2834 Result += "\nstruct _objc_protocol {\n";
2835 Result += "\tstruct _objc_protocol_extension *isa;\n";
2836 Result += "\tchar *protocol_name;\n";
2837 Result += "\tstruct _objc_protocol **protocol_list;\n";
2838 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2839 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2840 Result += "};\n";
2841
2842 objc_protocol = true;
2843 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002844
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002845 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002846 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002847 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
2848 "{\n\t0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002849 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002850 Result += "\", 0, ";
2851 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2852 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002853 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002854 Result += ", ";
2855 }
2856 else
2857 Result += "0, ";
2858 if (PDecl->getNumClassMethods() > 0) {
2859 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002860 Result += PDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002861 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002862 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002863 else
2864 Result += "0\n";
2865 Result += "};\n";
2866
2867 // Mark this protocol as having been generated.
2868 if (!ObjCSynthesizedProtocols.insert(PDecl))
2869 assert(false && "protocol already synthesized");
2870 }
2871 // Output the top lovel protocol meta-data for the class.
2872 /* struct _objc_protocol_list {
2873 struct _objc_protocol_list *next;
2874 int protocol_count;
2875 struct _objc_protocol *class_protocols[];
2876 }
2877 */
2878 Result += "\nstatic struct {\n";
2879 Result += "\tstruct _objc_protocol_list *next;\n";
2880 Result += "\tint protocol_count;\n";
2881 Result += "\tstruct _objc_protocol *class_protocols[";
2882 Result += utostr(Protocols.size());
2883 Result += "];\n} _OBJC_";
2884 Result += prefix;
2885 Result += "_PROTOCOLS_";
2886 Result += ClassName;
2887 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2888 "{\n\t0, ";
2889 Result += utostr(Protocols.size());
2890 Result += "\n";
2891
2892 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002893 Result += Protocols[0]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002894 Result += " \n";
2895
2896 for (unsigned i = 1; i != Protocols.size(); i++) {
2897 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002898 Result += Protocols[i]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002899 Result += "\n";
2900 }
2901 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002902}
2903
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002904/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002905/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00002906void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002907 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002908 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002909 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002910 ObjCCategoryDecl *CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002911 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2912 CDecl = CDecl->getNextClassCategory())
2913 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2914 break;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002915
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002916 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00002917 FullCategoryName += '_';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002918 FullCategoryName += IDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00002919
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002920 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002921 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002922 true, "CATEGORY_", FullCategoryName.c_str(),
2923 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002924
2925 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002926 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002927 false, "CATEGORY_", FullCategoryName.c_str(),
2928 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002929
2930 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002931 // Null CDecl is case of a category implementation with no category interface
2932 if (CDecl)
Chris Lattner780f3292008-07-21 21:32:27 +00002933 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Chris Lattnereb44eee2007-12-23 01:40:15 +00002934 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002935
2936 /* struct _objc_category {
2937 char *category_name;
2938 char *class_name;
2939 struct _objc_method_list *instance_methods;
2940 struct _objc_method_list *class_methods;
2941 struct _objc_protocol_list *protocols;
2942 // Objective-C 1.0 extensions
2943 uint32_t size; // sizeof (struct _objc_category)
2944 struct _objc_property_list *instance_properties; // category's own
2945 // @property decl.
2946 };
2947 */
2948
2949 static bool objc_category = false;
2950 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002951 Result += "\nstruct _objc_category {\n";
2952 Result += "\tchar *category_name;\n";
2953 Result += "\tchar *class_name;\n";
2954 Result += "\tstruct _objc_method_list *instance_methods;\n";
2955 Result += "\tstruct _objc_method_list *class_methods;\n";
2956 Result += "\tstruct _objc_protocol_list *protocols;\n";
2957 Result += "\tunsigned int size;\n";
2958 Result += "\tstruct _objc_property_list *instance_properties;\n";
2959 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002960 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002961 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002962 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2963 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002964 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002965 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002966 Result += "\"\n\t, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002967 Result += ClassDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002968 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002969
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002970 if (IDecl->getNumInstanceMethods() > 0) {
2971 Result += "\t, (struct _objc_method_list *)"
2972 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2973 Result += FullCategoryName;
2974 Result += "\n";
2975 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002976 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002977 Result += "\t, 0\n";
2978 if (IDecl->getNumClassMethods() > 0) {
2979 Result += "\t, (struct _objc_method_list *)"
2980 "&_OBJC_CATEGORY_CLASS_METHODS_";
2981 Result += FullCategoryName;
2982 Result += "\n";
2983 }
2984 else
2985 Result += "\t, 0\n";
2986
Chris Lattner780f3292008-07-21 21:32:27 +00002987 if (CDecl && !CDecl->getReferencedProtocols().empty()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002988 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2989 Result += FullCategoryName;
2990 Result += "\n";
2991 }
2992 else
2993 Result += "\t, 0\n";
2994 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002995}
2996
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002997/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2998/// ivar offset.
Steve Naroffb29b4272008-04-14 22:03:09 +00002999void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003000 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003001 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00003002 if (ivar->isBitField()) {
3003 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3004 // place all bitfields at offset 0.
3005 Result += "0";
3006 } else {
3007 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003008 Result += IDecl->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003009 if (LangOpts.Microsoft)
3010 Result += "_IMPL";
3011 Result += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003012 Result += ivar->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003013 Result += ")";
3014 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003015}
3016
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003017//===----------------------------------------------------------------------===//
3018// Meta Data Emission
3019//===----------------------------------------------------------------------===//
3020
Steve Naroffb29b4272008-04-14 22:03:09 +00003021void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003022 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003023 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003024
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003025 // Explictly declared @interface's are already synthesized.
3026 if (CDecl->ImplicitInterfaceDecl()) {
3027 // FIXME: Implementation of a class with no @interface (legacy) doese not
3028 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003029 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003030 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003031
Chris Lattnerbe6df082007-12-12 07:56:42 +00003032 // Build _objc_ivar_list metadata for classes ivars if needed
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003033 unsigned NumIvars = !IDecl->ivar_empty()
3034 ? IDecl->ivar_size()
3035 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003036 if (NumIvars > 0) {
3037 static bool objc_ivar = false;
3038 if (!objc_ivar) {
3039 /* struct _objc_ivar {
3040 char *ivar_name;
3041 char *ivar_type;
3042 int ivar_offset;
3043 };
3044 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003045 Result += "\nstruct _objc_ivar {\n";
3046 Result += "\tchar *ivar_name;\n";
3047 Result += "\tchar *ivar_type;\n";
3048 Result += "\tint ivar_offset;\n";
3049 Result += "};\n";
3050
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003051 objc_ivar = true;
3052 }
3053
Steve Naroff946a6932008-03-11 00:12:29 +00003054 /* struct {
3055 int ivar_count;
3056 struct _objc_ivar ivar_list[nIvars];
3057 };
3058 */
3059 Result += "\nstatic struct {\n";
3060 Result += "\tint ivar_count;\n";
3061 Result += "\tstruct _objc_ivar ivar_list[";
3062 Result += utostr(NumIvars);
3063 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003064 Result += IDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003065 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003066 "{\n\t";
3067 Result += utostr(NumIvars);
3068 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003069
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003070 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003071 if (!IDecl->ivar_empty()) {
Chris Lattnerbe6df082007-12-12 07:56:42 +00003072 IVI = IDecl->ivar_begin();
3073 IVE = IDecl->ivar_end();
3074 } else {
3075 IVI = CDecl->ivar_begin();
3076 IVE = CDecl->ivar_end();
3077 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003078 Result += "\t,{{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003079 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003080 Result += "\", \"";
3081 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003082 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003083 Result += StrEncoding;
3084 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003085 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003086 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003087 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003088 Result += "\t ,{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003089 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003090 Result += "\", \"";
3091 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003092 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003093 Result += StrEncoding;
3094 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003095 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003096 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003097 }
3098
3099 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003100 }
3101
3102 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003103 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003104 true, "", IDecl->getNameAsCString(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003105
3106 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003107 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003108 false, "", IDecl->getNameAsCString(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003109
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003110 // Protocols referenced in class declaration?
Chris Lattner780f3292008-07-21 21:32:27 +00003111 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003112 "CLASS", CDecl->getNameAsCString(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003113
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003114
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003115 // Declaration of class/meta-class metadata
3116 /* struct _objc_class {
3117 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003118 const char *super_class_name;
3119 char *name;
3120 long version;
3121 long info;
3122 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003123 struct _objc_ivar_list *ivars;
3124 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003125 struct objc_cache *cache;
3126 struct objc_protocol_list *protocols;
3127 const char *ivar_layout;
3128 struct _objc_class_ext *ext;
3129 };
3130 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003131 static bool objc_class = false;
3132 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003133 Result += "\nstruct _objc_class {\n";
3134 Result += "\tstruct _objc_class *isa;\n";
3135 Result += "\tconst char *super_class_name;\n";
3136 Result += "\tchar *name;\n";
3137 Result += "\tlong version;\n";
3138 Result += "\tlong info;\n";
3139 Result += "\tlong instance_size;\n";
3140 Result += "\tstruct _objc_ivar_list *ivars;\n";
3141 Result += "\tstruct _objc_method_list *methods;\n";
3142 Result += "\tstruct objc_cache *cache;\n";
3143 Result += "\tstruct _objc_protocol_list *protocols;\n";
3144 Result += "\tconst char *ivar_layout;\n";
3145 Result += "\tstruct _objc_class_ext *ext;\n";
3146 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003147 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003148 }
3149
3150 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003151 ObjCInterfaceDecl *RootClass = 0;
3152 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003153 while (SuperClass) {
3154 RootClass = SuperClass;
3155 SuperClass = SuperClass->getSuperClass();
3156 }
3157 SuperClass = CDecl->getSuperClass();
3158
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003159 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003160 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003161 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003162 "{\n\t(struct _objc_class *)\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003163 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003164 Result += "\"";
3165
3166 if (SuperClass) {
3167 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003168 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003169 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003170 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003171 Result += "\"";
3172 }
3173 else {
3174 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003175 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003176 Result += "\"";
3177 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003178 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003179 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003180 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffb26d7132007-12-05 21:49:40 +00003181 if (IDecl->getNumClassMethods() > 0) {
Steve Naroff23f41272008-03-11 18:14:26 +00003182 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003183 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003184 Result += "\n";
3185 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003186 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003187 Result += ", 0\n";
Chris Lattner3db6cae2008-07-21 18:19:38 +00003188 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003189 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003190 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003191 Result += ",0,0\n";
3192 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003193 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003194 Result += "\t,0,0,0,0\n";
3195 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003196
3197 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003198 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003199 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003200 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003201 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003202 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003203 if (SuperClass) {
3204 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003205 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003206 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003207 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003208 Result += "\"";
3209 }
3210 else {
3211 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003212 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003213 Result += "\"";
3214 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003215 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003216 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003217 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003218 Result += ",0";
3219 else {
3220 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003221 Result += ",sizeof(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003222 Result += CDecl->getNameAsString();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003223 if (LangOpts.Microsoft)
3224 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003225 Result += ")";
3226 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003227 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00003228 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003229 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003230 Result += "\n\t";
3231 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003232 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003233 Result += ",0";
3234 if (IDecl->getNumInstanceMethods() > 0) {
Steve Naroff946a6932008-03-11 00:12:29 +00003235 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003236 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003237 Result += ", 0\n\t";
3238 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003239 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003240 Result += ",0,0";
Chris Lattner3db6cae2008-07-21 18:19:38 +00003241 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003242 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003243 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003244 Result += ", 0,0\n";
3245 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003246 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003247 Result += ",0,0,0\n";
3248 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003249}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003250
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003251/// RewriteImplementations - This routine rewrites all method implementations
3252/// and emits meta-data.
3253
Steve Narofface66252008-11-13 20:07:04 +00003254void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003255 int ClsDefCount = ClassImplementation.size();
3256 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003257
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003258 // Rewrite implemented methods
3259 for (int i = 0; i < ClsDefCount; i++)
3260 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003261
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003262 for (int i = 0; i < CatDefCount; i++)
3263 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00003264}
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003265
Steve Narofface66252008-11-13 20:07:04 +00003266void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3267 int ClsDefCount = ClassImplementation.size();
3268 int CatDefCount = CategoryImplementation.size();
3269
Steve Naroff5df5b762008-05-07 21:23:49 +00003270 // This is needed for determining instance variable offsets.
Steve Naroffa11440b2008-08-05 18:47:23 +00003271 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003272 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003273 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003274 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003275
3276 // For each implemented category, write out all its meta data.
3277 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003278 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003279
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003280 // Write objc_symtab metadata
3281 /*
3282 struct _objc_symtab
3283 {
3284 long sel_ref_cnt;
3285 SEL *refs;
3286 short cls_def_cnt;
3287 short cat_def_cnt;
3288 void *defs[cls_def_cnt + cat_def_cnt];
3289 };
3290 */
3291
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003292 Result += "\nstruct _objc_symtab {\n";
3293 Result += "\tlong sel_ref_cnt;\n";
3294 Result += "\tSEL *refs;\n";
3295 Result += "\tshort cls_def_cnt;\n";
3296 Result += "\tshort cat_def_cnt;\n";
3297 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3298 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003299
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003300 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00003301 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003302 Result += "\t0, 0, " + utostr(ClsDefCount)
3303 + ", " + utostr(CatDefCount) + "\n";
3304 for (int i = 0; i < ClsDefCount; i++) {
3305 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003306 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003307 Result += "\n";
3308 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003309
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003310 for (int i = 0; i < CatDefCount; i++) {
3311 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003312 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003313 Result += "_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003314 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003315 Result += "\n";
3316 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003317
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003318 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003319
3320 // Write objc_module metadata
3321
3322 /*
3323 struct _objc_module {
3324 long version;
3325 long size;
3326 const char *name;
3327 struct _objc_symtab *symtab;
3328 }
3329 */
3330
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003331 Result += "\nstruct _objc_module {\n";
3332 Result += "\tlong version;\n";
3333 Result += "\tlong size;\n";
3334 Result += "\tconst char *name;\n";
3335 Result += "\tstruct _objc_symtab *symtab;\n";
3336 Result += "};\n\n";
3337 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00003338 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003339 Result += "\t" + utostr(OBJC_ABI_VERSION) +
3340 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003341 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003342
3343 if (LangOpts.Microsoft) {
3344 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00003345 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003346 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3347 Result += "&_OBJC_MODULES;\n";
3348 Result += "#pragma data_seg(pop)\n\n";
3349 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003350}
Chris Lattner311ff022007-10-16 22:36:42 +00003351
Steve Naroff54055232008-10-27 17:20:55 +00003352std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3353 const char *funcName,
3354 std::string Tag) {
3355 const FunctionType *AFT = CE->getFunctionType();
3356 QualType RT = AFT->getResultType();
3357 std::string StructRef = "struct " + Tag;
3358 std::string S = "static " + RT.getAsString() + " __" +
3359 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003360
Steve Naroff54055232008-10-27 17:20:55 +00003361 BlockDecl *BD = CE->getBlockDecl();
3362
3363 if (isa<FunctionTypeNoProto>(AFT)) {
3364 S += "()";
3365 } else if (BD->param_empty()) {
3366 S += "(" + StructRef + " *__cself)";
3367 } else {
3368 const FunctionTypeProto *FT = cast<FunctionTypeProto>(AFT);
3369 assert(FT && "SynthesizeBlockFunc: No function proto");
3370 S += '(';
3371 // first add the implicit argument.
3372 S += StructRef + " *__cself, ";
3373 std::string ParamStr;
3374 for (BlockDecl::param_iterator AI = BD->param_begin(),
3375 E = BD->param_end(); AI != E; ++AI) {
3376 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003377 ParamStr = (*AI)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003378 (*AI)->getType().getAsStringInternal(ParamStr);
3379 S += ParamStr;
3380 }
3381 if (FT->isVariadic()) {
3382 if (!BD->param_empty()) S += ", ";
3383 S += "...";
3384 }
3385 S += ')';
3386 }
3387 S += " {\n";
3388
3389 // Create local declarations to avoid rewriting all closure decl ref exprs.
3390 // First, emit a declaration for all "by ref" decls.
3391 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3392 E = BlockByRefDecls.end(); I != E; ++I) {
3393 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003394 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003395 Context->getPointerType((*I)->getType()).getAsStringInternal(Name);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003396 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Steve Naroff54055232008-10-27 17:20:55 +00003397 }
3398 // Next, emit a declaration for all "by copy" declarations.
3399 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3400 E = BlockByCopyDecls.end(); I != E; ++I) {
3401 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003402 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003403 // Handle nested closure invocation. For example:
3404 //
3405 // void (^myImportedClosure)(void);
3406 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3407 //
3408 // void (^anotherClosure)(void);
3409 // anotherClosure = ^(void) {
3410 // myImportedClosure(); // import and invoke the closure
3411 // };
3412 //
3413 if (isBlockPointerType((*I)->getType()))
3414 S += "struct __block_impl *";
3415 else
3416 (*I)->getType().getAsStringInternal(Name);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003417 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff54055232008-10-27 17:20:55 +00003418 }
3419 std::string RewrittenStr = RewrittenBlockExprs[CE];
3420 const char *cstr = RewrittenStr.c_str();
3421 while (*cstr++ != '{') ;
3422 S += cstr;
3423 S += "\n";
3424 return S;
3425}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003426
Steve Naroff54055232008-10-27 17:20:55 +00003427std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3428 const char *funcName,
3429 std::string Tag) {
3430 std::string StructRef = "struct " + Tag;
3431 std::string S = "static void __";
3432
3433 S += funcName;
3434 S += "_block_copy_" + utostr(i);
3435 S += "(" + StructRef;
3436 S += "*dst, " + StructRef;
3437 S += "*src) {";
3438 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3439 E = ImportedBlockDecls.end(); I != E; ++I) {
3440 S += "_Block_copy_assign(&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003441 S += (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003442 S += ", src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003443 S += (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003444 S += ");}";
3445 }
3446 S += "\nstatic void __";
3447 S += funcName;
3448 S += "_block_dispose_" + utostr(i);
3449 S += "(" + StructRef;
3450 S += "*src) {";
3451 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3452 E = ImportedBlockDecls.end(); I != E; ++I) {
3453 S += "_Block_destroy(src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003454 S += (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003455 S += ");";
3456 }
3457 S += "}\n";
3458 return S;
3459}
3460
3461std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3462 bool hasCopyDisposeHelpers) {
Steve Naroffced80a82008-10-30 12:09:33 +00003463 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00003464 std::string Constructor = " " + Tag;
3465
3466 S += " {\n struct __block_impl impl;\n";
3467
3468 if (hasCopyDisposeHelpers)
3469 S += " void *copy;\n void *dispose;\n";
3470
3471 Constructor += "(void *fp";
3472
3473 if (hasCopyDisposeHelpers)
3474 Constructor += ", void *copyHelp, void *disposeHelp";
3475
3476 if (BlockDeclRefs.size()) {
3477 // Output all "by copy" declarations.
3478 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3479 E = BlockByCopyDecls.end(); I != E; ++I) {
3480 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003481 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003482 std::string ArgName = "_" + FieldName;
3483 // Handle nested closure invocation. For example:
3484 //
3485 // void (^myImportedBlock)(void);
3486 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3487 //
3488 // void (^anotherBlock)(void);
3489 // anotherBlock = ^(void) {
3490 // myImportedBlock(); // import and invoke the closure
3491 // };
3492 //
3493 if (isBlockPointerType((*I)->getType())) {
3494 S += "struct __block_impl *";
3495 Constructor += ", void *" + ArgName;
3496 } else {
3497 (*I)->getType().getAsStringInternal(FieldName);
3498 (*I)->getType().getAsStringInternal(ArgName);
3499 Constructor += ", " + ArgName;
3500 }
3501 S += FieldName + ";\n";
3502 }
3503 // Output all "by ref" declarations.
3504 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3505 E = BlockByRefDecls.end(); I != E; ++I) {
3506 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003507 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003508 std::string ArgName = "_" + FieldName;
3509 // Handle nested closure invocation. For example:
3510 //
3511 // void (^myImportedBlock)(void);
3512 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3513 //
3514 // void (^anotherBlock)(void);
3515 // anotherBlock = ^(void) {
3516 // myImportedBlock(); // import and invoke the closure
3517 // };
3518 //
3519 if (isBlockPointerType((*I)->getType())) {
3520 S += "struct __block_impl *";
3521 Constructor += ", void *" + ArgName;
3522 } else {
3523 Context->getPointerType((*I)->getType()).getAsStringInternal(FieldName);
3524 Context->getPointerType((*I)->getType()).getAsStringInternal(ArgName);
3525 Constructor += ", " + ArgName;
3526 }
3527 S += FieldName + "; // by ref\n";
3528 }
3529 // Finish writing the constructor.
3530 // FIXME: handle NSConcreteGlobalBlock.
3531 Constructor += ", int flags=0) {\n";
3532 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3533 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3534
3535 if (hasCopyDisposeHelpers)
3536 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3537
3538 // Initialize all "by copy" arguments.
3539 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3540 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003541 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003542 Constructor += " ";
3543 if (isBlockPointerType((*I)->getType()))
3544 Constructor += Name + " = (struct __block_impl *)_";
3545 else
3546 Constructor += Name + " = _";
3547 Constructor += Name + ";\n";
3548 }
3549 // Initialize all "by ref" arguments.
3550 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3551 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003552 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003553 Constructor += " ";
3554 if (isBlockPointerType((*I)->getType()))
3555 Constructor += Name + " = (struct __block_impl *)_";
3556 else
3557 Constructor += Name + " = _";
3558 Constructor += Name + ";\n";
3559 }
3560 } else {
3561 // Finish writing the constructor.
3562 // FIXME: handle NSConcreteGlobalBlock.
3563 Constructor += ", int flags=0) {\n";
3564 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3565 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3566 if (hasCopyDisposeHelpers)
3567 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3568 }
3569 Constructor += " ";
3570 Constructor += "}\n";
3571 S += Constructor;
3572 S += "};\n";
3573 return S;
3574}
3575
3576void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3577 const char *FunName) {
3578 // Insert closures that were part of the function.
3579 for (unsigned i = 0; i < Blocks.size(); i++) {
3580
3581 CollectBlockDeclRefInfo(Blocks[i]);
3582
3583 std::string Tag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
3584
3585 std::string CI = SynthesizeBlockImpl(Blocks[i], Tag,
3586 ImportedBlockDecls.size() > 0);
3587
3588 InsertText(FunLocStart, CI.c_str(), CI.size());
3589
3590 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, Tag);
3591
3592 InsertText(FunLocStart, CF.c_str(), CF.size());
3593
3594 if (ImportedBlockDecls.size()) {
3595 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, Tag);
3596 InsertText(FunLocStart, HF.c_str(), HF.size());
3597 }
3598
3599 BlockDeclRefs.clear();
3600 BlockByRefDecls.clear();
3601 BlockByCopyDecls.clear();
3602 BlockCallExprs.clear();
3603 ImportedBlockDecls.clear();
3604 }
3605 Blocks.clear();
3606 RewrittenBlockExprs.clear();
3607}
3608
3609void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3610 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner8ec03f52008-11-24 03:54:41 +00003611 const char *FuncName = FD->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003612
3613 SynthesizeBlockLiterals(FunLocStart, FuncName);
3614}
3615
3616void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00003617 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3618 //SourceLocation FunLocStart = MD->getLocStart();
3619 // FIXME: This hack works around a bug in Rewrite.InsertText().
3620 SourceLocation FunLocStart = MD->getLocStart().getFileLocWithOffset(-1);
Chris Lattner077bf5e2008-11-24 03:33:13 +00003621 std::string FuncName = MD->getSelector().getAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003622 // Convert colons to underscores.
3623 std::string::size_type loc = 0;
3624 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3625 FuncName.replace(loc, 1, "_");
3626
3627 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
3628}
3629
3630void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
3631 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3632 CI != E; ++CI)
3633 if (*CI) {
3634 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3635 GetBlockDeclRefExprs(CBE->getBody());
3636 else
3637 GetBlockDeclRefExprs(*CI);
3638 }
3639 // Handle specific things.
3640 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
3641 // FIXME: Handle enums.
3642 if (!isa<FunctionDecl>(CDRE->getDecl()))
3643 BlockDeclRefs.push_back(CDRE);
3644 return;
3645}
3646
3647void RewriteObjC::GetBlockCallExprs(Stmt *S) {
3648 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3649 CI != E; ++CI)
3650 if (*CI) {
3651 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3652 GetBlockCallExprs(CBE->getBody());
3653 else
3654 GetBlockCallExprs(*CI);
3655 }
3656
3657 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
3658 if (CE->getCallee()->getType()->isBlockPointerType()) {
3659 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
3660 }
3661 }
3662 return;
3663}
3664
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003665Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00003666 // Navigate to relevant type information.
3667 const char *closureName = 0;
3668 const BlockPointerType *CPT = 0;
3669
3670 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003671 closureName = DRE->getDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003672 CPT = DRE->getType()->getAsBlockPointerType();
3673 } else if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003674 closureName = CDRE->getDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003675 CPT = CDRE->getType()->getAsBlockPointerType();
3676 } else if (MemberExpr *MExpr = dyn_cast<MemberExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003677 closureName = MExpr->getMemberDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003678 CPT = MExpr->getType()->getAsBlockPointerType();
3679 } else {
3680 assert(1 && "RewriteBlockClass: Bad type");
3681 }
3682 assert(CPT && "RewriteBlockClass: Bad type");
3683 const FunctionType *FT = CPT->getPointeeType()->getAsFunctionType();
3684 assert(FT && "RewriteBlockClass: Bad type");
3685 const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(FT);
3686 // FTP will be null for closures that don't take arguments.
3687
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003688 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
3689 SourceLocation(),
3690 &Context->Idents.get("__block_impl"));
3691 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00003692
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003693 // Generate a funky cast.
3694 llvm::SmallVector<QualType, 8> ArgTypes;
3695
3696 // Push the block argument type.
3697 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00003698 if (FTP) {
3699 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003700 E = FTP->arg_type_end(); I && (I != E); ++I) {
3701 QualType t = *I;
3702 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3703 if (isBlockPointerType(t)) {
3704 const BlockPointerType *BPT = t->getAsBlockPointerType();
3705 t = Context->getPointerType(BPT->getPointeeType());
3706 }
3707 ArgTypes.push_back(t);
3708 }
Steve Naroff54055232008-10-27 17:20:55 +00003709 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003710 // Now do the pointer to function cast.
3711 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
3712 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
3713
3714 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Steve Naroff54055232008-10-27 17:20:55 +00003715
Steve Naroffb2f9e512008-11-03 23:29:32 +00003716 CastExpr *BlkCast = new CStyleCastExpr(PtrBlock, Exp->getCallee(), PtrBlock, SourceLocation(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003717 // Don't forget the parens to enforce the proper binding.
3718 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), BlkCast);
3719 //PE->dump();
Steve Naroff54055232008-10-27 17:20:55 +00003720
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003721 FieldDecl *FD = FieldDecl::Create(*Context, SourceLocation(),
3722 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy);
3723 MemberExpr *ME = new MemberExpr(PE, true, FD, SourceLocation(), FD->getType());
3724
Steve Naroffb2f9e512008-11-03 23:29:32 +00003725 CastExpr *FunkCast = new CStyleCastExpr(PtrToFuncCastType, ME, PtrToFuncCastType, SourceLocation(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003726 PE = new ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
3727
3728 llvm::SmallVector<Expr*, 8> BlkExprs;
3729 // Add the implicit argument.
3730 BlkExprs.push_back(BlkCast);
3731 // Add the user arguments.
Steve Naroff54055232008-10-27 17:20:55 +00003732 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3733 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003734 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00003735 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003736 CallExpr *CE = new CallExpr(PE, &BlkExprs[0], BlkExprs.size(), Exp->getType(), SourceLocation());
3737 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00003738}
3739
3740void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003741 Stmt *BlockCall = SynthesizeBlockCall(Exp);
3742 ReplaceStmt(Exp, BlockCall);
Steve Naroff54055232008-10-27 17:20:55 +00003743}
3744
3745void RewriteObjC::RewriteBlockDeclRefExpr(BlockDeclRefExpr *BDRE) {
3746 // FIXME: Add more elaborate code generation required by the ABI.
3747 InsertText(BDRE->getLocStart(), "*", 1);
3748}
3749
Steve Naroffb2f9e512008-11-03 23:29:32 +00003750void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3751 SourceLocation LocStart = CE->getLParenLoc();
3752 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00003753
3754 // Need to avoid trying to rewrite synthesized casts.
3755 if (LocStart.isInvalid())
3756 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00003757 // Need to avoid trying to rewrite casts contained in macros.
3758 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3759 return;
Steve Narofffa15fd92008-10-28 20:29:00 +00003760
Steve Naroff54055232008-10-27 17:20:55 +00003761 const char *startBuf = SM->getCharacterData(LocStart);
3762 const char *endBuf = SM->getCharacterData(LocEnd);
3763
3764 // advance the location to startArgList.
3765 const char *argPtr = startBuf;
3766
3767 while (*argPtr++ && (argPtr < endBuf)) {
3768 switch (*argPtr) {
3769 case '^':
3770 // Replace the '^' with '*'.
3771 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
3772 ReplaceText(LocStart, 1, "*", 1);
3773 break;
3774 }
3775 }
3776 return;
3777}
3778
3779void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
3780 SourceLocation DeclLoc = FD->getLocation();
3781 unsigned parenCount = 0;
3782
3783 // We have 1 or more arguments that have closure pointers.
3784 const char *startBuf = SM->getCharacterData(DeclLoc);
3785 const char *startArgList = strchr(startBuf, '(');
3786
3787 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
3788
3789 parenCount++;
3790 // advance the location to startArgList.
3791 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
3792 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
3793
3794 const char *argPtr = startArgList;
3795
3796 while (*argPtr++ && parenCount) {
3797 switch (*argPtr) {
3798 case '^':
3799 // Replace the '^' with '*'.
3800 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
3801 ReplaceText(DeclLoc, 1, "*", 1);
3802 break;
3803 case '(':
3804 parenCount++;
3805 break;
3806 case ')':
3807 parenCount--;
3808 break;
3809 }
3810 }
3811 return;
3812}
3813
3814bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
3815 const FunctionTypeProto *FTP;
3816 const PointerType *PT = QT->getAsPointerType();
3817 if (PT) {
3818 FTP = PT->getPointeeType()->getAsFunctionTypeProto();
3819 } else {
3820 const BlockPointerType *BPT = QT->getAsBlockPointerType();
3821 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
3822 FTP = BPT->getPointeeType()->getAsFunctionTypeProto();
3823 }
3824 if (FTP) {
3825 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
3826 E = FTP->arg_type_end(); I != E; ++I)
3827 if (isBlockPointerType(*I))
3828 return true;
3829 }
3830 return false;
3831}
3832
3833void RewriteObjC::GetExtentOfArgList(const char *Name,
3834 const char *&LParen, const char *&RParen) {
3835 const char *argPtr = strchr(Name, '(');
3836 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
3837
3838 LParen = argPtr; // output the start.
3839 argPtr++; // skip past the left paren.
3840 unsigned parenCount = 1;
3841
3842 while (*argPtr && parenCount) {
3843 switch (*argPtr) {
3844 case '(': parenCount++; break;
3845 case ')': parenCount--; break;
3846 default: break;
3847 }
3848 if (parenCount) argPtr++;
3849 }
3850 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
3851 RParen = argPtr; // output the end
3852}
3853
3854void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
3855 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3856 RewriteBlockPointerFunctionArgs(FD);
3857 return;
3858 }
3859 // Handle Variables and Typedefs.
3860 SourceLocation DeclLoc = ND->getLocation();
3861 QualType DeclT;
3862 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3863 DeclT = VD->getType();
3864 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
3865 DeclT = TDD->getUnderlyingType();
3866 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
3867 DeclT = FD->getType();
3868 else
3869 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
3870
3871 const char *startBuf = SM->getCharacterData(DeclLoc);
3872 const char *endBuf = startBuf;
3873 // scan backward (from the decl location) for the end of the previous decl.
3874 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
3875 startBuf--;
3876
3877 // *startBuf != '^' if we are dealing with a pointer to function that
3878 // may take block argument types (which will be handled below).
3879 if (*startBuf == '^') {
3880 // Replace the '^' with '*', computing a negative offset.
3881 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
3882 ReplaceText(DeclLoc, 1, "*", 1);
3883 }
3884 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
3885 // Replace the '^' with '*' for arguments.
3886 DeclLoc = ND->getLocation();
3887 startBuf = SM->getCharacterData(DeclLoc);
3888 const char *argListBegin, *argListEnd;
3889 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
3890 while (argListBegin < argListEnd) {
3891 if (*argListBegin == '^') {
3892 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
3893 ReplaceText(CaretLoc, 1, "*", 1);
3894 }
3895 argListBegin++;
3896 }
3897 }
3898 return;
3899}
3900
3901void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
3902 // Add initializers for any closure decl refs.
3903 GetBlockDeclRefExprs(Exp->getBody());
3904 if (BlockDeclRefs.size()) {
3905 // Unique all "by copy" declarations.
3906 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3907 if (!BlockDeclRefs[i]->isByRef())
3908 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
3909 // Unique all "by ref" declarations.
3910 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3911 if (BlockDeclRefs[i]->isByRef()) {
3912 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
3913 }
3914 // Find any imported blocks...they will need special attention.
3915 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
3916 if (isBlockPointerType(BlockDeclRefs[i]->getType())) {
Steve Naroff00072682008-11-13 17:40:07 +00003917 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff54055232008-10-27 17:20:55 +00003918 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
3919 }
3920 }
3921}
3922
Steve Narofffa15fd92008-10-28 20:29:00 +00003923FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
3924 IdentifierInfo *ID = &Context->Idents.get(name);
3925 QualType FType = Context->getFunctionTypeNoProto(Context->VoidPtrTy);
3926 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
3927 ID, FType, FunctionDecl::Extern, false, 0);
3928}
3929
Steve Naroff8e2f57a2008-10-29 18:15:37 +00003930Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Narofffa15fd92008-10-28 20:29:00 +00003931 Blocks.push_back(Exp);
3932
3933 CollectBlockDeclRefInfo(Exp);
3934 std::string FuncName;
3935
3936 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00003937 FuncName = CurFunctionDef->getNameAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00003938 else if (CurMethodDef) {
Chris Lattner077bf5e2008-11-24 03:33:13 +00003939 FuncName = CurMethodDef->getSelector().getAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00003940 // Convert colons to underscores.
3941 std::string::size_type loc = 0;
3942 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3943 FuncName.replace(loc, 1, "_");
Steve Naroff8e2f57a2008-10-29 18:15:37 +00003944 } else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003945 FuncName = std::string(GlobalVarDecl->getNameAsString());
Steve Narofffa15fd92008-10-28 20:29:00 +00003946
3947 std::string BlockNumber = utostr(Blocks.size()-1);
3948
3949 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
3950 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
3951
3952 // Get a pointer to the function type so we can cast appropriately.
3953 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
3954
3955 FunctionDecl *FD;
3956 Expr *NewRep;
3957
3958 // Simulate a contructor call...
3959 FD = SynthBlockInitFunctionDecl(Tag.c_str());
3960 DeclRefExpr *DRE = new DeclRefExpr(FD, FType, SourceLocation());
3961
3962 llvm::SmallVector<Expr*, 4> InitExprs;
3963
Steve Narofffdc03722008-10-29 21:23:59 +00003964 // Initialize the block function.
Steve Narofffa15fd92008-10-28 20:29:00 +00003965 FD = SynthBlockInitFunctionDecl(Func.c_str());
3966 DeclRefExpr *Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3967 CastExpr *castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00003968 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00003969 InitExprs.push_back(castExpr);
Steve Narofffa15fd92008-10-28 20:29:00 +00003970
3971 if (ImportedBlockDecls.size()) {
3972 std::string Buf = "__" + FuncName + "_block_copy_" + BlockNumber;
Steve Narofffdc03722008-10-29 21:23:59 +00003973 FD = SynthBlockInitFunctionDecl(Buf.c_str());
3974 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3975 castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00003976 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffdc03722008-10-29 21:23:59 +00003977 InitExprs.push_back(castExpr);
3978
Steve Narofffa15fd92008-10-28 20:29:00 +00003979 Buf = "__" + FuncName + "_block_dispose_" + BlockNumber;
Steve Narofffdc03722008-10-29 21:23:59 +00003980 FD = SynthBlockInitFunctionDecl(Buf.c_str());
3981 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3982 castExpr = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00003983 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffdc03722008-10-29 21:23:59 +00003984 InitExprs.push_back(castExpr);
Steve Narofffa15fd92008-10-28 20:29:00 +00003985 }
3986 // Add initializers for any closure decl refs.
3987 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00003988 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00003989 // Output all "by copy" declarations.
3990 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3991 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00003992 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00003993 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner8ec03f52008-11-24 03:54:41 +00003994 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00003995 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00003996 } else if (isBlockPointerType((*I)->getType())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003997 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00003998 Arg = new DeclRefExpr(FD, FD->getType(), SourceLocation());
3999 Exp = new CStyleCastExpr(Context->VoidPtrTy, Arg,
Steve Naroffb2f9e512008-11-03 23:29:32 +00004000 Context->VoidPtrTy, SourceLocation(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004001 } else {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004002 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00004003 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004004 }
Steve Narofffdc03722008-10-29 21:23:59 +00004005 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004006 }
4007 // Output all "by ref" declarations.
4008 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4009 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004010 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Steve Narofffdc03722008-10-29 21:23:59 +00004011 Exp = new DeclRefExpr(FD, FD->getType(), SourceLocation());
4012 Exp = new UnaryOperator(Exp, UnaryOperator::AddrOf,
4013 Context->getPointerType(Exp->getType()),
4014 SourceLocation());
Steve Naroff707b0fe2008-11-14 21:36:12 +00004015 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004016 }
4017 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004018 NewRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
4019 FType, SourceLocation());
4020 NewRep = new UnaryOperator(NewRep, UnaryOperator::AddrOf,
4021 Context->getPointerType(NewRep->getType()),
4022 SourceLocation());
Steve Naroffb2f9e512008-11-03 23:29:32 +00004023 NewRep = new CStyleCastExpr(FType, NewRep, FType, SourceLocation(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004024 BlockDeclRefs.clear();
4025 BlockByRefDecls.clear();
4026 BlockByCopyDecls.clear();
4027 ImportedBlockDecls.clear();
4028 return NewRep;
4029}
4030
4031//===----------------------------------------------------------------------===//
4032// Function Body / Expression rewriting
4033//===----------------------------------------------------------------------===//
4034
Steve Naroffc77a6362008-12-04 16:24:46 +00004035// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
4036// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
4037// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
4038// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
4039// Since the rewriter isn't capable of rewriting rewritten code, it's important
4040// we get this right.
4041void RewriteObjC::CollectPropertySetters(Stmt *S) {
4042 // Perform a bottom up traversal of all children.
4043 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4044 CI != E; ++CI)
4045 if (*CI)
4046 CollectPropertySetters(*CI);
4047
4048 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
4049 if (BinOp->isAssignmentOp()) {
4050 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
4051 PropSetters[PRE] = BinOp;
4052 }
4053 }
4054}
4055
Steve Narofffa15fd92008-10-28 20:29:00 +00004056Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
4057 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4058 isa<DoStmt>(S) || isa<ForStmt>(S))
4059 Stmts.push_back(S);
4060 else if (isa<ObjCForCollectionStmt>(S)) {
4061 Stmts.push_back(S);
4062 ObjCBcLabelNo.push_back(++BcLabelCount);
4063 }
4064
4065 SourceRange OrigStmtRange = S->getSourceRange();
4066
4067 // Perform a bottom up rewrite of all children.
4068 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4069 CI != E; ++CI)
4070 if (*CI) {
4071 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
4072 if (newStmt)
4073 *CI = newStmt;
4074 }
4075
4076 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4077 // Rewrite the block body in place.
4078 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
4079
4080 // Now we snarf the rewritten text and stash it away for later use.
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004081 std::string Str = Rewrite.getRewritenText(BE->getSourceRange());
4082 RewrittenBlockExprs[BE] = Str;
Steve Narofffa15fd92008-10-28 20:29:00 +00004083
4084 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
4085 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004086 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00004087 return blockTranscribed;
4088 }
4089 // Handle specific things.
4090 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4091 return RewriteAtEncode(AtEncode);
4092
4093 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
4094 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
4095
Steve Naroffc77a6362008-12-04 16:24:46 +00004096 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
4097 BinaryOperator *BinOp = PropSetters[PropRefExpr];
4098 if (BinOp) {
4099 // Because the rewriter doesn't allow us to rewrite rewritten code,
4100 // we need to rewrite the right hand side prior to rewriting the setter.
4101 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroff4c3580e2008-12-04 23:50:32 +00004102 //
4103 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
4104 // we changed the RHS of BinOp, the rewriter would fail (since it needs
4105 // to see the original expression). Consider this example:
4106 //
4107 // Foo *obj1, *obj2;
4108 //
4109 // obj1.i = [obj2 rrrr];
4110 //
4111 // 'BinOp' for the previous expression looks like:
4112 //
4113 // (BinaryOperator 0x231ccf0 'int' '='
4114 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
4115 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
4116 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
4117 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
4118 //
4119 // 'newStmt' represents the rewritten message expression. For example:
4120 //
4121 // (CallExpr 0x231d300 'id':'struct objc_object *'
4122 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
4123 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
4124 // (CStyleCastExpr 0x231d220 'void *'
4125 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
4126 //
4127 // Note that 'newStmt' is passed to RewritePropertySetter so that it
4128 // can be used as the setter argument. ReplaceStmt() will still 'see'
4129 // the original RHS (since we haven't altered BinOp).
4130 //
4131 // This implies the Rewrite* routines can no longer delete the original
4132 // node. As a result, we now leak the original AST nodes.
4133 //
Steve Naroffc77a6362008-12-04 16:24:46 +00004134 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt));
4135 } else {
4136 return RewritePropertyGetter(PropRefExpr);
Steve Naroff15f081d2008-12-03 00:56:33 +00004137 }
4138 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004139 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4140 return RewriteAtSelector(AtSelector);
4141
4142 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4143 return RewriteObjCStringLiteral(AtString);
4144
4145 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00004146#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00004147 // Before we rewrite it, put the original message expression in a comment.
4148 SourceLocation startLoc = MessExpr->getLocStart();
4149 SourceLocation endLoc = MessExpr->getLocEnd();
4150
4151 const char *startBuf = SM->getCharacterData(startLoc);
4152 const char *endBuf = SM->getCharacterData(endLoc);
4153
4154 std::string messString;
4155 messString += "// ";
4156 messString.append(startBuf, endBuf-startBuf+1);
4157 messString += "\n";
4158
4159 // FIXME: Missing definition of
4160 // InsertText(clang::SourceLocation, char const*, unsigned int).
4161 // InsertText(startLoc, messString.c_str(), messString.size());
4162 // Tried this, but it didn't work either...
4163 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00004164#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00004165 return RewriteMessageExpr(MessExpr);
4166 }
4167
4168 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4169 return RewriteObjCTryStmt(StmtTry);
4170
4171 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4172 return RewriteObjCSynchronizedStmt(StmtTry);
4173
4174 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4175 return RewriteObjCThrowStmt(StmtThrow);
4176
4177 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4178 return RewriteObjCProtocolExpr(ProtocolExp);
4179
4180 if (ObjCForCollectionStmt *StmtForCollection =
4181 dyn_cast<ObjCForCollectionStmt>(S))
4182 return RewriteObjCForCollectionStmt(StmtForCollection,
4183 OrigStmtRange.getEnd());
4184 if (BreakStmt *StmtBreakStmt =
4185 dyn_cast<BreakStmt>(S))
4186 return RewriteBreakStmt(StmtBreakStmt);
4187 if (ContinueStmt *StmtContinueStmt =
4188 dyn_cast<ContinueStmt>(S))
4189 return RewriteContinueStmt(StmtContinueStmt);
4190
4191 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
4192 // and cast exprs.
4193 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4194 // FIXME: What we're doing here is modifying the type-specifier that
4195 // precedes the first Decl. In the future the DeclGroup should have
4196 // a separate type-specifier that we can rewrite.
4197 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
4198
4199 // Blocks rewrite rules.
4200 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4201 DI != DE; ++DI) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004202 ScopedDecl *SD = *DI;
4203 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
4204 if (isBlockPointerType(ND->getType()))
4205 RewriteBlockPointerDecl(ND);
4206 else if (ND->getType()->isFunctionPointerType())
4207 CheckFunctionPointerDecl(ND->getType(), ND);
4208 }
4209 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
4210 if (isBlockPointerType(TD->getUnderlyingType()))
4211 RewriteBlockPointerDecl(TD);
4212 else if (TD->getUnderlyingType()->isFunctionPointerType())
4213 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4214 }
4215 }
4216 }
4217
4218 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4219 RewriteObjCQualifiedInterfaceTypes(CE);
4220
4221 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4222 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4223 assert(!Stmts.empty() && "Statement stack is empty");
4224 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4225 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
4226 && "Statement stack mismatch");
4227 Stmts.pop_back();
4228 }
4229 // Handle blocks rewriting.
4230 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4231 if (BDRE->isByRef())
4232 RewriteBlockDeclRefExpr(BDRE);
4233 }
4234 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004235 if (CE->getCallee()->getType()->isBlockPointerType()) {
4236 Stmt *BlockCall = SynthesizeBlockCall(CE);
4237 ReplaceStmt(S, BlockCall);
4238 return BlockCall;
4239 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004240 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00004241 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004242 RewriteCastExpr(CE);
4243 }
4244#if 0
4245 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
4246 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
4247 // Get the new text.
4248 std::string SStr;
4249 llvm::raw_string_ostream Buf(SStr);
4250 Replacement->printPretty(Buf);
4251 const std::string &Str = Buf.str();
4252
4253 printf("CAST = %s\n", &Str[0]);
4254 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4255 delete S;
4256 return Replacement;
4257 }
4258#endif
4259 // Return this stmt unmodified.
4260 return S;
4261}
4262
4263/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4264/// main file of the input.
4265void RewriteObjC::HandleDeclInMainFile(Decl *D) {
4266 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4267 // Since function prototypes don't have ParmDecl's, we check the function
4268 // prototype. This enables us to rewrite function declarations and
4269 // definitions using the same code.
4270 RewriteBlocksInFunctionTypeProto(FD->getType(), FD);
4271
4272 if (Stmt *Body = FD->getBody()) {
4273 CurFunctionDef = FD;
Steve Naroffc77a6362008-12-04 16:24:46 +00004274 CollectPropertySetters(Body);
Steve Narofffa15fd92008-10-28 20:29:00 +00004275 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroffc77a6362008-12-04 16:24:46 +00004276
Steve Narofffa15fd92008-10-28 20:29:00 +00004277 // This synthesizes and inserts the block "impl" struct, invoke function,
4278 // and any copy/dispose helper functions.
4279 InsertBlockLiteralsWithinFunction(FD);
4280 CurFunctionDef = 0;
4281 }
4282 return;
4283 }
4284 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4285 if (Stmt *Body = MD->getBody()) {
4286 //Body->dump();
4287 CurMethodDef = MD;
Steve Naroffc77a6362008-12-04 16:24:46 +00004288 CollectPropertySetters(Body);
Steve Narofffa15fd92008-10-28 20:29:00 +00004289 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
4290 InsertBlockLiteralsWithinMethod(MD);
4291 CurMethodDef = 0;
4292 }
4293 }
4294 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
4295 ClassImplementation.push_back(CI);
4296 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
4297 CategoryImplementation.push_back(CI);
4298 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
4299 RewriteForwardClassDecl(CD);
4300 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4301 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004302 if (isBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004303 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004304 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004305 CheckFunctionPointerDecl(VD->getType(), VD);
4306 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00004307 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004308 RewriteCastExpr(CE);
4309 }
4310 }
4311 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004312 if (VD->getInit()) {
4313 GlobalVarDecl = VD;
Steve Naroffc77a6362008-12-04 16:24:46 +00004314 CollectPropertySetters(VD->getInit());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004315 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Douglas Gregor2e1cd422008-11-17 14:58:09 +00004316 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00004317 VD->getNameAsCString());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004318 GlobalVarDecl = 0;
4319
4320 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00004321 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004322 RewriteCastExpr(CE);
4323 }
4324 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004325 return;
4326 }
4327 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
4328 if (isBlockPointerType(TD->getUnderlyingType()))
4329 RewriteBlockPointerDecl(TD);
4330 else if (TD->getUnderlyingType()->isFunctionPointerType())
4331 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4332 return;
4333 }
4334 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
4335 if (RD->isDefinition()) {
4336 for (RecordDecl::field_const_iterator i = RD->field_begin(),
4337 e = RD->field_end(); i != e; ++i) {
4338 FieldDecl *FD = *i;
4339 if (isBlockPointerType(FD->getType()))
4340 RewriteBlockPointerDecl(FD);
4341 }
4342 }
4343 return;
4344 }
4345 // Nothing yet.
4346}
4347
4348void RewriteObjC::HandleTranslationUnit(TranslationUnit& TU) {
4349 // Get the top-level buffer that this corresponds to.
4350
4351 // Rewrite tabs if we care.
4352 //RewriteTabs();
4353
4354 if (Diags.hasErrorOccurred())
4355 return;
4356
4357 // Create the output file.
4358
4359 llvm::OwningPtr<llvm::raw_ostream> OwnedStream;
4360 llvm::raw_ostream *OutFile;
4361 if (OutFileName == "-") {
4362 OutFile = &llvm::outs();
4363 } else if (!OutFileName.empty()) {
4364 std::string Err;
Daniel Dunbar26fb2722008-11-13 05:09:21 +00004365 OutFile = new llvm::raw_fd_ostream(OutFileName.c_str(), false, Err);
Steve Narofffa15fd92008-10-28 20:29:00 +00004366 OwnedStream.reset(OutFile);
4367 } else if (InFileName == "-") {
4368 OutFile = &llvm::outs();
4369 } else {
4370 llvm::sys::Path Path(InFileName);
4371 Path.eraseSuffix();
4372 Path.appendSuffix("cpp");
4373 std::string Err;
Daniel Dunbar26fb2722008-11-13 05:09:21 +00004374 OutFile = new llvm::raw_fd_ostream(Path.toString().c_str(), false, Err);
Steve Narofffa15fd92008-10-28 20:29:00 +00004375 OwnedStream.reset(OutFile);
4376 }
4377
4378 RewriteInclude();
4379
4380 InsertText(SourceLocation::getFileLoc(MainFileID, 0),
4381 Preamble.c_str(), Preamble.size(), false);
4382
Steve Naroff0aab7962008-11-14 14:10:01 +00004383 if (ClassImplementation.size() || CategoryImplementation.size())
4384 RewriteImplementations();
Steve Narofffa15fd92008-10-28 20:29:00 +00004385
4386 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
4387 // we are done.
4388 if (const RewriteBuffer *RewriteBuf =
4389 Rewrite.getRewriteBufferFor(MainFileID)) {
4390 //printf("Changed:\n");
4391 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4392 } else {
4393 fprintf(stderr, "No changes\n");
4394 }
Steve Narofface66252008-11-13 20:07:04 +00004395
Steve Naroff0aab7962008-11-14 14:10:01 +00004396 if (ClassImplementation.size() || CategoryImplementation.size()) {
4397 // Rewrite Objective-c meta data*
4398 std::string ResultStr;
4399 SynthesizeMetaDataIntoBuffer(ResultStr);
4400 // Emit metadata.
4401 *OutFile << ResultStr;
4402 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004403 OutFile->flush();
4404}
4405