blob: e0267ec2d042b2bbd690e08428a089a845e0a094 [file] [log] [blame]
Steve Naroff44e81222008-04-14 22:03:09 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
Chris Lattnerb429ae42007-10-11 00:43:27 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-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 Lattnerb429ae42007-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 Lattner569faa62007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattnerb429ae42007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Steve Narofffbed6802008-12-08 16:43:47 +000018#include "clang/AST/ParentMap.h"
Chris Lattner569faa62007-10-11 18:38:32 +000019#include "clang/Basic/SourceManager.h"
Steve Naroffe9780582007-10-23 23:50:29 +000020#include "clang/Basic/IdentifierTable.h"
Chris Lattner4478db92007-11-30 22:53:43 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattnerae43eb72007-12-02 01:13:47 +000022#include "clang/Lex/Lexer.h"
Chris Lattnerc3aa5c42007-10-25 17:07:24 +000023#include "llvm/ADT/StringExtras.h"
Fariborz Jahanianf185aef2007-10-26 19:46:17 +000024#include "llvm/ADT/SmallPtrSet.h"
Ted Kremenek7b6f67b2008-09-13 05:16:45 +000025#include "llvm/ADT/OwningPtr.h"
Chris Lattnerae43eb72007-12-02 01:13:47 +000026#include "llvm/Support/MemoryBuffer.h"
Steve Naroff1c46cf12008-01-28 21:34:52 +000027#include "llvm/Support/CommandLine.h"
Dan Gohman6da15102008-05-21 20:19:16 +000028#include "llvm/Support/Streams.h"
Ted Kremenek7b6f67b2008-09-13 05:16:45 +000029#include "llvm/Support/raw_ostream.h"
Chris Lattner673f2bd2008-03-22 00:08:40 +000030#include "llvm/System/Path.h"
Chris Lattnerb429ae42007-10-11 00:43:27 +000031using namespace clang;
Chris Lattnerc3aa5c42007-10-25 17:07:24 +000032using llvm::utostr;
Chris Lattnerb429ae42007-10-11 00:43:27 +000033
Steve Naroff1c46cf12008-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 Lattnerb429ae42007-10-11 00:43:27 +000038namespace {
Steve Naroff44e81222008-04-14 22:03:09 +000039 class RewriteObjC : public ASTConsumer {
Chris Lattner74db1682007-10-16 21:07:07 +000040 Rewriter Rewrite;
Chris Lattner258f26c2007-11-30 22:25:36 +000041 Diagnostic &Diags;
Steve Naroff7fd0aff2008-03-10 20:43:59 +000042 const LangOptions &LangOpts;
Steve Naroff53b6f4c2008-01-30 19:17:43 +000043 unsigned RewriteFailedDiag;
Steve Naroff43964fb2008-12-05 17:03:39 +000044 unsigned TryFinallyContainsReturnDiag;
45
Chris Lattnerbf0bfa62007-10-17 22:35:30 +000046 ASTContext *Context;
Chris Lattnerb429ae42007-10-11 00:43:27 +000047 SourceManager *SM;
Argiris Kirtzidisd3586002008-04-17 14:40:12 +000048 TranslationUnitDecl *TUDecl;
Chris Lattnerf4f776a2009-01-17 06:22:33 +000049 FileID MainFileID;
Chris Lattnerae43eb72007-12-02 01:13:47 +000050 const char *MainFileStart, *MainFileEnd;
Chris Lattner74db1682007-10-16 21:07:07 +000051 SourceLocation LastIncLoc;
Steve Narofffef037c2008-03-27 22:29:16 +000052
Ted Kremenek42730c52008-01-07 19:49:32 +000053 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
54 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
55 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Naroff04eaa192008-05-06 18:26:51 +000056 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremenek42730c52008-01-07 19:49:32 +000057 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
58 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanian13dad332008-01-15 23:58:23 +000059 llvm::SmallVector<Stmt *, 32> Stmts;
60 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroffe9780582007-10-23 23:50:29 +000061
Steve Naroff47e7fa22008-03-15 00:55:56 +000062 unsigned NumObjCStringLiterals;
63
Steve Naroffe9780582007-10-23 23:50:29 +000064 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +000065 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +000066 FunctionDecl *MsgSendStretFunctionDecl;
67 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +000068 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffe9780582007-10-23 23:50:29 +000069 FunctionDecl *GetClassFunctionDecl;
Steve Naroff3b1caac2007-12-07 03:50:46 +000070 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff71226032007-10-24 22:48:43 +000071 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroffabb96362007-11-08 14:30:50 +000072 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +000073 FunctionDecl *GetProtocolFunctionDecl;
Steve Naroffbec4bf52008-03-11 17:37:02 +000074 FunctionDecl *SuperContructorFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +000075
Steve Naroff0add5d22007-11-03 11:27:19 +000076 // ObjC string constant support.
Steve Naroff72a6ebc2008-04-15 22:42:06 +000077 VarDecl *ConstantStringClassReference;
Steve Naroff0add5d22007-11-03 11:27:19 +000078 RecordDecl *NSStringRecord;
Steve Naroff0744c472007-11-04 22:37:50 +000079
Fariborz Jahanian22277422008-01-16 00:09:11 +000080 // ObjC foreach break/continue generation support.
Fariborz Jahanian13dad332008-01-15 23:58:23 +000081 int BcLabelCount;
82
Steve Naroff764c1ae2007-11-15 10:28:18 +000083 // Needed for super.
Steve Naroff38a9e3f2008-10-27 17:20:55 +000084 ObjCMethodDecl *CurMethodDef;
Steve Naroff764c1ae2007-11-15 10:28:18 +000085 RecordDecl *SuperStructDecl;
Steve Naroff47e7fa22008-03-15 00:55:56 +000086 RecordDecl *ConstantStringDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +000087
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +000088 // Needed for header files being rewritten
89 bool IsHeader;
90
Steve Naroffcfd9f4c2008-03-28 22:26:09 +000091 std::string InFileName;
92 std::string OutFileName;
93
Steve Narofffef037c2008-03-27 22:29:16 +000094 std::string Preamble;
Steve Naroff38a9e3f2008-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 Narofffef037c2008-03-27 22:29:16 +0000100
Steve Naroff38a9e3f2008-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 Naroff0e948412008-12-04 16:24:46 +0000108 // This maps a property to it's assignment statement.
109 llvm::DenseMap<ObjCPropertyRefExpr *, BinaryOperator *> PropSetters;
Steve Narofffbed6802008-12-08 16:43:47 +0000110 // This maps a property to it's synthesied message expression.
111 // This allows us to rewrite chained getters (e.g. o.a.b.c).
112 llvm::DenseMap<ObjCPropertyRefExpr *, Stmt *> PropGetters;
113
Steve Naroff102c3f22008-12-04 23:50:32 +0000114 // This maps an original source AST to it's rewritten form. This allows
115 // us to avoid rewriting the same node twice (which is very uncommon).
116 // This is needed to support some of the exotic property rewriting.
117 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Narofff6ce8a12008-12-03 00:56:33 +0000118
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000119 FunctionDecl *CurFunctionDef;
Steve Naroff80c54752008-10-29 18:15:37 +0000120 VarDecl *GlobalVarDecl;
121
Steve Naroffedb4bc92008-12-09 12:56:34 +0000122 bool DisableReplaceStmt;
123
Fariborz Jahanian640a01f2007-10-18 19:23:00 +0000124 static const int OBJC_ABI_VERSION =7 ;
Chris Lattnerb429ae42007-10-11 00:43:27 +0000125 public:
Ted Kremenek79b50cb2008-05-31 20:11:04 +0000126 virtual void Initialize(ASTContext &context);
127
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000128 // Top Level Driver code.
129 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner74db1682007-10-16 21:07:07 +0000130 void HandleDeclInMainFile(Decl *D);
Steve Naroff44e81222008-04-14 22:03:09 +0000131 RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffcfd9f4c2008-03-28 22:26:09 +0000132 Diagnostic &D, const LangOptions &LOpts);
Ted Kremenekcab0b0c2008-08-08 04:15:52 +0000133
134 ~RewriteObjC() {}
135
Chris Lattner2a594d02009-03-28 04:11:33 +0000136 virtual void HandleTranslationUnit(ASTContext &C);
Chris Lattnerb1548372008-01-31 19:37:57 +0000137
138 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff102c3f22008-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 Lattnerb1548372008-01-31 19:37:57 +0000143
Steve Naroffedb4bc92008-12-09 12:56:34 +0000144 if (DisableReplaceStmt)
145 return; // Used when rewriting the assignment of a property setter.
146
Steve Naroff102c3f22008-12-04 23:50:32 +0000147 // If replacement succeeded or warning disabled return with no warning.
148 if (!Rewrite.ReplaceStmt(Old, New)) {
149 ReplacedNodes[Old] = New;
150 return;
151 }
152 if (SilenceRewriteMacroWarning)
153 return;
Chris Lattner6948ae62008-11-18 07:04:44 +0000154 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
155 << Old->getSourceRange();
Chris Lattnerb1548372008-01-31 19:37:57 +0000156 }
Steve Naroffedb4bc92008-12-09 12:56:34 +0000157
158 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
159 // Measaure the old text.
160 int Size = Rewrite.getRangeSize(SrcRange);
161 if (Size == -1) {
162 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
163 << Old->getSourceRange();
164 return;
165 }
166 // Get the new text.
167 std::string SStr;
168 llvm::raw_string_ostream S(SStr);
169 New->printPretty(S);
170 const std::string &Str = S.str();
171
172 // If replacement succeeded or warning disabled return with no warning.
173 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, &Str[0], Str.size())) {
174 ReplacedNodes[Old] = New;
175 return;
176 }
177 if (SilenceRewriteMacroWarning)
178 return;
179 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
180 << Old->getSourceRange();
181 }
182
Steve Narofffef037c2008-03-27 22:29:16 +0000183 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
184 bool InsertAfter = true) {
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000185 // If insertion succeeded or warning disabled return with no warning.
Steve Narofffef037c2008-03-27 22:29:16 +0000186 if (!Rewrite.InsertText(Loc, StrData, StrLen, InsertAfter) ||
Chris Lattner6216f292008-01-31 19:42:41 +0000187 SilenceRewriteMacroWarning)
188 return;
189
190 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
191 }
Chris Lattnerb1548372008-01-31 19:37:57 +0000192
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000193 void RemoveText(SourceLocation Loc, unsigned StrLen) {
194 // If removal succeeded or warning disabled return with no warning.
195 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
196 return;
197
198 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
199 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000200
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000201 void ReplaceText(SourceLocation Start, unsigned OrigLength,
202 const char *NewStr, unsigned NewLength) {
203 // If removal succeeded or warning disabled return with no warning.
204 if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength) ||
205 SilenceRewriteMacroWarning)
206 return;
207
208 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
209 }
210
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000211 // Syntactic Rewriting.
Steve Naroff0744c472007-11-04 22:37:50 +0000212 void RewritePrologue(SourceLocation Loc);
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000213 void RewriteInclude();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000214 void RewriteTabs();
Ted Kremenek42730c52008-01-07 19:49:32 +0000215 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffea6610f2008-12-02 17:36:43 +0000216 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
217 ObjCImplementationDecl *IMD,
218 ObjCCategoryImplDecl *CID);
Ted Kremenek42730c52008-01-07 19:49:32 +0000219 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000220 void RewriteImplementationDecl(Decl *Dcl);
Ted Kremenek42730c52008-01-07 19:49:32 +0000221 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
222 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
223 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
224 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
225 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff56af2002009-01-11 01:06:09 +0000226 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff02a82aa2007-10-30 23:14:51 +0000227 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000228 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroffd06c88d2008-07-29 18:15:38 +0000229 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffc8a92d12007-11-01 13:24:47 +0000230 bool needToScanForQualifiers(QualType T);
Ted Kremenek42730c52008-01-07 19:49:32 +0000231 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff764c1ae2007-11-15 10:28:18 +0000232 QualType getSuperStructType();
Steve Naroff47e7fa22008-03-15 00:55:56 +0000233 QualType getConstantStringStructType();
Steve Naroffef82b742008-05-31 14:15:04 +0000234 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Chris Lattner6fe8b272007-10-16 22:36:42 +0000235
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000236 // Expression Rewriting.
Steve Naroff334fbc22007-11-09 15:20:18 +0000237 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroff0e948412008-12-04 16:24:46 +0000238 void CollectPropertySetters(Stmt *S);
239
Steve Narofffbed6802008-12-08 16:43:47 +0000240 Stmt *CurrentBody;
241 ParentMap *PropParentMap; // created lazily.
242
Chris Lattner0021f452007-10-24 16:57:36 +0000243 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner343c82b2008-05-23 20:40:52 +0000244 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart);
Steve Naroff0e948412008-12-04 16:24:46 +0000245 Stmt *RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr);
Steve Naroffedb4bc92008-12-09 12:56:34 +0000246 Stmt *RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
247 SourceRange SrcRange);
Steve Naroff296b74f2007-11-05 14:50:49 +0000248 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner0021f452007-10-24 16:57:36 +0000249 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroff0add5d22007-11-03 11:27:19 +0000250 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000251 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroff43964fb2008-12-05 17:03:39 +0000252 void WarnAboutReturnGotoContinueOrBreakStmts(Stmt *S);
Ted Kremenek42730c52008-01-07 19:49:32 +0000253 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian499bf412008-01-29 22:59:37 +0000254 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremenek42730c52008-01-07 19:49:32 +0000255 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
256 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
257 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner2c022162008-01-31 05:10:40 +0000258 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
259 SourceLocation OrigEnd);
Steve Naroff71226032007-10-24 22:48:43 +0000260 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
261 Expr **args, unsigned nargs);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000262 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000263 Stmt *RewriteBreakStmt(BreakStmt *S);
264 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000265 void SynthCountByEnumWithState(std::string &buf);
266
Steve Naroff02a82aa2007-10-30 23:14:51 +0000267 void SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +0000268 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000269 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +0000270 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000271 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +0000272 void SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +0000273 void SynthGetMetaClassFunctionDecl();
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +0000274 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000275 void SynthGetProtocolFunctionDecl();
Steve Naroffbec4bf52008-03-11 17:37:02 +0000276 void SynthSuperContructorFunctionDecl();
Steve Naroffabb96362007-11-08 14:30:50 +0000277
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000278 // Metadata emission.
Ted Kremenek42730c52008-01-07 19:49:32 +0000279 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000280 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000281
Ted Kremenek42730c52008-01-07 19:49:32 +0000282 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000283 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000284
Ted Kremenek42730c52008-01-07 19:49:32 +0000285 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
286 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000287 instmeth_iterator MethodEnd,
Fariborz Jahaniana3986372007-10-25 00:14:44 +0000288 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000289 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +0000290 const char *ClassName,
291 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000292
Chris Lattner0be08822008-07-21 21:32:27 +0000293 void RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl>
294 &Protocols,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000295 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000296 const char *ClassName,
297 std::string &Result);
Ted Kremenek42730c52008-01-07 19:49:32 +0000298 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000299 std::string &Result);
Ted Kremenek42730c52008-01-07 19:49:32 +0000300 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
301 ObjCIvarDecl *ivar,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000302 std::string &Result);
Steve Naroff21658f62008-11-13 20:07:04 +0000303 void RewriteImplementations();
304 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000305
306 // Block rewriting.
Douglas Gregor4fa58902009-02-26 23:50:07 +0000307 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000308 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
309
310 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
311 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
312
Steve Naroff80c54752008-10-29 18:15:37 +0000313 // Block specific rewrite rules.
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000314 void RewriteBlockCall(CallExpr *Exp);
315 void RewriteBlockPointerDecl(NamedDecl *VD);
316 void RewriteBlockDeclRefExpr(BlockDeclRefExpr *VD);
317 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
318
319 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
320 const char *funcName, std::string Tag);
321 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
322 const char *funcName, std::string Tag);
323 std::string SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
324 bool hasCopyDisposeHelpers);
Steve Naroff85eb17b2008-10-30 10:07:53 +0000325 Stmt *SynthesizeBlockCall(CallExpr *Exp);
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000326 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
327 const char *FunName);
328
329 void CollectBlockDeclRefInfo(BlockExpr *Exp);
330 void GetBlockCallExprs(Stmt *S);
331 void GetBlockDeclRefExprs(Stmt *S);
332
333 // We avoid calling Type::isBlockPointerType(), since it operates on the
334 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek0c97e042009-02-07 01:47:29 +0000335 bool isTopLevelBlockPointerType(QualType T) {
336 return isa<BlockPointerType>(T);
337 }
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000338
339 // FIXME: This predicate seems like it would be useful to add to ASTContext.
340 bool isObjCType(QualType T) {
341 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
342 return false;
343
344 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
345
346 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
347 OCT == Context->getCanonicalType(Context->getObjCClassType()))
348 return true;
349
350 if (const PointerType *PT = OCT->getAsPointerType()) {
351 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
352 isa<ObjCQualifiedIdType>(PT->getPointeeType()))
353 return true;
354 }
355 return false;
356 }
357 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Ted Kremenek0c97e042009-02-07 01:47:29 +0000358 void GetExtentOfArgList(const char *Name, const char *&LParen,
359 const char *&RParen);
Steve Naroff7f1412d2008-11-03 23:29:32 +0000360 void RewriteCastExpr(CStyleCastExpr *CE);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +0000361
362 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Steve Naroff80c54752008-10-29 18:15:37 +0000363 Stmt *SynthBlockInitExpr(BlockExpr *Exp);
Chris Lattnerb429ae42007-10-11 00:43:27 +0000364 };
365}
366
Douglas Gregor4fa58902009-02-26 23:50:07 +0000367void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000368 NamedDecl *D) {
Douglas Gregor4fa58902009-02-26 23:50:07 +0000369 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
370 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000371 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroffd896f4b2008-12-11 21:05:33 +0000372 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000373 // All the args are checked/rewritten. Don't call twice!
374 RewriteBlockPointerDecl(D);
375 break;
376 }
377 }
378}
379
380void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
381 const PointerType *PT = funcType->getAsPointerType();
382 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor4fa58902009-02-26 23:50:07 +0000383 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000384}
385
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +0000386static bool IsHeaderFile(const std::string &Filename) {
387 std::string::size_type DotPos = Filename.rfind('.');
388
389 if (DotPos == std::string::npos) {
390 // no file extension
391 return false;
392 }
393
394 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
395 // C header: .h
396 // C++ header: .hh or .H;
397 return Ext == "h" || Ext == "hh" || Ext == "H";
398}
399
Steve Naroff44e81222008-04-14 22:03:09 +0000400RewriteObjC::RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffcfd9f4c2008-03-28 22:26:09 +0000401 Diagnostic &D, const LangOptions &LOpts)
402 : Diags(D), LangOpts(LOpts) {
403 IsHeader = IsHeaderFile(inFile);
404 InFileName = inFile;
405 OutFileName = outFile;
406 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
407 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff43964fb2008-12-05 17:03:39 +0000408 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek0c97e042009-02-07 01:47:29 +0000409 "rewriter doesn't support user-specified control flow semantics "
410 "for @try/@finally (code may not execute properly)");
Steve Naroffcfd9f4c2008-03-28 22:26:09 +0000411}
412
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +0000413ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
Chris Lattner673f2bd2008-03-22 00:08:40 +0000414 const std::string& OutFile,
Steve Naroff7fd0aff2008-03-10 20:43:59 +0000415 Diagnostic &Diags,
416 const LangOptions &LOpts) {
Steve Naroff44e81222008-04-14 22:03:09 +0000417 return new RewriteObjC(InFile, OutFile, Diags, LOpts);
Chris Lattner258f26c2007-11-30 22:25:36 +0000418}
Chris Lattnerb429ae42007-10-11 00:43:27 +0000419
Steve Naroff44e81222008-04-14 22:03:09 +0000420void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner12499682008-01-31 19:38:44 +0000421 Context = &context;
422 SM = &Context->getSourceManager();
Argiris Kirtzidisd3586002008-04-17 14:40:12 +0000423 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner12499682008-01-31 19:38:44 +0000424 MsgSendFunctionDecl = 0;
425 MsgSendSuperFunctionDecl = 0;
426 MsgSendStretFunctionDecl = 0;
427 MsgSendSuperStretFunctionDecl = 0;
428 MsgSendFpretFunctionDecl = 0;
429 GetClassFunctionDecl = 0;
430 GetMetaClassFunctionDecl = 0;
431 SelGetUidFunctionDecl = 0;
432 CFStringFunctionDecl = 0;
433 GetProtocolFunctionDecl = 0;
434 ConstantStringClassReference = 0;
435 NSStringRecord = 0;
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000436 CurMethodDef = 0;
437 CurFunctionDef = 0;
Steve Naroffedb4bc92008-12-09 12:56:34 +0000438 GlobalVarDecl = 0;
Chris Lattner12499682008-01-31 19:38:44 +0000439 SuperStructDecl = 0;
Steve Naroff053ae3f2008-03-27 22:59:54 +0000440 ConstantStringDecl = 0;
Chris Lattner12499682008-01-31 19:38:44 +0000441 BcLabelCount = 0;
Steve Naroffbec4bf52008-03-11 17:37:02 +0000442 SuperContructorFunctionDecl = 0;
Steve Naroff47e7fa22008-03-15 00:55:56 +0000443 NumObjCStringLiterals = 0;
Steve Naroffbad6f3b2008-12-08 20:01:41 +0000444 PropParentMap = 0;
445 CurrentBody = 0;
Steve Naroffedb4bc92008-12-09 12:56:34 +0000446 DisableReplaceStmt = false;
447
Chris Lattner12499682008-01-31 19:38:44 +0000448 // Get the ID and start/end of the main file.
449 MainFileID = SM->getMainFileID();
450 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
451 MainFileStart = MainBuf->getBufferStart();
452 MainFileEnd = MainBuf->getBufferEnd();
Steve Narofffef037c2008-03-27 22:29:16 +0000453
Chris Lattner12499682008-01-31 19:38:44 +0000454 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Naroffde0da102008-03-10 23:16:54 +0000455
Chris Lattner12499682008-01-31 19:38:44 +0000456 // declaring objc_selector outside the parameter list removes a silly
457 // scope related warning...
Steve Narofffef037c2008-03-27 22:29:16 +0000458 if (IsHeader)
Steve Naroff08299f82009-02-03 20:39:18 +0000459 Preamble = "#pragma once\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000460 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff12673622008-12-23 20:11:22 +0000461 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Narofffef037c2008-03-27 22:29:16 +0000462 Preamble += "struct objc_object *superClass; ";
Steve Naroffbec4bf52008-03-11 17:37:02 +0000463 if (LangOpts.Microsoft) {
464 // Add a constructor for creating temporary objects.
Ted Kremenek0c97e042009-02-07 01:47:29 +0000465 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
466 ": ";
Steve Narofffef037c2008-03-27 22:29:16 +0000467 Preamble += "object(o), superClass(s) {} ";
Steve Naroffbec4bf52008-03-11 17:37:02 +0000468 }
Steve Narofffef037c2008-03-27 22:29:16 +0000469 Preamble += "};\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000470 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
471 Preamble += "typedef struct objc_object Protocol;\n";
472 Preamble += "#define _REWRITER_typedef_Protocol\n";
473 Preamble += "#endif\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000474 if (LangOpts.Microsoft) {
475 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
476 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
477 } else
478 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
479 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Narofffef037c2008-03-27 22:29:16 +0000480 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000481 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Narofffef037c2008-03-27 22:29:16 +0000482 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000483 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Narofffef037c2008-03-27 22:29:16 +0000484 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000485 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Narofffef037c2008-03-27 22:29:16 +0000486 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000487 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Narofffef037c2008-03-27 22:29:16 +0000488 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000489 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Narofffef037c2008-03-27 22:29:16 +0000490 Preamble += "(const char *);\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000491 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Narofffef037c2008-03-27 22:29:16 +0000492 Preamble += "(const char *);\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000493 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
494 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
495 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
496 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
497 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroff3e2c98c2008-05-09 21:17:56 +0000498 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroffcd25d782008-07-16 18:58:11 +0000499 // @synchronized hooks.
Steve Naroff1b208d72008-12-08 17:30:33 +0000500 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
501 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
502 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000503 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
504 Preamble += "struct __objcFastEnumerationState {\n\t";
505 Preamble += "unsigned long state;\n\t";
Steve Naroffc960e9d2008-04-04 22:58:22 +0000506 Preamble += "void **itemsPtr;\n\t";
Steve Narofffef037c2008-03-27 22:29:16 +0000507 Preamble += "unsigned long *mutationsPtr;\n\t";
508 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000509 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000510 Preamble += "#define __FASTENUMERATIONSTATE\n";
511 Preamble += "#endif\n";
512 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
513 Preamble += "struct __NSConstantStringImpl {\n";
514 Preamble += " int *isa;\n";
515 Preamble += " int flags;\n";
516 Preamble += " char *str;\n";
517 Preamble += " long length;\n";
518 Preamble += "};\n";
Steve Naroffc6e571e2008-08-05 20:04:48 +0000519 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
520 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
521 Preamble += "#else\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000522 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroffc6e571e2008-08-05 20:04:48 +0000523 Preamble += "#endif\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000524 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
525 Preamble += "#endif\n";
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000526 // Blocks preamble.
527 Preamble += "#ifndef BLOCK_IMPL\n";
528 Preamble += "#define BLOCK_IMPL\n";
529 Preamble += "struct __block_impl {\n";
530 Preamble += " void *isa;\n";
531 Preamble += " int Flags;\n";
532 Preamble += " int Size;\n";
533 Preamble += " void *FuncPtr;\n";
534 Preamble += "};\n";
Steve Naroff44fe1e32008-12-16 15:50:30 +0000535 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
536 Preamble += "__OBJC_RW_STATICIMPORT void _Block_object_assign(void *, const void *, const int);\n";
537 Preamble += "__OBJC_RW_STATICIMPORT void _Block_object_dispose(const void *, const int);\n";
538 Preamble += "__OBJC_RW_STATICIMPORT void *_NSConcreteGlobalBlock[32];\n";
539 Preamble += "__OBJC_RW_STATICIMPORT void *_NSConcreteStackBlock[32];\n";
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000540 Preamble += "#endif\n";
Steve Naroff39ba90e2008-10-27 18:50:14 +0000541 if (LangOpts.Microsoft) {
Steve Naroff1b208d72008-12-08 17:30:33 +0000542 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
543 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Steve Naroff39ba90e2008-10-27 18:50:14 +0000544 Preamble += "#define __attribute__(X)\n";
545 }
Chris Lattner12499682008-01-31 19:38:44 +0000546}
547
548
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000549//===----------------------------------------------------------------------===//
550// Top Level Driver Code
551//===----------------------------------------------------------------------===//
552
Steve Naroff44e81222008-04-14 22:03:09 +0000553void RewriteObjC::HandleTopLevelDecl(Decl *D) {
Chris Lattner74db1682007-10-16 21:07:07 +0000554 // Two cases: either the decl could be in the main file, or it could be in a
555 // #included file. If the former, rewrite it now. If the later, check to see
556 // if we rewrote the #include/#import.
557 SourceLocation Loc = D->getLocation();
Chris Lattner18c8dc02009-01-16 07:36:28 +0000558 Loc = SM->getInstantiationLoc(Loc);
Chris Lattner74db1682007-10-16 21:07:07 +0000559
560 // If this is for a builtin, ignore it.
561 if (Loc.isInvalid()) return;
562
Steve Naroffe9780582007-10-23 23:50:29 +0000563 // Look for built-in declarations that we need to refer during the rewrite.
564 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff02a82aa2007-10-30 23:14:51 +0000565 RewriteFunctionDecl(FD);
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000566 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroff0add5d22007-11-03 11:27:19 +0000567 // declared in <Foundation/NSString.h>
Chris Lattnerd120b9e2008-11-24 03:54:41 +0000568 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroff0add5d22007-11-03 11:27:19 +0000569 ConstantStringClassReference = FVD;
570 return;
571 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000572 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroff3774dd92007-10-26 20:53:56 +0000573 RewriteInterfaceDecl(MD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000574 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff667f1682007-10-30 13:30:57 +0000575 RewriteCategoryDecl(CD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000576 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000577 RewriteProtocolDecl(PD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000578 } else if (ObjCForwardProtocolDecl *FP =
579 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000580 RewriteForwardProtocolDecl(FP);
Douglas Gregor6e4fa2c2009-01-09 00:49:46 +0000581 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
582 // Recurse into linkage specifications
583 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
584 DIEnd = LSD->decls_end();
585 DI != DIEnd; ++DI)
586 HandleTopLevelDecl(*DI);
Steve Naroffe9780582007-10-23 23:50:29 +0000587 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000588 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenek2450c262008-04-14 21:24:13 +0000589 if (SM->isFromMainFile(Loc))
Chris Lattner74db1682007-10-16 21:07:07 +0000590 return HandleDeclInMainFile(D);
Chris Lattner74db1682007-10-16 21:07:07 +0000591}
592
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000593//===----------------------------------------------------------------------===//
594// Syntactic (non-AST) Rewriting Code
595//===----------------------------------------------------------------------===//
596
Steve Naroff44e81222008-04-14 22:03:09 +0000597void RewriteObjC::RewriteInclude() {
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000598 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000599 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
600 const char *MainBufStart = MainBuf.first;
601 const char *MainBufEnd = MainBuf.second;
602 size_t ImportLen = strlen("import");
603 size_t IncludeLen = strlen("include");
604
Fariborz Jahanianc81ed742008-01-19 01:03:17 +0000605 // Loop over the whole file, looking for includes.
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000606 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
607 if (*BufPtr == '#') {
608 if (++BufPtr == MainBufEnd)
609 return;
610 while (*BufPtr == ' ' || *BufPtr == '\t')
611 if (++BufPtr == MainBufEnd)
612 return;
613 if (!strncmp(BufPtr, "import", ImportLen)) {
614 // replace import with include
615 SourceLocation ImportLoc =
616 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000617 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000618 BufPtr += ImportLen;
619 }
620 }
621 }
Chris Lattner74db1682007-10-16 21:07:07 +0000622}
623
Steve Naroff44e81222008-04-14 22:03:09 +0000624void RewriteObjC::RewriteTabs() {
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000625 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
626 const char *MainBufStart = MainBuf.first;
627 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian640a01f2007-10-18 19:23:00 +0000628
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000629 // Loop over the whole file, looking for tabs.
630 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
631 if (*BufPtr != '\t')
632 continue;
633
634 // Okay, we found a tab. This tab will turn into at least one character,
635 // but it depends on which 'virtual column' it is in. Compute that now.
636 unsigned VCol = 0;
637 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
638 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
639 ++VCol;
640
641 // Okay, now that we know the virtual column, we know how many spaces to
642 // insert. We assume 8-character tab-stops.
643 unsigned Spaces = 8-(VCol & 7);
644
645 // Get the location of the tab.
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000646 SourceLocation TabLoc = SM->getLocForStartOfFile(MainFileID);
647 TabLoc = TabLoc.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000648
649 // Rewrite the single tab character into a sequence of spaces.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000650 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000651 }
Chris Lattner569faa62007-10-11 18:38:32 +0000652}
653
Steve Naroff121ed222008-12-02 15:48:25 +0000654static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
655 ObjCIvarDecl *OID) {
656 std::string S;
657 S = "((struct ";
658 S += ClassDecl->getIdentifier()->getName();
659 S += "_IMPL *)self)->";
660 S += OID->getNameAsCString();
661 return S;
662}
663
Steve Naroffea6610f2008-12-02 17:36:43 +0000664void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
665 ObjCImplementationDecl *IMD,
666 ObjCCategoryImplDecl *CID) {
Steve Naroff110be842008-12-01 20:33:01 +0000667 SourceLocation startLoc = PID->getLocStart();
668 InsertText(startLoc, "// ", 3);
Steve Naroff121ed222008-12-02 15:48:25 +0000669 const char *startBuf = SM->getCharacterData(startLoc);
670 assert((*startBuf == '@') && "bogus @synthesize location");
671 const char *semiBuf = strchr(startBuf, ';');
672 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek0c97e042009-02-07 01:47:29 +0000673 SourceLocation onePastSemiLoc =
674 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroff121ed222008-12-02 15:48:25 +0000675
676 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
677 return; // FIXME: is this correct?
678
679 // Generate the 'getter' function.
Steve Naroff121ed222008-12-02 15:48:25 +0000680 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroff121ed222008-12-02 15:48:25 +0000681 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroff121ed222008-12-02 15:48:25 +0000682 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Steve Naroff1e7b7962008-12-02 16:05:55 +0000683
684 if (!OID)
685 return;
686
687 std::string Getr;
688 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
689 Getr += "{ ";
690 // Synthesize an explicit cast to gain access to the ivar.
Steve Naroff11671e72008-12-02 17:54:50 +0000691 // FIXME: deal with code generation implications for various property
692 // attributes (copy, retain, nonatomic).
693 // See objc-act.c:objc_synthesize_new_getter() for details.
Steve Naroff1e7b7962008-12-02 16:05:55 +0000694 Getr += "return " + getIvarAccessString(ClassDecl, OID);
695 Getr += "; }";
Steve Naroff121ed222008-12-02 15:48:25 +0000696 InsertText(onePastSemiLoc, Getr.c_str(), Getr.size());
Steve Naroffea6610f2008-12-02 17:36:43 +0000697
698 // Add the rewritten getter to trigger meta data generation. An alternate, and
699 // possibly cleaner approach is to hack RewriteObjCMethodsMetaData() to deal
700 // with properties explicitly. The following addInstanceMethod() required far
701 // less code change (and actually models what the rewriter is doing).
702 if (IMD)
703 IMD->addInstanceMethod(PD->getGetterMethodDecl());
704 else
705 CID->addInstanceMethod(PD->getGetterMethodDecl());
Steve Naroff121ed222008-12-02 15:48:25 +0000706
707 if (PD->isReadOnly())
708 return;
709
710 // Generate the 'setter' function.
711 std::string Setr;
712 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroff121ed222008-12-02 15:48:25 +0000713 Setr += "{ ";
Steve Naroff1e7b7962008-12-02 16:05:55 +0000714 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff11671e72008-12-02 17:54:50 +0000715 // FIXME: deal with code generation implications for various property
716 // attributes (copy, retain, nonatomic).
Steve Narofff6ce8a12008-12-03 00:56:33 +0000717 // See objc-act.c:objc_synthesize_new_setter() for details.
Steve Naroff1e7b7962008-12-02 16:05:55 +0000718 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
Steve Naroff20f67392008-12-11 19:29:16 +0000719 Setr += PD->getNameAsCString();
Steve Naroff1e7b7962008-12-02 16:05:55 +0000720 Setr += "; }";
Steve Naroff121ed222008-12-02 15:48:25 +0000721 InsertText(onePastSemiLoc, Setr.c_str(), Setr.size());
Steve Naroffea6610f2008-12-02 17:36:43 +0000722
723 // Add the rewritten setter to trigger meta data generation.
724 if (IMD)
725 IMD->addInstanceMethod(PD->getSetterMethodDecl());
726 else
727 CID->addInstanceMethod(PD->getSetterMethodDecl());
Steve Naroff110be842008-12-01 20:33:01 +0000728}
Chris Lattner569faa62007-10-11 18:38:32 +0000729
Steve Naroff44e81222008-04-14 22:03:09 +0000730void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000731 // Get the start location and compute the semi location.
732 SourceLocation startLoc = ClassDecl->getLocation();
733 const char *startBuf = SM->getCharacterData(startLoc);
734 const char *semiPtr = strchr(startBuf, ';');
735
736 // Translate to typedef's that forward reference structs with the same name
737 // as the class. As a convenience, we include the original declaration
738 // as a comment.
739 std::string typedefString;
740 typedefString += "// ";
Steve Naroff71226032007-10-24 22:48:43 +0000741 typedefString.append(startBuf, semiPtr-startBuf+1);
742 typedefString += "\n";
Chris Lattner6a028742009-02-20 18:04:31 +0000743 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
744 I != E; ++I) {
745 ObjCInterfaceDecl *ForwardDecl = *I;
Steve Naroff2aeae312007-11-09 12:50:28 +0000746 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattner271d4c22008-11-24 05:29:24 +0000747 typedefString += ForwardDecl->getNameAsString();
Steve Naroff2aeae312007-11-09 12:50:28 +0000748 typedefString += "\n";
749 typedefString += "#define _REWRITER_typedef_";
Chris Lattner271d4c22008-11-24 05:29:24 +0000750 typedefString += ForwardDecl->getNameAsString();
Steve Naroff2aeae312007-11-09 12:50:28 +0000751 typedefString += "\n";
Steve Naroff4242b972007-11-05 14:36:37 +0000752 typedefString += "typedef struct objc_object ";
Chris Lattner271d4c22008-11-24 05:29:24 +0000753 typedefString += ForwardDecl->getNameAsString();
Steve Naroff2aeae312007-11-09 12:50:28 +0000754 typedefString += ";\n#endif\n";
Steve Naroff71226032007-10-24 22:48:43 +0000755 }
756
757 // Replace the @class with typedefs corresponding to the classes.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000758 ReplaceText(startLoc, semiPtr-startBuf+1,
759 typedefString.c_str(), typedefString.size());
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000760}
761
Steve Naroff44e81222008-04-14 22:03:09 +0000762void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff2ce399a2007-12-14 23:37:57 +0000763 SourceLocation LocStart = Method->getLocStart();
764 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff667f1682007-10-30 13:30:57 +0000765
Chris Lattner2d89c562009-02-04 01:06:56 +0000766 if (SM->getInstantiationLineNumber(LocEnd) >
767 SM->getInstantiationLineNumber(LocStart)) {
Steve Naroff99f50fe2008-10-21 13:37:27 +0000768 InsertText(LocStart, "#if 0\n", 6);
769 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff2ce399a2007-12-14 23:37:57 +0000770 } else {
Chris Lattner6216f292008-01-31 19:42:41 +0000771 InsertText(LocStart, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000772 }
773}
774
Steve Naroff56af2002009-01-11 01:06:09 +0000775void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop)
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000776{
Steve Naroff56af2002009-01-11 01:06:09 +0000777 SourceLocation Loc = prop->getLocation();
778
779 ReplaceText(Loc, 0, "// ", 3);
780
781 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000782}
783
Steve Naroff44e81222008-04-14 22:03:09 +0000784void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff667f1682007-10-30 13:30:57 +0000785 SourceLocation LocStart = CatDecl->getLocStart();
786
787 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000788 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000789
Ted Kremenek42730c52008-01-07 19:49:32 +0000790 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000791 E = CatDecl->instmeth_end(); I != E; ++I)
792 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000793 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000794 E = CatDecl->classmeth_end(); I != E; ++I)
795 RewriteMethodDeclaration(*I);
796
Steve Naroff667f1682007-10-30 13:30:57 +0000797 // Lastly, comment out the @end.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000798 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000799}
800
Steve Naroff44e81222008-04-14 22:03:09 +0000801void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000802 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000803
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000804 SourceLocation LocStart = PDecl->getLocStart();
805
806 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000807 ReplaceText(LocStart, 0, "// ", 3);
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000808
Ted Kremenek42730c52008-01-07 19:49:32 +0000809 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000810 E = PDecl->instmeth_end(); I != E; ++I)
811 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000812 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000813 E = PDecl->classmeth_end(); I != E; ++I)
814 RewriteMethodDeclaration(*I);
815
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000816 // Lastly, comment out the @end.
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000817 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000818 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff268fa592007-11-14 15:03:57 +0000819
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000820 // Must comment out @optional/@required
821 const char *startBuf = SM->getCharacterData(LocStart);
822 const char *endBuf = SM->getCharacterData(LocEnd);
823 for (const char *p = startBuf; p < endBuf; p++) {
824 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
825 std::string CommentedOptional = "/* @optional */";
Steve Naroff268fa592007-11-14 15:03:57 +0000826 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000827 ReplaceText(OptionalLoc, strlen("@optional"),
828 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000829
830 }
831 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
832 std::string CommentedRequired = "/* @required */";
Steve Naroff268fa592007-11-14 15:03:57 +0000833 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000834 ReplaceText(OptionalLoc, strlen("@required"),
835 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000836
837 }
838 }
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000839}
840
Steve Naroff44e81222008-04-14 22:03:09 +0000841void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000842 SourceLocation LocStart = PDecl->getLocation();
Steve Naroff0540f3f2007-11-14 03:37:28 +0000843 if (LocStart.isInvalid())
844 assert(false && "Invalid SourceLocation");
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000845 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000846 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000847}
848
Steve Naroff44e81222008-04-14 22:03:09 +0000849void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000850 std::string &ResultStr) {
Steve Naroff6449c6c2008-10-30 12:09:33 +0000851 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroff91044cf2008-07-16 14:40:40 +0000852 const FunctionType *FPRetType = 0;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000853 ResultStr += "\nstatic ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000854 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000855 ResultStr += "id";
Steve Naroff20f67392008-12-11 19:29:16 +0000856 else if (OMD->getResultType()->isFunctionPointerType() ||
857 OMD->getResultType()->isBlockPointerType()) {
Steve Naroff91044cf2008-07-16 14:40:40 +0000858 // needs special handling, since pointer-to-functions have special
859 // syntax (where a decaration models use).
860 QualType retType = OMD->getResultType();
Steve Naroff20f67392008-12-11 19:29:16 +0000861 QualType PointeeTy;
862 if (const PointerType* PT = retType->getAsPointerType())
863 PointeeTy = PT->getPointeeType();
864 else if (const BlockPointerType *BPT = retType->getAsBlockPointerType())
865 PointeeTy = BPT->getPointeeType();
866 if ((FPRetType = PointeeTy->getAsFunctionType())) {
867 ResultStr += FPRetType->getResultType().getAsString();
868 ResultStr += "(*";
Steve Naroff91044cf2008-07-16 14:40:40 +0000869 }
870 } else
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000871 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian7202d982008-01-10 01:39:52 +0000872 ResultStr += " ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000873
874 // Unique method name
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000875 std::string NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000876
Douglas Gregor5d764842009-01-09 17:18:27 +0000877 if (OMD->isInstanceMethod())
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000878 NameStr += "_I_";
879 else
880 NameStr += "_C_";
881
Chris Lattner271d4c22008-11-24 05:29:24 +0000882 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000883 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000884
Ted Kremenek42730c52008-01-07 19:49:32 +0000885 if (ObjCCategoryImplDecl *CID =
Steve Naroff438be772009-01-08 19:41:02 +0000886 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattner271d4c22008-11-24 05:29:24 +0000887 NameStr += CID->getNameAsString();
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000888 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000889 }
Steve Naroff5cb1e6e2008-04-04 22:23:44 +0000890 // Append selector names, replacing ':' with '_'
Chris Lattner3a8f2942008-11-24 03:33:13 +0000891 {
892 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000893 int len = selString.size();
894 for (int i = 0; i < len; i++)
895 if (selString[i] == ':')
896 selString[i] = '_';
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000897 NameStr += selString;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000898 }
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000899 // Remember this name for metadata emission
900 MethodInternalNames[OMD] = NameStr;
901 ResultStr += NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000902
903 // Rewrite arguments
904 ResultStr += "(";
905
906 // invisible arguments
Douglas Gregor5d764842009-01-09 17:18:27 +0000907 if (OMD->isInstanceMethod()) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000908 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000909 selfTy = Context->getPointerType(selfTy);
Steve Naroff60dfb6b2008-03-12 00:25:36 +0000910 if (!LangOpts.Microsoft) {
911 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
912 ResultStr += "struct ";
913 }
914 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattner271d4c22008-11-24 05:29:24 +0000915 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroffde0da102008-03-10 23:16:54 +0000916 ResultStr += " *";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000917 }
918 else
Ted Kremenek42730c52008-01-07 19:49:32 +0000919 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000920
921 ResultStr += " self, ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000922 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000923 ResultStr += " _cmd";
924
925 // Method arguments.
Chris Lattner5c6b2c62009-02-20 18:43:26 +0000926 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
927 E = OMD->param_end(); PI != E; ++PI) {
928 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000929 ResultStr += ", ";
Steve Naroff133dfda2008-04-18 21:13:19 +0000930 if (PDecl->getType()->isObjCQualifiedIdType()) {
931 ResultStr += "id ";
Chris Lattner271d4c22008-11-24 05:29:24 +0000932 ResultStr += PDecl->getNameAsString();
Steve Naroff133dfda2008-04-18 21:13:19 +0000933 } else {
Chris Lattner271d4c22008-11-24 05:29:24 +0000934 std::string Name = PDecl->getNameAsString();
Steve Naroffd896f4b2008-12-11 21:05:33 +0000935 if (isTopLevelBlockPointerType(PDecl->getType())) {
Steve Naroff4e2ae512008-10-30 14:45:29 +0000936 // Make sure we convert "t (^)(...)" to "t (*)(...)".
937 const BlockPointerType *BPT = PDecl->getType()->getAsBlockPointerType();
938 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name);
939 } else
940 PDecl->getType().getAsStringInternal(Name);
Steve Naroff133dfda2008-04-18 21:13:19 +0000941 ResultStr += Name;
942 }
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000943 }
Fariborz Jahanian2fab94e2008-01-21 20:14:23 +0000944 if (OMD->isVariadic())
945 ResultStr += ", ...";
Fariborz Jahanian7202d982008-01-10 01:39:52 +0000946 ResultStr += ") ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000947
Steve Naroff91044cf2008-07-16 14:40:40 +0000948 if (FPRetType) {
949 ResultStr += ")"; // close the precedence "scope" for "*".
950
951 // Now, emit the argument types (if any).
Douglas Gregor4fa58902009-02-26 23:50:07 +0000952 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff91044cf2008-07-16 14:40:40 +0000953 ResultStr += "(";
954 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
955 if (i) ResultStr += ", ";
956 std::string ParamStr = FT->getArgType(i).getAsString();
957 ResultStr += ParamStr;
958 }
959 if (FT->isVariadic()) {
960 if (FT->getNumArgs()) ResultStr += ", ";
961 ResultStr += "...";
962 }
963 ResultStr += ")";
964 } else {
965 ResultStr += "()";
966 }
967 }
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000968}
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000969void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000970 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
971 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000972
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000973 if (IMD)
Chris Lattner6216f292008-01-31 19:42:41 +0000974 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000975 else
Chris Lattner6216f292008-01-31 19:42:41 +0000976 InsertText(CID->getLocStart(), "// ", 3);
Steve Naroff21658f62008-11-13 20:07:04 +0000977
Ted Kremenek42730c52008-01-07 19:49:32 +0000978 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000979 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
980 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000981 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000982 ObjCMethodDecl *OMD = *I;
983 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000984 SourceLocation LocStart = OMD->getLocStart();
985 SourceLocation LocEnd = OMD->getBody()->getLocStart();
986
987 const char *startBuf = SM->getCharacterData(LocStart);
988 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000989 ReplaceText(LocStart, endBuf-startBuf,
990 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000991 }
992
Ted Kremenek42730c52008-01-07 19:49:32 +0000993 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000994 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
995 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000996 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000997 ObjCMethodDecl *OMD = *I;
998 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000999 SourceLocation LocStart = OMD->getLocStart();
1000 SourceLocation LocEnd = OMD->getBody()->getLocStart();
1001
1002 const char *startBuf = SM->getCharacterData(LocStart);
1003 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001004 ReplaceText(LocStart, endBuf-startBuf,
1005 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +00001006 }
Steve Naroff110be842008-12-01 20:33:01 +00001007 for (ObjCCategoryImplDecl::propimpl_iterator
1008 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1009 E = IMD ? IMD->propimpl_end() : CID->propimpl_end(); I != E; ++I) {
Steve Naroffea6610f2008-12-02 17:36:43 +00001010 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroff110be842008-12-01 20:33:01 +00001011 }
1012
Fariborz Jahanian0136e372007-11-13 20:04:28 +00001013 if (IMD)
Chris Lattner6216f292008-01-31 19:42:41 +00001014 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian0136e372007-11-13 20:04:28 +00001015 else
Chris Lattner6216f292008-01-31 19:42:41 +00001016 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +00001017}
1018
Steve Naroff44e81222008-04-14 22:03:09 +00001019void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffef20ed32007-10-30 02:23:23 +00001020 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +00001021 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff77d081b2007-11-01 03:35:41 +00001022 // we haven't seen a forward decl - generate a typedef.
Steve Naroff2adead72007-11-14 23:02:56 +00001023 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattner271d4c22008-11-24 05:29:24 +00001024 ResultStr += ClassDecl->getNameAsString();
Steve Naroff2aeae312007-11-09 12:50:28 +00001025 ResultStr += "\n";
1026 ResultStr += "#define _REWRITER_typedef_";
Chris Lattner271d4c22008-11-24 05:29:24 +00001027 ResultStr += ClassDecl->getNameAsString();
Steve Naroff2aeae312007-11-09 12:50:28 +00001028 ResultStr += "\n";
Steve Naroffde0da102008-03-10 23:16:54 +00001029 ResultStr += "typedef struct objc_object ";
Chris Lattner271d4c22008-11-24 05:29:24 +00001030 ResultStr += ClassDecl->getNameAsString();
Steve Naroff2aeae312007-11-09 12:50:28 +00001031 ResultStr += ";\n#endif\n";
Steve Naroff77d081b2007-11-01 03:35:41 +00001032 // Mark this typedef as having been generated.
Ted Kremenek42730c52008-01-07 19:49:32 +00001033 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff77d081b2007-11-01 03:35:41 +00001034 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001035 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Naroffef20ed32007-10-30 02:23:23 +00001036
Steve Naroff56af2002009-01-11 01:06:09 +00001037 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
1038 E = ClassDecl->prop_end(); I != E; ++I)
1039 RewriteProperty(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +00001040 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +00001041 E = ClassDecl->instmeth_end(); I != E; ++I)
1042 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +00001043 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +00001044 E = ClassDecl->classmeth_end(); I != E; ++I)
1045 RewriteMethodDeclaration(*I);
1046
Steve Naroff1ccf4632007-10-30 03:43:13 +00001047 // Lastly, comment out the @end.
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001048 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff3774dd92007-10-26 20:53:56 +00001049}
1050
Steve Naroffedb4bc92008-12-09 12:56:34 +00001051Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1052 SourceRange SrcRange) {
Steve Naroff0e948412008-12-04 16:24:46 +00001053 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1054 // This allows us to reuse all the fun and games in SynthMessageExpr().
1055 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1056 ObjCMessageExpr *MsgExpr;
1057 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1058 llvm::SmallVector<Expr *, 1> ExprVec;
1059 ExprVec.push_back(newStmt);
1060
Steve Narofffbed6802008-12-08 16:43:47 +00001061 Stmt *Receiver = PropRefExpr->getBase();
1062 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1063 if (PRE && PropGetters[PRE]) {
1064 // This allows us to handle chain/nested property getters.
1065 Receiver = PropGetters[PRE];
1066 }
Ted Kremenek0c97e042009-02-07 01:47:29 +00001067 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
Steve Naroff0e948412008-12-04 16:24:46 +00001068 PDecl->getSetterName(), PDecl->getType(),
1069 PDecl->getSetterMethodDecl(),
1070 SourceLocation(), SourceLocation(),
1071 &ExprVec[0], 1);
1072 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
1073
1074 // Now do the actual rewrite.
Steve Naroffedb4bc92008-12-09 12:56:34 +00001075 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroff478f7382008-12-10 14:53:27 +00001076 //delete BinOp;
Ted Kremenek0c97e042009-02-07 01:47:29 +00001077 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1078 // to things that stay around.
1079 Context->Deallocate(MsgExpr);
Steve Naroff0e948412008-12-04 16:24:46 +00001080 return ReplacingStmt;
Steve Narofff6ce8a12008-12-03 00:56:33 +00001081}
1082
Steve Naroff0e948412008-12-04 16:24:46 +00001083Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Narofff6ce8a12008-12-03 00:56:33 +00001084 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1085 // This allows us to reuse all the fun and games in SynthMessageExpr().
1086 ObjCMessageExpr *MsgExpr;
1087 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1088
Steve Narofffbed6802008-12-08 16:43:47 +00001089 Stmt *Receiver = PropRefExpr->getBase();
1090
1091 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1092 if (PRE && PropGetters[PRE]) {
1093 // This allows us to handle chain/nested property getters.
1094 Receiver = PropGetters[PRE];
1095 }
Ted Kremenek0c97e042009-02-07 01:47:29 +00001096 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
Steve Narofff6ce8a12008-12-03 00:56:33 +00001097 PDecl->getGetterName(), PDecl->getType(),
1098 PDecl->getGetterMethodDecl(),
1099 SourceLocation(), SourceLocation(),
1100 0, 0);
1101
Steve Naroff102c3f22008-12-04 23:50:32 +00001102 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Narofffbed6802008-12-08 16:43:47 +00001103
1104 if (!PropParentMap)
1105 PropParentMap = new ParentMap(CurrentBody);
1106
1107 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1108 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1109 // We stash away the ReplacingStmt since actually doing the
1110 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1111 PropGetters[PropRefExpr] = ReplacingStmt;
Ted Kremenek0c97e042009-02-07 01:47:29 +00001112 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1113 // to things that stay around.
1114 Context->Deallocate(MsgExpr);
Steve Narofffbed6802008-12-08 16:43:47 +00001115 return PropRefExpr; // return the original...
1116 } else {
1117 ReplaceStmt(PropRefExpr, ReplacingStmt);
Ted Kremenek0c97e042009-02-07 01:47:29 +00001118 // delete PropRefExpr; elsewhere...
1119 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1120 // to things that stay around.
1121 Context->Deallocate(MsgExpr);
Steve Narofffbed6802008-12-08 16:43:47 +00001122 return ReplacingStmt;
1123 }
Steve Narofff6ce8a12008-12-03 00:56:33 +00001124}
1125
Chris Lattner343c82b2008-05-23 20:40:52 +00001126Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
1127 SourceLocation OrigStart) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001128 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00001129 if (CurMethodDef) {
Steve Naroff60dfb6b2008-03-12 00:25:36 +00001130 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Ted Kremenek0c97e042009-02-07 01:47:29 +00001131 ObjCInterfaceType *iFaceDecl =
1132 dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroffa9636222008-05-08 17:52:16 +00001133 // lookup which class implements the instance variable.
1134 ObjCInterfaceDecl *clsDeclared = 0;
1135 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
1136 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1137
1138 // Synthesize an explicit cast to gain access to the ivar.
1139 std::string RecName = clsDeclared->getIdentifier()->getName();
1140 RecName += "_IMPL";
1141 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001142 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek2c984042008-09-05 01:34:33 +00001143 SourceLocation(), II);
Steve Naroffa9636222008-05-08 17:52:16 +00001144 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1145 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Ted Kremenek0c97e042009-02-07 01:47:29 +00001146 CastExpr *castExpr = new (Context) CStyleCastExpr(castT, IV->getBase(),
1147 castT,SourceLocation(),
1148 SourceLocation());
Steve Naroffa9636222008-05-08 17:52:16 +00001149 // Don't forget the parens to enforce the proper binding.
Ted Kremenek0c97e042009-02-07 01:47:29 +00001150 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1151 IV->getBase()->getLocEnd(),
1152 castExpr);
Steve Naroffa9636222008-05-08 17:52:16 +00001153 if (IV->isFreeIvar() &&
Steve Naroff38a9e3f2008-10-27 17:20:55 +00001154 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek0c97e042009-02-07 01:47:29 +00001155 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1156 IV->getLocation(),
1157 D->getType());
Steve Naroffa9636222008-05-08 17:52:16 +00001158 ReplaceStmt(IV, ME);
Steve Naroff102c3f22008-12-04 23:50:32 +00001159 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffa9636222008-05-08 17:52:16 +00001160 return ME;
Steve Naroff292b7b92007-11-15 11:33:00 +00001161 }
Chris Lattner343c82b2008-05-23 20:40:52 +00001162
1163 ReplaceStmt(IV->getBase(), PE);
1164 // Cannot delete IV->getBase(), since PE points to it.
1165 // Replace the old base with the cast. This is important when doing
1166 // embedded rewrites. For example, [newInv->_container addObject:0].
1167 IV->setBase(PE);
1168 return IV;
Steve Naroff292b7b92007-11-15 11:33:00 +00001169 }
Steve Naroffe6155362008-04-18 21:55:08 +00001170 } else { // we are outside a method.
Steve Naroffd8d30b92008-05-06 23:20:07 +00001171 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
1172
1173 // Explicit ivar refs need to have a cast inserted.
1174 // FIXME: consider sharing some of this code with the code above.
1175 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Naroffa9636222008-05-08 17:52:16 +00001176 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroffd8d30b92008-05-06 23:20:07 +00001177 // lookup which class implements the instance variable.
1178 ObjCInterfaceDecl *clsDeclared = 0;
Steve Naroffa9636222008-05-08 17:52:16 +00001179 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
Steve Naroffd8d30b92008-05-06 23:20:07 +00001180 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1181
1182 // Synthesize an explicit cast to gain access to the ivar.
1183 std::string RecName = clsDeclared->getIdentifier()->getName();
1184 RecName += "_IMPL";
1185 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001186 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek2c984042008-09-05 01:34:33 +00001187 SourceLocation(), II);
Steve Naroffd8d30b92008-05-06 23:20:07 +00001188 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1189 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Ted Kremenek0c97e042009-02-07 01:47:29 +00001190 CastExpr *castExpr = new (Context) CStyleCastExpr(castT, IV->getBase(),
1191 castT, SourceLocation(),
1192 SourceLocation());
Steve Naroffd8d30b92008-05-06 23:20:07 +00001193 // Don't forget the parens to enforce the proper binding.
Ted Kremenek0c97e042009-02-07 01:47:29 +00001194 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner3cca6612008-05-28 16:38:23 +00001195 IV->getBase()->getLocEnd(), castExpr);
Steve Naroffd8d30b92008-05-06 23:20:07 +00001196 ReplaceStmt(IV->getBase(), PE);
1197 // Cannot delete IV->getBase(), since PE points to it.
1198 // Replace the old base with the cast. This is important when doing
1199 // embedded rewrites. For example, [newInv->_container addObject:0].
1200 IV->setBase(PE);
1201 return IV;
1202 }
Steve Naroff292b7b92007-11-15 11:33:00 +00001203 }
Steve Naroffe6155362008-04-18 21:55:08 +00001204 return IV;
Steve Naroff6b759ce2007-11-15 02:58:25 +00001205}
1206
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001207/// SynthCountByEnumWithState - To print:
1208/// ((unsigned int (*)
1209/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1210/// (void *)objc_msgSend)((id)l_collection,
1211/// sel_registerName(
1212/// "countByEnumeratingWithState:objects:count:"),
1213/// &enumState,
1214/// (id *)items, (unsigned int)16)
1215///
Steve Naroff44e81222008-04-14 22:03:09 +00001216void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001217 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1218 "id *, unsigned int))(void *)objc_msgSend)";
1219 buf += "\n\t\t";
1220 buf += "((id)l_collection,\n\t\t";
1221 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1222 buf += "\n\t\t";
1223 buf += "&enumState, "
1224 "(id *)items, (unsigned int)16)";
1225}
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001226
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001227/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1228/// statement to exit to its outer synthesized loop.
1229///
Steve Naroff44e81222008-04-14 22:03:09 +00001230Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001231 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1232 return S;
1233 // replace break with goto __break_label
1234 std::string buf;
1235
1236 SourceLocation startLoc = S->getLocStart();
1237 buf = "goto __break_label_";
1238 buf += utostr(ObjCBcLabelNo.back());
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001239 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001240
1241 return 0;
1242}
1243
1244/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1245/// statement to continue with its inner synthesized loop.
1246///
Steve Naroff44e81222008-04-14 22:03:09 +00001247Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001248 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1249 return S;
1250 // replace continue with goto __continue_label
1251 std::string buf;
1252
1253 SourceLocation startLoc = S->getLocStart();
1254 buf = "goto __continue_label_";
1255 buf += utostr(ObjCBcLabelNo.back());
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001256 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001257
1258 return 0;
1259}
1260
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001261/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001262/// It rewrites:
1263/// for ( type elem in collection) { stmts; }
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00001264
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001265/// Into:
1266/// {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001267/// type elem;
1268/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001269/// id items[16];
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001270/// id l_collection = (id)collection;
1271/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1272/// objects:items count:16];
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001273/// if (limit) {
1274/// unsigned long startMutations = *enumState.mutationsPtr;
1275/// do {
1276/// unsigned long counter = 0;
1277/// do {
1278/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001279/// objc_enumerationMutation(l_collection);
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001280/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001281/// stmts;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001282/// __continue_label: ;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001283/// } while (counter < limit);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001284/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1285/// objects:items count:16]);
1286/// elem = nil;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001287/// __break_label: ;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001288/// }
1289/// else
1290/// elem = nil;
1291/// }
1292///
Steve Naroff44e81222008-04-14 22:03:09 +00001293Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner2c022162008-01-31 05:10:40 +00001294 SourceLocation OrigEnd) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001295 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1296 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1297 "ObjCForCollectionStmt Statement stack mismatch");
1298 assert(!ObjCBcLabelNo.empty() &&
1299 "ObjCForCollectionStmt - Label No stack empty");
1300
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001301 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001302 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001303 const char *elementName;
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001304 std::string elementTypeAsString;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001305 std::string buf;
1306 buf = "\n{\n\t";
1307 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1308 // type elem;
Chris Lattner4a9a85e2009-03-28 06:33:19 +00001309 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek91a2bd32008-10-06 22:16:13 +00001310 QualType ElementType = cast<ValueDecl>(D)->getType();
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001311 elementTypeAsString = ElementType.getAsString();
1312 buf += elementTypeAsString;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001313 buf += " ";
Chris Lattnerd120b9e2008-11-24 03:54:41 +00001314 elementName = D->getNameAsCString();
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001315 buf += elementName;
1316 buf += ";\n\t";
1317 }
Chris Lattner690c2872008-04-08 05:52:18 +00001318 else {
1319 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattnerd120b9e2008-11-24 03:54:41 +00001320 elementName = DR->getDecl()->getNameAsCString();
Douglas Gregord2baafd2008-10-21 16:13:35 +00001321 elementTypeAsString
1322 = cast<ValueDecl>(DR->getDecl())->getType().getAsString();
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001323 }
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001324
1325 // struct __objcFastEnumerationState enumState = { 0 };
1326 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1327 // id items[16];
1328 buf += "id items[16];\n\t";
1329 // id l_collection = (id)
1330 buf += "id l_collection = (id)";
Fariborz Jahaniandf2b0952008-01-10 00:24:29 +00001331 // Find start location of 'collection' the hard way!
1332 const char *startCollectionBuf = startBuf;
1333 startCollectionBuf += 3; // skip 'for'
1334 startCollectionBuf = strchr(startCollectionBuf, '(');
1335 startCollectionBuf++; // skip '('
1336 // find 'in' and skip it.
1337 while (*startCollectionBuf != ' ' ||
1338 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1339 (*(startCollectionBuf+3) != ' ' &&
1340 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1341 startCollectionBuf++;
1342 startCollectionBuf += 3;
1343
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001344 // Replace: "for (type element in" with string constructed thus far.
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001345 ReplaceText(startLoc, startCollectionBuf - startBuf,
1346 buf.c_str(), buf.size());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001347 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahaniandf2b0952008-01-10 00:24:29 +00001348 SourceLocation rightParenLoc = S->getRParenLoc();
1349 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1350 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001351 buf = ";\n\t";
1352
1353 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1354 // objects:items count:16];
1355 // which is synthesized into:
1356 // unsigned int limit =
1357 // ((unsigned int (*)
1358 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1359 // (void *)objc_msgSend)((id)l_collection,
1360 // sel_registerName(
1361 // "countByEnumeratingWithState:objects:count:"),
1362 // (struct __objcFastEnumerationState *)&state,
1363 // (id *)items, (unsigned int)16);
1364 buf += "unsigned long limit =\n\t\t";
1365 SynthCountByEnumWithState(buf);
1366 buf += ";\n\t";
1367 /// if (limit) {
1368 /// unsigned long startMutations = *enumState.mutationsPtr;
1369 /// do {
1370 /// unsigned long counter = 0;
1371 /// do {
1372 /// if (startMutations != *enumState.mutationsPtr)
1373 /// objc_enumerationMutation(l_collection);
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001374 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001375 buf += "if (limit) {\n\t";
1376 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1377 buf += "do {\n\t\t";
1378 buf += "unsigned long counter = 0;\n\t\t";
1379 buf += "do {\n\t\t\t";
1380 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1381 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1382 buf += elementName;
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001383 buf += " = (";
1384 buf += elementTypeAsString;
1385 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001386 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001387 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001388
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001389 /// __continue_label: ;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001390 /// } while (counter < limit);
1391 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1392 /// objects:items count:16]);
1393 /// elem = nil;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001394 /// __break_label: ;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001395 /// }
1396 /// else
1397 /// elem = nil;
1398 /// }
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001399 ///
1400 buf = ";\n\t";
1401 buf += "__continue_label_";
1402 buf += utostr(ObjCBcLabelNo.back());
1403 buf += ": ;";
1404 buf += "\n\t\t";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001405 buf += "} while (counter < limit);\n\t";
1406 buf += "} while (limit = ";
1407 SynthCountByEnumWithState(buf);
1408 buf += ");\n\t";
1409 buf += elementName;
Steve Naroffa9dc0262008-12-17 14:24:39 +00001410 buf += " = ((id)0);\n\t";
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001411 buf += "__break_label_";
1412 buf += utostr(ObjCBcLabelNo.back());
1413 buf += ": ;\n\t";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001414 buf += "}\n\t";
1415 buf += "else\n\t\t";
1416 buf += elementName;
Steve Naroffa9dc0262008-12-17 14:24:39 +00001417 buf += " = ((id)0);\n";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001418 buf += "}\n";
Steve Naroff5f238fe2008-07-21 18:26:02 +00001419
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001420 // Insert all these *after* the statement body.
Steve Naroff5f238fe2008-07-21 18:26:02 +00001421 if (isa<CompoundStmt>(S->getBody())) {
1422 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1423 InsertText(endBodyLoc, buf.c_str(), buf.size());
1424 } else {
1425 /* Need to treat single statements specially. For example:
1426 *
1427 * for (A *a in b) if (stuff()) break;
1428 * for (A *a in b) xxxyy;
1429 *
1430 * The following code simply scans ahead to the semi to find the actual end.
1431 */
1432 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1433 const char *semiBuf = strchr(stmtBuf, ';');
1434 assert(semiBuf && "Can't find ';'");
1435 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1436 InsertText(endBodyLoc, buf.c_str(), buf.size());
1437 }
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001438 Stmts.pop_back();
1439 ObjCBcLabelNo.pop_back();
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001440 return 0;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001441}
1442
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001443/// RewriteObjCSynchronizedStmt -
1444/// This routine rewrites @synchronized(expr) stmt;
1445/// into:
1446/// objc_sync_enter(expr);
1447/// @try stmt @finally { objc_sync_exit(expr); }
1448///
Steve Naroff44e81222008-04-14 22:03:09 +00001449Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001450 // Get the start location and compute the semi location.
1451 SourceLocation startLoc = S->getLocStart();
1452 const char *startBuf = SM->getCharacterData(startLoc);
1453
1454 assert((*startBuf == '@') && "bogus @synchronized location");
1455
1456 std::string buf;
Steve Naroffc1656a62008-08-21 13:03:03 +00001457 buf = "objc_sync_enter((id)";
1458 const char *lparenBuf = startBuf;
1459 while (*lparenBuf != '(') lparenBuf++;
1460 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Steve Naroff027cd0b2008-08-19 13:04:19 +00001461 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1462 // the sync expression is typically a message expression that's already
1463 // been rewritten! (which implies the SourceLocation's are invalid).
1464 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001465 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroff027cd0b2008-08-19 13:04:19 +00001466 while (*endBuf != ')') endBuf--;
1467 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001468 buf = ");\n";
1469 // declare a new scope with two variables, _stack and _rethrow.
1470 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1471 buf += "int buf[18/*32-bit i386*/];\n";
1472 buf += "char *pointers[4];} _stack;\n";
1473 buf += "id volatile _rethrow = 0;\n";
1474 buf += "objc_exception_try_enter(&_stack);\n";
1475 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001476 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001477 startLoc = S->getSynchBody()->getLocEnd();
1478 startBuf = SM->getCharacterData(startLoc);
1479
Steve Naroff027cd0b2008-08-19 13:04:19 +00001480 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001481 SourceLocation lastCurlyLoc = startLoc;
1482 buf = "}\nelse {\n";
1483 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1484 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroff17919b52008-07-16 19:47:39 +00001485 buf += " objc_sync_exit(";
Ted Kremenek0c97e042009-02-07 01:47:29 +00001486 Expr *syncExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
1487 S->getSynchExpr(),
1488 Context->getObjCIdType(),
1489 SourceLocation(),
1490 SourceLocation());
Ted Kremenek7b6f67b2008-09-13 05:16:45 +00001491 std::string syncExprBufS;
1492 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Steve Naroffc1656a62008-08-21 13:03:03 +00001493 syncExpr->printPretty(syncExprBuf);
Steve Naroff17919b52008-07-16 19:47:39 +00001494 buf += syncExprBuf.str();
1495 buf += ");\n";
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001496 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1497 buf += "}\n";
1498 buf += "}";
1499
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001500 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001501 return 0;
1502}
1503
Steve Naroff43964fb2008-12-05 17:03:39 +00001504void RewriteObjC::WarnAboutReturnGotoContinueOrBreakStmts(Stmt *S) {
1505 // Perform a bottom up traversal of all children.
1506 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1507 CI != E; ++CI)
1508 if (*CI)
1509 WarnAboutReturnGotoContinueOrBreakStmts(*CI);
1510
1511 if (isa<ReturnStmt>(S) || isa<ContinueStmt>(S) ||
1512 isa<BreakStmt>(S) || isa<GotoStmt>(S)) {
1513 Diags.Report(Context->getFullLoc(S->getLocStart()),
1514 TryFinallyContainsReturnDiag);
1515 }
1516 return;
1517}
1518
Steve Naroff44e81222008-04-14 22:03:09 +00001519Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001520 // Get the start location and compute the semi location.
1521 SourceLocation startLoc = S->getLocStart();
1522 const char *startBuf = SM->getCharacterData(startLoc);
1523
1524 assert((*startBuf == '@') && "bogus @try location");
1525
1526 std::string buf;
1527 // declare a new scope with two variables, _stack and _rethrow.
1528 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1529 buf += "int buf[18/*32-bit i386*/];\n";
1530 buf += "char *pointers[4];} _stack;\n";
1531 buf += "id volatile _rethrow = 0;\n";
1532 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +00001533 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffe9f69842007-11-07 04:08:17 +00001534
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001535 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001536
1537 startLoc = S->getTryBody()->getLocEnd();
1538 startBuf = SM->getCharacterData(startLoc);
1539
1540 assert((*startBuf == '}') && "bogus @try block");
Steve Naroff9d0ff352008-07-16 15:31:30 +00001541
Steve Naroffe9f69842007-11-07 04:08:17 +00001542 SourceLocation lastCurlyLoc = startLoc;
Steve Naroff9d0ff352008-07-16 15:31:30 +00001543 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1544 if (catchList) {
1545 startLoc = startLoc.getFileLocWithOffset(1);
1546 buf = " /* @catch begin */ else {\n";
1547 buf += " id _caught = objc_exception_extract(&_stack);\n";
1548 buf += " objc_exception_try_enter (&_stack);\n";
1549 buf += " if (_setjmp(_stack.buf))\n";
1550 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1551 buf += " else { /* @catch continue */";
1552
1553 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff36269d22008-09-09 19:59:12 +00001554 } else { /* no catch list */
1555 buf = "}\nelse {\n";
1556 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1557 buf += "}";
1558 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroff9d0ff352008-07-16 15:31:30 +00001559 }
Steve Naroffe9f69842007-11-07 04:08:17 +00001560 bool sawIdTypedCatch = false;
1561 Stmt *lastCatchBody = 0;
Steve Naroffe9f69842007-11-07 04:08:17 +00001562 while (catchList) {
Steve Naroff0e8b96a2009-03-03 19:52:17 +00001563 ParmVarDecl *catchDecl = catchList->getCatchParamDecl();
Steve Naroffe9f69842007-11-07 04:08:17 +00001564
1565 if (catchList == S->getCatchStmts())
1566 buf = "if ("; // we are generating code for the first catch clause
1567 else
1568 buf = "else if (";
1569 startLoc = catchList->getLocStart();
1570 startBuf = SM->getCharacterData(startLoc);
1571
1572 assert((*startBuf == '@') && "bogus @catch location");
1573
1574 const char *lParenLoc = strchr(startBuf, '(');
1575
Steve Naroff397c4ce2008-02-01 22:08:12 +00001576 if (catchList->hasEllipsis()) {
Steve Naroff929c77e2008-02-01 20:02:07 +00001577 // Now rewrite the body...
1578 lastCatchBody = catchList->getCatchBody();
Steve Naroff929c77e2008-02-01 20:02:07 +00001579 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1580 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner690c2872008-04-08 05:52:18 +00001581 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1582 "bogus @catch paren location");
Steve Naroff929c77e2008-02-01 20:02:07 +00001583 assert((*bodyBuf == '{') && "bogus @catch body location");
1584
1585 buf += "1) { id _tmp = _caught;";
1586 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1587 buf.c_str(), buf.size());
Steve Naroff0e8b96a2009-03-03 19:52:17 +00001588 } else if (catchDecl) {
1589 QualType t = catchDecl->getType();
Ted Kremenek42730c52008-01-07 19:49:32 +00001590 if (t == Context->getObjCIdType()) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001591 buf += "1) { ";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001592 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001593 sawIdTypedCatch = true;
1594 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001595 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroffe9f69842007-11-07 04:08:17 +00001596
Ted Kremenek42730c52008-01-07 19:49:32 +00001597 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroffe9f69842007-11-07 04:08:17 +00001598 if (cls) {
Steve Naroffd3287d82007-11-07 18:43:40 +00001599 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattner271d4c22008-11-24 05:29:24 +00001600 buf += cls->getDecl()->getNameAsString();
Steve Naroffd3287d82007-11-07 18:43:40 +00001601 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001602 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001603 }
1604 }
1605 // Now rewrite the body...
1606 lastCatchBody = catchList->getCatchBody();
1607 SourceLocation rParenLoc = catchList->getRParenLoc();
1608 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1609 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1610 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1611 assert((*rParenBuf == ')') && "bogus @catch paren location");
1612 assert((*bodyBuf == '{') && "bogus @catch body location");
1613
1614 buf = " = _caught;";
1615 // Here we replace ") {" with "= _caught;" (which initializes and
1616 // declares the @catch parameter).
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001617 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff0e8b96a2009-03-03 19:52:17 +00001618 } else {
Steve Naroffe9f69842007-11-07 04:08:17 +00001619 assert(false && "@catch rewrite bug");
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001620 }
Steve Naroff929c77e2008-02-01 20:02:07 +00001621 // make sure all the catch bodies get rewritten!
Steve Naroffe9f69842007-11-07 04:08:17 +00001622 catchList = catchList->getNextCatchStmt();
1623 }
1624 // Complete the catch list...
1625 if (lastCatchBody) {
1626 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner690c2872008-04-08 05:52:18 +00001627 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1628 "bogus @catch body location");
Steve Naroffe9f69842007-11-07 04:08:17 +00001629
Steve Naroff31325c12008-09-11 15:29:03 +00001630 // Insert the last (implicit) else clause *before* the right curly brace.
1631 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1632 buf = "} /* last catch end */\n";
1633 buf += "else {\n";
1634 buf += " _rethrow = _caught;\n";
1635 buf += " objc_exception_try_exit(&_stack);\n";
1636 buf += "} } /* @catch end */\n";
1637 if (!S->getFinallyStmt())
1638 buf += "}\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001639 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001640
1641 // Set lastCurlyLoc
1642 lastCurlyLoc = lastCatchBody->getLocEnd();
1643 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001644 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001645 startLoc = finalStmt->getLocStart();
1646 startBuf = SM->getCharacterData(startLoc);
1647 assert((*startBuf == '@') && "bogus @finally start");
1648
1649 buf = "/* @finally */";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001650 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001651
1652 Stmt *body = finalStmt->getFinallyBody();
1653 SourceLocation startLoc = body->getLocStart();
1654 SourceLocation endLoc = body->getLocEnd();
Chris Lattner690c2872008-04-08 05:52:18 +00001655 assert(*SM->getCharacterData(startLoc) == '{' &&
1656 "bogus @finally body location");
1657 assert(*SM->getCharacterData(endLoc) == '}' &&
1658 "bogus @finally body location");
Steve Naroffe9f69842007-11-07 04:08:17 +00001659
1660 startLoc = startLoc.getFileLocWithOffset(1);
1661 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001662 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001663 endLoc = endLoc.getFileLocWithOffset(-1);
1664 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001665 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001666
1667 // Set lastCurlyLoc
1668 lastCurlyLoc = body->getLocEnd();
Steve Naroff43964fb2008-12-05 17:03:39 +00001669
1670 // Now check for any return/continue/go statements within the @try.
1671 WarnAboutReturnGotoContinueOrBreakStmts(S->getTryBody());
Steve Naroff31325c12008-09-11 15:29:03 +00001672 } else { /* no finally clause - make sure we synthesize an implicit one */
1673 buf = "{ /* implicit finally clause */\n";
1674 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1675 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1676 buf += "}";
1677 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001678 }
1679 // Now emit the final closing curly brace...
1680 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1681 buf = " } /* @try scope end */\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001682 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001683 return 0;
1684}
1685
Steve Naroff44e81222008-04-14 22:03:09 +00001686Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001687 return 0;
1688}
1689
Steve Naroff44e81222008-04-14 22:03:09 +00001690Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001691 return 0;
1692}
1693
Chris Lattnerb1548372008-01-31 19:37:57 +00001694// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001695// the throw expression is typically a message expression that's already
1696// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroff44e81222008-04-14 22:03:09 +00001697Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001698 // Get the start location and compute the semi location.
1699 SourceLocation startLoc = S->getLocStart();
1700 const char *startBuf = SM->getCharacterData(startLoc);
1701
1702 assert((*startBuf == '@') && "bogus @throw location");
1703
1704 std::string buf;
1705 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffbe72efa2008-01-19 00:42:38 +00001706 if (S->getThrowExpr())
1707 buf = "objc_exception_throw(";
1708 else // add an implicit argument
1709 buf = "objc_exception_throw(_caught";
Steve Naroff3de6eaa2008-07-25 15:41:30 +00001710
1711 // handle "@ throw" correctly.
1712 const char *wBuf = strchr(startBuf, 'w');
1713 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1714 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
1715
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001716 const char *semiBuf = strchr(startBuf, ';');
1717 assert((*semiBuf == ';') && "@throw: can't find ';'");
1718 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1719 buf = ");";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001720 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001721 return 0;
1722}
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001723
Steve Naroff44e81222008-04-14 22:03:09 +00001724Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerbf0bfa62007-10-17 22:35:30 +00001725 // Create a new string expression.
1726 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson36f07d82007-10-29 05:01:08 +00001727 std::string StrEncoding;
Daniel Dunbarc9197cd2008-10-17 20:21:44 +00001728 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattneraa491192009-02-18 06:40:38 +00001729 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
1730 StrEncoding.length(), false,StrType,
1731 SourceLocation());
Chris Lattnerb1548372008-01-31 19:37:57 +00001732 ReplaceStmt(Exp, Replacement);
Chris Lattner258f26c2007-11-30 22:25:36 +00001733
Chris Lattner4478db92007-11-30 22:53:43 +00001734 // Replace this subexpr in the parent.
Steve Naroff102c3f22008-12-04 23:50:32 +00001735 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattner0021f452007-10-24 16:57:36 +00001736 return Replacement;
Chris Lattner6fe8b272007-10-16 22:36:42 +00001737}
1738
Steve Naroff44e81222008-04-14 22:03:09 +00001739Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff95f6bce2008-12-22 22:16:07 +00001740 if (!SelGetUidFunctionDecl)
1741 SynthSelGetUidFunctionDecl();
Steve Naroff296b74f2007-11-05 14:50:49 +00001742 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1743 // Create a call to sel_registerName("selName").
1744 llvm::SmallVector<Expr*, 8> SelExprs;
1745 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattneraa491192009-02-18 06:40:38 +00001746 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek4f530a92009-02-06 19:55:15 +00001747 Exp->getSelector().getAsString().c_str(),
Chris Lattner3a8f2942008-11-24 03:33:13 +00001748 Exp->getSelector().getAsString().size(),
Chris Lattnerc3144742009-02-18 05:49:11 +00001749 false, argType, SourceLocation()));
Steve Naroff296b74f2007-11-05 14:50:49 +00001750 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1751 &SelExprs[0], SelExprs.size());
Chris Lattnerb1548372008-01-31 19:37:57 +00001752 ReplaceStmt(Exp, SelExp);
Steve Naroff102c3f22008-12-04 23:50:32 +00001753 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff296b74f2007-11-05 14:50:49 +00001754 return SelExp;
1755}
1756
Steve Naroff44e81222008-04-14 22:03:09 +00001757CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff71226032007-10-24 22:48:43 +00001758 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffe9780582007-10-23 23:50:29 +00001759 // Get the type, we will need to reference it in a couple spots.
Steve Naroff71226032007-10-24 22:48:43 +00001760 QualType msgSendType = FD->getType();
Steve Naroffe9780582007-10-23 23:50:29 +00001761
1762 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek0c97e042009-02-07 01:47:29 +00001763 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffe9780582007-10-23 23:50:29 +00001764
1765 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerfce2c5a2007-10-24 17:06:59 +00001766 QualType pToFunc = Context->getPointerType(msgSendType);
Ted Kremenek0c97e042009-02-07 01:47:29 +00001767 ImplicitCastExpr *ICE = new (Context) ImplicitCastExpr(pToFunc, DRE,
Douglas Gregor70d26122008-11-12 17:17:38 +00001768 /*isLvalue=*/false);
Steve Naroffe9780582007-10-23 23:50:29 +00001769
1770 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattner0021f452007-10-24 16:57:36 +00001771
Ted Kremenek362abcd2009-02-09 20:51:47 +00001772 return new (Context) CallExpr(*Context, ICE, args, nargs, FT->getResultType(),
1773 SourceLocation());
Steve Naroff71226032007-10-24 22:48:43 +00001774}
1775
Steve Naroffc8a92d12007-11-01 13:24:47 +00001776static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1777 const char *&startRef, const char *&endRef) {
1778 while (startBuf < endBuf) {
1779 if (*startBuf == '<')
1780 startRef = startBuf; // mark the start.
1781 if (*startBuf == '>') {
Steve Naroff2aeae312007-11-09 12:50:28 +00001782 if (startRef && *startRef == '<') {
1783 endRef = startBuf; // mark the end.
1784 return true;
1785 }
1786 return false;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001787 }
1788 startBuf++;
1789 }
1790 return false;
1791}
1792
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001793static void scanToNextArgument(const char *&argRef) {
1794 int angle = 0;
1795 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1796 if (*argRef == '<')
1797 angle++;
1798 else if (*argRef == '>')
1799 angle--;
1800 argRef++;
1801 }
1802 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1803}
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +00001804
Steve Naroff44e81222008-04-14 22:03:09 +00001805bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001806
Ted Kremenek42730c52008-01-07 19:49:32 +00001807 if (T->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001808 return true;
1809
Steve Naroffc8a92d12007-11-01 13:24:47 +00001810 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff05d6ff52007-10-31 04:38:33 +00001811 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremenek42730c52008-01-07 19:49:32 +00001812 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff05d6ff52007-10-31 04:38:33 +00001813 return true; // we have "Class <Protocol> *".
1814 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001815 return false;
1816}
1817
Steve Naroffd06c88d2008-07-29 18:15:38 +00001818void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1819 QualType Type = E->getType();
1820 if (needToScanForQualifiers(Type)) {
Steve Narofff31ece92008-11-19 21:15:47 +00001821 SourceLocation Loc, EndLoc;
1822
1823 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
1824 Loc = ECE->getLParenLoc();
1825 EndLoc = ECE->getRParenLoc();
1826 } else {
1827 Loc = E->getLocStart();
1828 EndLoc = E->getLocEnd();
1829 }
1830 // This will defend against trying to rewrite synthesized expressions.
1831 if (Loc.isInvalid() || EndLoc.isInvalid())
1832 return;
1833
Steve Naroffd06c88d2008-07-29 18:15:38 +00001834 const char *startBuf = SM->getCharacterData(Loc);
Steve Narofff31ece92008-11-19 21:15:47 +00001835 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroffd06c88d2008-07-29 18:15:38 +00001836 const char *startRef = 0, *endRef = 0;
1837 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1838 // Get the locations of the startRef, endRef.
1839 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1840 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1841 // Comment out the protocol references.
1842 InsertText(LessLoc, "/*", 2);
1843 InsertText(GreaterLoc, "*/", 2);
1844 }
1845 }
1846}
1847
Steve Naroff44e81222008-04-14 22:03:09 +00001848void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001849 SourceLocation Loc;
1850 QualType Type;
Douglas Gregor4fa58902009-02-26 23:50:07 +00001851 const FunctionProtoType *proto = 0;
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001852 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1853 Loc = VD->getLocation();
1854 Type = VD->getType();
1855 }
1856 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1857 Loc = FD->getLocation();
1858 // Check for ObjC 'id' and class types that have been adorned with protocol
1859 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1860 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1861 assert(funcType && "missing function type");
Douglas Gregor4fa58902009-02-26 23:50:07 +00001862 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001863 if (!proto)
1864 return;
1865 Type = proto->getResultType();
1866 }
1867 else
1868 return;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001869
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001870 if (needToScanForQualifiers(Type)) {
Steve Naroffc8a92d12007-11-01 13:24:47 +00001871 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001872
1873 const char *endBuf = SM->getCharacterData(Loc);
1874 const char *startBuf = endBuf;
Steve Naroffff2fa192008-05-31 05:02:17 +00001875 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffc8a92d12007-11-01 13:24:47 +00001876 startBuf--; // scan backward (from the decl location) for return type.
1877 const char *startRef = 0, *endRef = 0;
1878 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1879 // Get the locations of the startRef, endRef.
1880 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1881 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1882 // Comment out the protocol references.
Chris Lattner6216f292008-01-31 19:42:41 +00001883 InsertText(LessLoc, "/*", 2);
1884 InsertText(GreaterLoc, "*/", 2);
Steve Naroff05d6ff52007-10-31 04:38:33 +00001885 }
1886 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001887 if (!proto)
1888 return; // most likely, was a variable
Steve Naroffc8a92d12007-11-01 13:24:47 +00001889 // Now check arguments.
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001890 const char *startBuf = SM->getCharacterData(Loc);
1891 const char *startFuncBuf = startBuf;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001892 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1893 if (needToScanForQualifiers(proto->getArgType(i))) {
1894 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001895
Steve Naroffc8a92d12007-11-01 13:24:47 +00001896 const char *endBuf = startBuf;
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001897 // scan forward (from the decl location) for argument types.
1898 scanToNextArgument(endBuf);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001899 const char *startRef = 0, *endRef = 0;
1900 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1901 // Get the locations of the startRef, endRef.
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +00001902 SourceLocation LessLoc =
1903 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1904 SourceLocation GreaterLoc =
1905 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001906 // Comment out the protocol references.
Chris Lattner6216f292008-01-31 19:42:41 +00001907 InsertText(LessLoc, "/*", 2);
1908 InsertText(GreaterLoc, "*/", 2);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001909 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001910 startBuf = ++endBuf;
1911 }
1912 else {
Steve Naroff6a1d88b2008-08-06 15:58:23 +00001913 // If the function name is derived from a macro expansion, then the
1914 // argument buffer will not follow the name. Need to speak with Chris.
1915 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001916 startBuf++; // scan forward (from the decl location) for argument types.
1917 startBuf++;
1918 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001919 }
Steve Naroff05d6ff52007-10-31 04:38:33 +00001920}
1921
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001922// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroff44e81222008-04-14 22:03:09 +00001923void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001924 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1925 llvm::SmallVector<QualType, 16> ArgTys;
1926 ArgTys.push_back(Context->getPointerType(
1927 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001928 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001929 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00001930 false /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001931 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001932 SourceLocation(),
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001933 SelGetUidIdent, getFuncType,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001934 FunctionDecl::Extern, false);
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001935}
1936
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001937// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
Steve Naroff44e81222008-04-14 22:03:09 +00001938void RewriteObjC::SynthGetProtocolFunctionDecl() {
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001939 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1940 llvm::SmallVector<QualType, 16> ArgTys;
1941 ArgTys.push_back(Context->getPointerType(
1942 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001943 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001944 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00001945 false /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001946 GetProtocolFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001947 SourceLocation(),
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001948 SelGetProtoIdent, getFuncType,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001949 FunctionDecl::Extern, false);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001950}
1951
Steve Naroff44e81222008-04-14 22:03:09 +00001952void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001953 // declared in <objc/objc.h>
Douglas Gregor7339c9e2009-01-09 01:47:02 +00001954 if (FD->getIdentifier() &&
1955 strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001956 SelGetUidFunctionDecl = FD;
Steve Naroff05d6ff52007-10-31 04:38:33 +00001957 return;
1958 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001959 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff02a82aa2007-10-30 23:14:51 +00001960}
1961
Steve Naroffbec4bf52008-03-11 17:37:02 +00001962// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroff44e81222008-04-14 22:03:09 +00001963void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffbec4bf52008-03-11 17:37:02 +00001964 if (SuperContructorFunctionDecl)
1965 return;
Steve Naroff12673622008-12-23 20:11:22 +00001966 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroffbec4bf52008-03-11 17:37:02 +00001967 llvm::SmallVector<QualType, 16> ArgTys;
1968 QualType argT = Context->getObjCIdType();
1969 assert(!argT.isNull() && "Can't find 'id' type");
1970 ArgTys.push_back(argT);
1971 ArgTys.push_back(argT);
1972 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1973 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00001974 false, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001975 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001976 SourceLocation(),
Steve Naroffbec4bf52008-03-11 17:37:02 +00001977 msgSendIdent, msgSendType,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001978 FunctionDecl::Extern, false);
Steve Naroffbec4bf52008-03-11 17:37:02 +00001979}
1980
Steve Naroff02a82aa2007-10-30 23:14:51 +00001981// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00001982void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001983 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1984 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001985 QualType argT = Context->getObjCIdType();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001986 assert(!argT.isNull() && "Can't find 'id' type");
1987 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001988 argT = Context->getObjCSelType();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001989 assert(!argT.isNull() && "Can't find 'SEL' type");
1990 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001991 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001992 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00001993 true /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001994 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001995 SourceLocation(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001996 msgSendIdent, msgSendType,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001997 FunctionDecl::Extern, false);
Steve Naroff02a82aa2007-10-30 23:14:51 +00001998}
1999
Steve Naroff764c1ae2007-11-15 10:28:18 +00002000// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00002001void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff764c1ae2007-11-15 10:28:18 +00002002 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2003 llvm::SmallVector<QualType, 16> ArgTys;
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002004 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00002005 SourceLocation(),
Ted Kremenek2c984042008-09-05 01:34:33 +00002006 &Context->Idents.get("objc_super"));
Steve Naroff764c1ae2007-11-15 10:28:18 +00002007 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2008 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2009 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00002010 argT = Context->getObjCSelType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00002011 assert(!argT.isNull() && "Can't find 'SEL' type");
2012 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00002013 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00002014 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002015 true /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00002016 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00002017 SourceLocation(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00002018 msgSendIdent, msgSendType,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002019 FunctionDecl::Extern, false);
Steve Naroff764c1ae2007-11-15 10:28:18 +00002020}
2021
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002022// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00002023void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002024 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2025 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00002026 QualType argT = Context->getObjCIdType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002027 assert(!argT.isNull() && "Can't find 'id' type");
2028 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00002029 argT = Context->getObjCSelType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002030 assert(!argT.isNull() && "Can't find 'SEL' type");
2031 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00002032 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002033 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002034 true /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00002035 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00002036 SourceLocation(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002037 msgSendIdent, msgSendType,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002038 FunctionDecl::Extern, false);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002039}
2040
2041// SynthMsgSendSuperStretFunctionDecl -
2042// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00002043void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002044 IdentifierInfo *msgSendIdent =
2045 &Context->Idents.get("objc_msgSendSuper_stret");
2046 llvm::SmallVector<QualType, 16> ArgTys;
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002047 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00002048 SourceLocation(),
Ted Kremenek2c984042008-09-05 01:34:33 +00002049 &Context->Idents.get("objc_super"));
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002050 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2051 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2052 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00002053 argT = Context->getObjCSelType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002054 assert(!argT.isNull() && "Can't find 'SEL' type");
2055 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00002056 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002057 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002058 true /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00002059 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner4c7802b2008-03-15 21:24:04 +00002060 SourceLocation(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002061 msgSendIdent, msgSendType,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002062 FunctionDecl::Extern, false);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002063}
2064
Steve Naroff31316a12008-05-08 22:02:18 +00002065// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00002066void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002067 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2068 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00002069 QualType argT = Context->getObjCIdType();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002070 assert(!argT.isNull() && "Can't find 'id' type");
2071 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00002072 argT = Context->getObjCSelType();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002073 assert(!argT.isNull() && "Can't find 'SEL' type");
2074 ArgTys.push_back(argT);
Steve Naroff31316a12008-05-08 22:02:18 +00002075 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002076 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002077 true /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00002078 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00002079 SourceLocation(),
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002080 msgSendIdent, msgSendType,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002081 FunctionDecl::Extern, false);
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002082}
2083
Steve Naroff02a82aa2007-10-30 23:14:51 +00002084// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff44e81222008-04-14 22:03:09 +00002085void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff02a82aa2007-10-30 23:14:51 +00002086 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2087 llvm::SmallVector<QualType, 16> ArgTys;
2088 ArgTys.push_back(Context->getPointerType(
2089 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00002090 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00002091 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002092 false /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00002093 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00002094 SourceLocation(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00002095 getClassIdent, getClassType,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002096 FunctionDecl::Extern, false);
Steve Naroff02a82aa2007-10-30 23:14:51 +00002097}
2098
Steve Naroff3b1caac2007-12-07 03:50:46 +00002099// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff44e81222008-04-14 22:03:09 +00002100void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff3b1caac2007-12-07 03:50:46 +00002101 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2102 llvm::SmallVector<QualType, 16> ArgTys;
2103 ArgTys.push_back(Context->getPointerType(
2104 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00002105 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00002106 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002107 false /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00002108 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00002109 SourceLocation(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00002110 getClassIdent, getClassType,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002111 FunctionDecl::Extern, false);
Steve Naroff3b1caac2007-12-07 03:50:46 +00002112}
2113
Steve Naroff44e81222008-04-14 22:03:09 +00002114Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroff47e7fa22008-03-15 00:55:56 +00002115 QualType strType = getConstantStringStructType();
2116
2117 std::string S = "__NSConstantStringImpl_";
Steve Naroffa1f00992008-05-31 03:35:42 +00002118
2119 std::string tmpName = InFileName;
2120 unsigned i;
2121 for (i=0; i < tmpName.length(); i++) {
2122 char c = tmpName.at(i);
2123 // replace any non alphanumeric characters with '_'.
2124 if (!isalpha(c) && (c < '0' || c > '9'))
2125 tmpName[i] = '_';
2126 }
2127 S += tmpName;
2128 S += "_";
Steve Naroff47e7fa22008-03-15 00:55:56 +00002129 S += utostr(NumObjCStringLiterals++);
2130
Steve Narofffef037c2008-03-27 22:29:16 +00002131 Preamble += "static __NSConstantStringImpl " + S;
2132 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2133 Preamble += "0x000007c8,"; // utf8_str
Steve Naroff47e7fa22008-03-15 00:55:56 +00002134 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremenek7b6f67b2008-09-13 05:16:45 +00002135 std::string prettyBufS;
2136 llvm::raw_string_ostream prettyBuf(prettyBufS);
Steve Naroff47e7fa22008-03-15 00:55:56 +00002137 Exp->getString()->printPretty(prettyBuf);
Steve Narofffef037c2008-03-27 22:29:16 +00002138 Preamble += prettyBuf.str();
2139 Preamble += ",";
Steve Naroff64bce352008-03-15 01:36:04 +00002140 // The minus 2 removes the begin/end double quotes.
Steve Narofffef037c2008-03-27 22:29:16 +00002141 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroff47e7fa22008-03-15 00:55:56 +00002142
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00002143 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002144 &Context->Idents.get(S.c_str()), strType,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002145 VarDecl::Static);
Ted Kremenek0c97e042009-02-07 01:47:29 +00002146 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
2147 Expr *Unop = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
Steve Naroff47e7fa22008-03-15 00:55:56 +00002148 Context->getPointerType(DRE->getType()),
2149 SourceLocation());
Steve Naroffabb96362007-11-08 14:30:50 +00002150 // cast to NSConstantString *
Ted Kremenek0c97e042009-02-07 01:47:29 +00002151 CastExpr *cast = new (Context) CStyleCastExpr(Exp->getType(), Unop,
Steve Naroff7f1412d2008-11-03 23:29:32 +00002152 Exp->getType(), SourceLocation(), SourceLocation());
Chris Lattnerb1548372008-01-31 19:37:57 +00002153 ReplaceStmt(Exp, cast);
Steve Naroff102c3f22008-12-04 23:50:32 +00002154 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffabb96362007-11-08 14:30:50 +00002155 return cast;
Steve Naroff0add5d22007-11-03 11:27:19 +00002156}
2157
Steve Naroff44e81222008-04-14 22:03:09 +00002158ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff3b1caac2007-12-07 03:50:46 +00002159 // check if we are sending a message to 'super'
Douglas Gregor5d764842009-01-09 17:18:27 +00002160 if (!CurMethodDef || !CurMethodDef->isInstanceMethod()) return 0;
Chris Lattnere4650482008-03-15 06:12:44 +00002161
Douglas Gregord8606632008-11-04 14:56:14 +00002162 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
2163 const PointerType *PT = Super->getType()->getAsPointerType();
Chris Lattner4423d372008-06-21 18:04:54 +00002164 assert(PT);
2165 ObjCInterfaceType *IT = cast<ObjCInterfaceType>(PT->getPointeeType());
2166 return IT->getDecl();
2167 }
2168 return 0;
Steve Naroff764c1ae2007-11-15 10:28:18 +00002169}
2170
2171// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroff44e81222008-04-14 22:03:09 +00002172QualType RewriteObjC::getSuperStructType() {
Steve Naroff764c1ae2007-11-15 10:28:18 +00002173 if (!SuperStructDecl) {
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002174 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner58114f02008-03-15 21:32:50 +00002175 SourceLocation(),
Ted Kremenek2c984042008-09-05 01:34:33 +00002176 &Context->Idents.get("objc_super"));
Steve Naroff764c1ae2007-11-15 10:28:18 +00002177 QualType FieldTypes[2];
2178
2179 // struct objc_object *receiver;
Ted Kremenek42730c52008-01-07 19:49:32 +00002180 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00002181 // struct objc_class *super;
Ted Kremenek42730c52008-01-07 19:49:32 +00002182 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor8acb7272008-12-11 16:49:14 +00002183
Steve Naroff764c1ae2007-11-15 10:28:18 +00002184 // Create fields
Douglas Gregor8acb7272008-12-11 16:49:14 +00002185 for (unsigned i = 0; i < 2; ++i) {
Douglas Gregor03b2ad22009-01-12 23:27:07 +00002186 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
Douglas Gregor8acb7272008-12-11 16:49:14 +00002187 SourceLocation(), 0,
2188 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002189 /*Mutable=*/false));
Douglas Gregor8acb7272008-12-11 16:49:14 +00002190 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00002191
Douglas Gregor8acb7272008-12-11 16:49:14 +00002192 SuperStructDecl->completeDefinition(*Context);
Steve Naroff764c1ae2007-11-15 10:28:18 +00002193 }
2194 return Context->getTagDeclType(SuperStructDecl);
2195}
2196
Steve Naroff44e81222008-04-14 22:03:09 +00002197QualType RewriteObjC::getConstantStringStructType() {
Steve Naroff47e7fa22008-03-15 00:55:56 +00002198 if (!ConstantStringDecl) {
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002199 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner58114f02008-03-15 21:32:50 +00002200 SourceLocation(),
Ted Kremenek2c984042008-09-05 01:34:33 +00002201 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroff47e7fa22008-03-15 00:55:56 +00002202 QualType FieldTypes[4];
2203
2204 // struct objc_object *receiver;
2205 FieldTypes[0] = Context->getObjCIdType();
2206 // int flags;
2207 FieldTypes[1] = Context->IntTy;
2208 // char *str;
2209 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2210 // long length;
2211 FieldTypes[3] = Context->LongTy;
Douglas Gregor8acb7272008-12-11 16:49:14 +00002212
Steve Naroff47e7fa22008-03-15 00:55:56 +00002213 // Create fields
Douglas Gregor8acb7272008-12-11 16:49:14 +00002214 for (unsigned i = 0; i < 4; ++i) {
Douglas Gregor03b2ad22009-01-12 23:27:07 +00002215 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
Douglas Gregor8acb7272008-12-11 16:49:14 +00002216 ConstantStringDecl,
2217 SourceLocation(), 0,
2218 FieldTypes[i],
2219 /*BitWidth=*/0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002220 /*Mutable=*/true));
Douglas Gregor8acb7272008-12-11 16:49:14 +00002221 }
2222
2223 ConstantStringDecl->completeDefinition(*Context);
Steve Naroff47e7fa22008-03-15 00:55:56 +00002224 }
2225 return Context->getTagDeclType(ConstantStringDecl);
2226}
2227
Steve Naroff44e81222008-04-14 22:03:09 +00002228Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00002229 if (!SelGetUidFunctionDecl)
2230 SynthSelGetUidFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00002231 if (!MsgSendFunctionDecl)
2232 SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +00002233 if (!MsgSendSuperFunctionDecl)
2234 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002235 if (!MsgSendStretFunctionDecl)
2236 SynthMsgSendStretFunctionDecl();
2237 if (!MsgSendSuperStretFunctionDecl)
2238 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002239 if (!MsgSendFpretFunctionDecl)
2240 SynthMsgSendFpretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00002241 if (!GetClassFunctionDecl)
2242 SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +00002243 if (!GetMetaClassFunctionDecl)
2244 SynthGetMetaClassFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002245
Steve Naroff764c1ae2007-11-15 10:28:18 +00002246 // default to objc_msgSend().
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002247 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2248 // May need to use objc_msgSend_stret() as well.
2249 FunctionDecl *MsgSendStretFlavor = 0;
Chris Lattner5c6b2c62009-02-20 18:43:26 +00002250 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
2251 QualType resultType = OMD->getResultType();
Chris Lattnerb724ab22008-07-26 22:36:27 +00002252 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002253 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattnerb724ab22008-07-26 22:36:27 +00002254 else if (resultType->isRealFloatingType())
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002255 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002256 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00002257
Steve Naroff71226032007-10-24 22:48:43 +00002258 // Synthesize a call to objc_msgSend().
2259 llvm::SmallVector<Expr*, 8> MsgExprs;
2260 IdentifierInfo *clsName = Exp->getClassName();
2261
2262 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2263 if (clsName) { // class message.
Steve Naroff91a69202008-07-24 19:44:33 +00002264 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2265 // the 'super' idiom within a class method.
Steve Naroff3b1caac2007-12-07 03:50:46 +00002266 if (!strcmp(clsName->getName(), "super")) {
2267 MsgSendFlavor = MsgSendSuperFunctionDecl;
2268 if (MsgSendStretFlavor)
2269 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2270 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2271
Ted Kremenek42730c52008-01-07 19:49:32 +00002272 ObjCInterfaceDecl *SuperDecl =
Steve Naroff38a9e3f2008-10-27 17:20:55 +00002273 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroff3b1caac2007-12-07 03:50:46 +00002274
2275 llvm::SmallVector<Expr*, 4> InitExprs;
2276
2277 // set the receiver to self, the first argument to all methods.
Ted Kremenek0c97e042009-02-07 01:47:29 +00002278 InitExprs.push_back(new (Context) DeclRefExpr(
Steve Naroff38a9e3f2008-10-27 17:20:55 +00002279 CurMethodDef->getSelfDecl(),
Chris Lattner8c7c6a12008-06-17 18:05:57 +00002280 Context->getObjCIdType(),
2281 SourceLocation()));
Steve Naroff3b1caac2007-12-07 03:50:46 +00002282 llvm::SmallVector<Expr*, 8> ClsExprs;
2283 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattneraa491192009-02-18 06:40:38 +00002284 ClsExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek4f530a92009-02-06 19:55:15 +00002285 SuperDecl->getIdentifier()->getName(),
2286 SuperDecl->getIdentifier()->getLength(),
Chris Lattnerc3144742009-02-18 05:49:11 +00002287 false, argType, SourceLocation()));
Steve Naroff3b1caac2007-12-07 03:50:46 +00002288 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2289 &ClsExprs[0],
2290 ClsExprs.size());
2291 // To turn off a warning, type-cast to 'id'
Douglas Gregor21a04f32008-10-27 19:41:14 +00002292 InitExprs.push_back( // set 'super class', using objc_getClass().
Ted Kremenek0c97e042009-02-07 01:47:29 +00002293 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor21a04f32008-10-27 19:41:14 +00002294 Cls, Context->getObjCIdType(),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002295 SourceLocation(), SourceLocation()));
Steve Naroff3b1caac2007-12-07 03:50:46 +00002296 // struct objc_super
2297 QualType superType = getSuperStructType();
Steve Naroffdee066b2008-03-11 18:14:26 +00002298 Expr *SuperRep;
Steve Naroffbec4bf52008-03-11 17:37:02 +00002299
Steve Naroffdee066b2008-03-11 18:14:26 +00002300 if (LangOpts.Microsoft) {
2301 SynthSuperContructorFunctionDecl();
2302 // Simulate a contructor call...
Ted Kremenek0c97e042009-02-07 01:47:29 +00002303 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroffdee066b2008-03-11 18:14:26 +00002304 superType, SourceLocation());
Ted Kremenek362abcd2009-02-09 20:51:47 +00002305 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2306 InitExprs.size(),
2307 superType, SourceLocation());
Steve Naroff12673622008-12-23 20:11:22 +00002308 // The code for super is a little tricky to prevent collision with
2309 // the structure definition in the header. The rewriter has it's own
2310 // internal definition (__rw_objc_super) that is uses. This is why
2311 // we need the cast below. For example:
2312 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2313 //
Ted Kremenek0c97e042009-02-07 01:47:29 +00002314 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Steve Naroff12673622008-12-23 20:11:22 +00002315 Context->getPointerType(SuperRep->getType()),
2316 SourceLocation());
Ted Kremenek0c97e042009-02-07 01:47:29 +00002317 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
Steve Naroff12673622008-12-23 20:11:22 +00002318 SuperRep, Context->getPointerType(superType),
2319 SourceLocation(), SourceLocation());
Steve Naroffdee066b2008-03-11 18:14:26 +00002320 } else {
2321 // (struct objc_super) { <exprs from above> }
Ted Kremenek0c97e042009-02-07 01:47:29 +00002322 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
Steve Naroffdee066b2008-03-11 18:14:26 +00002323 &InitExprs[0], InitExprs.size(),
Douglas Gregorf603b472009-01-28 21:54:33 +00002324 SourceLocation());
Ted Kremenek0c97e042009-02-07 01:47:29 +00002325 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE,
Chris Lattner71ca8c82008-10-26 23:43:26 +00002326 false);
Steve Naroff12673622008-12-23 20:11:22 +00002327 // struct objc_super *
Ted Kremenek0c97e042009-02-07 01:47:29 +00002328 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Steve Naroff12673622008-12-23 20:11:22 +00002329 Context->getPointerType(SuperRep->getType()),
2330 SourceLocation());
Steve Naroffdee066b2008-03-11 18:14:26 +00002331 }
Steve Naroff12673622008-12-23 20:11:22 +00002332 MsgExprs.push_back(SuperRep);
Steve Naroff3b1caac2007-12-07 03:50:46 +00002333 } else {
2334 llvm::SmallVector<Expr*, 8> ClsExprs;
2335 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattneraa491192009-02-18 06:40:38 +00002336 ClsExprs.push_back(StringLiteral::Create(*Context,
2337 clsName->getName(),
2338 clsName->getLength(),
2339 false, argType,
2340 SourceLocation()));
Steve Naroff3b1caac2007-12-07 03:50:46 +00002341 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2342 &ClsExprs[0],
2343 ClsExprs.size());
2344 MsgExprs.push_back(Cls);
2345 }
Steve Naroff885e2122007-11-14 23:54:14 +00002346 } else { // instance message.
2347 Expr *recExpr = Exp->getReceiver();
Steve Naroff764c1ae2007-11-15 10:28:18 +00002348
Ted Kremenek42730c52008-01-07 19:49:32 +00002349 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff764c1ae2007-11-15 10:28:18 +00002350 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002351 if (MsgSendStretFlavor)
2352 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +00002353 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2354
2355 llvm::SmallVector<Expr*, 4> InitExprs;
2356
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00002357 InitExprs.push_back(
Ted Kremenek0c97e042009-02-07 01:47:29 +00002358 new (Context) CStyleCastExpr(Context->getObjCIdType(),
2359 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroff23528612008-07-16 22:35:27 +00002360 Context->getObjCIdType(),
Douglas Gregor21a04f32008-10-27 19:41:14 +00002361 SourceLocation()),
2362 Context->getObjCIdType(),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002363 SourceLocation(), SourceLocation())); // set the 'receiver'.
Steve Naroff764c1ae2007-11-15 10:28:18 +00002364
2365 llvm::SmallVector<Expr*, 8> ClsExprs;
2366 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattneraa491192009-02-18 06:40:38 +00002367 ClsExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek4f530a92009-02-06 19:55:15 +00002368 SuperDecl->getIdentifier()->getName(),
2369 SuperDecl->getIdentifier()->getLength(),
Chris Lattnerc3144742009-02-18 05:49:11 +00002370 false, argType, SourceLocation()));
Steve Naroff764c1ae2007-11-15 10:28:18 +00002371 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00002372 &ClsExprs[0],
2373 ClsExprs.size());
Fariborz Jahanianfabf3bf2007-12-05 17:29:46 +00002374 // To turn off a warning, type-cast to 'id'
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00002375 InitExprs.push_back(
Douglas Gregor21a04f32008-10-27 19:41:14 +00002376 // set 'super class', using objc_getClass().
Ted Kremenek0c97e042009-02-07 01:47:29 +00002377 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002378 Cls, Context->getObjCIdType(), SourceLocation(), SourceLocation()));
Steve Naroff764c1ae2007-11-15 10:28:18 +00002379 // struct objc_super
2380 QualType superType = getSuperStructType();
Steve Naroffbec4bf52008-03-11 17:37:02 +00002381 Expr *SuperRep;
2382
2383 if (LangOpts.Microsoft) {
2384 SynthSuperContructorFunctionDecl();
2385 // Simulate a contructor call...
Ted Kremenek0c97e042009-02-07 01:47:29 +00002386 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroffbec4bf52008-03-11 17:37:02 +00002387 superType, SourceLocation());
Ted Kremenek362abcd2009-02-09 20:51:47 +00002388 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2389 InitExprs.size(),
2390 superType, SourceLocation());
Steve Naroff12673622008-12-23 20:11:22 +00002391 // The code for super is a little tricky to prevent collision with
2392 // the structure definition in the header. The rewriter has it's own
2393 // internal definition (__rw_objc_super) that is uses. This is why
2394 // we need the cast below. For example:
2395 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2396 //
Ted Kremenek0c97e042009-02-07 01:47:29 +00002397 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Steve Naroff12673622008-12-23 20:11:22 +00002398 Context->getPointerType(SuperRep->getType()),
2399 SourceLocation());
Ted Kremenek0c97e042009-02-07 01:47:29 +00002400 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
Steve Naroff12673622008-12-23 20:11:22 +00002401 SuperRep, Context->getPointerType(superType),
2402 SourceLocation(), SourceLocation());
Steve Naroffbec4bf52008-03-11 17:37:02 +00002403 } else {
2404 // (struct objc_super) { <exprs from above> }
Ted Kremenek0c97e042009-02-07 01:47:29 +00002405 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
Steve Naroffbec4bf52008-03-11 17:37:02 +00002406 &InitExprs[0], InitExprs.size(),
Douglas Gregorf603b472009-01-28 21:54:33 +00002407 SourceLocation());
Ted Kremenek0c97e042009-02-07 01:47:29 +00002408 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
Steve Naroffbec4bf52008-03-11 17:37:02 +00002409 }
Steve Naroff12673622008-12-23 20:11:22 +00002410 MsgExprs.push_back(SuperRep);
Steve Naroff764c1ae2007-11-15 10:28:18 +00002411 } else {
Fariborz Jahanianbe4283c2007-12-07 21:21:21 +00002412 // Remove all type-casts because it may contain objc-style types; e.g.
2413 // Foo<Proto> *.
Douglas Gregor035d0882008-10-28 15:36:24 +00002414 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanianbe4283c2007-12-07 21:21:21 +00002415 recExpr = CE->getSubExpr();
Ted Kremenek0c97e042009-02-07 01:47:29 +00002416 recExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(), recExpr,
Douglas Gregor21a04f32008-10-27 19:41:14 +00002417 Context->getObjCIdType(),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002418 SourceLocation(), SourceLocation());
Steve Naroff764c1ae2007-11-15 10:28:18 +00002419 MsgExprs.push_back(recExpr);
2420 }
Steve Naroff885e2122007-11-14 23:54:14 +00002421 }
Steve Naroff0add5d22007-11-03 11:27:19 +00002422 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff71226032007-10-24 22:48:43 +00002423 llvm::SmallVector<Expr*, 8> SelExprs;
2424 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattneraa491192009-02-18 06:40:38 +00002425 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek4f530a92009-02-06 19:55:15 +00002426 Exp->getSelector().getAsString().c_str(),
Chris Lattner3a8f2942008-11-24 03:33:13 +00002427 Exp->getSelector().getAsString().size(),
Chris Lattnerc3144742009-02-18 05:49:11 +00002428 false, argType, SourceLocation()));
Steve Naroff71226032007-10-24 22:48:43 +00002429 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2430 &SelExprs[0], SelExprs.size());
2431 MsgExprs.push_back(SelExp);
2432
2433 // Now push any user supplied arguments.
2434 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff885e2122007-11-14 23:54:14 +00002435 Expr *userExpr = Exp->getArg(i);
Steve Naroff6b759ce2007-11-15 02:58:25 +00002436 // Make all implicit casts explicit...ICE comes in handy:-)
2437 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2438 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregor21a04f32008-10-27 19:41:14 +00002439 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremenek42730c52008-01-07 19:49:32 +00002440 ? Context->getObjCIdType()
Douglas Gregor21a04f32008-10-27 19:41:14 +00002441 : ICE->getType();
Ted Kremenek0c97e042009-02-07 01:47:29 +00002442 userExpr = new (Context) CStyleCastExpr(type, userExpr, type, SourceLocation(), SourceLocation());
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002443 }
2444 // Make id<P...> cast into an 'id' cast.
Douglas Gregor035d0882008-10-28 15:36:24 +00002445 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002446 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor035d0882008-10-28 15:36:24 +00002447 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002448 userExpr = CE->getSubExpr();
Ted Kremenek0c97e042009-02-07 01:47:29 +00002449 userExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor21a04f32008-10-27 19:41:14 +00002450 userExpr, Context->getObjCIdType(),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002451 SourceLocation(), SourceLocation());
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002452 }
Steve Naroff6b759ce2007-11-15 02:58:25 +00002453 }
Steve Naroff885e2122007-11-14 23:54:14 +00002454 MsgExprs.push_back(userExpr);
Steve Naroff71226032007-10-24 22:48:43 +00002455 // We've transferred the ownership to MsgExprs. Null out the argument in
2456 // the original expression, since we will delete it below.
2457 Exp->setArg(i, 0);
2458 }
Steve Naroff0744c472007-11-04 22:37:50 +00002459 // Generate the funky cast.
2460 CastExpr *cast;
2461 llvm::SmallVector<QualType, 8> ArgTypes;
2462 QualType returnType;
2463
2464 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff0c04bb62007-11-15 10:43:57 +00002465 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2466 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2467 else
Ted Kremenek42730c52008-01-07 19:49:32 +00002468 ArgTypes.push_back(Context->getObjCIdType());
2469 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner5c6b2c62009-02-20 18:43:26 +00002470 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroff0744c472007-11-04 22:37:50 +00002471 // Push any user argument types.
Chris Lattner5c6b2c62009-02-20 18:43:26 +00002472 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2473 E = OMD->param_end(); PI != E; ++PI) {
2474 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Ted Kremenek42730c52008-01-07 19:49:32 +00002475 ? Context->getObjCIdType()
Chris Lattner5c6b2c62009-02-20 18:43:26 +00002476 : (*PI)->getType();
Steve Naroff66c842f2008-10-29 14:49:46 +00002477 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffd896f4b2008-12-11 21:05:33 +00002478 if (isTopLevelBlockPointerType(t)) {
Steve Naroff66c842f2008-10-29 14:49:46 +00002479 const BlockPointerType *BPT = t->getAsBlockPointerType();
2480 t = Context->getPointerType(BPT->getPointeeType());
2481 }
Steve Naroff4242b972007-11-05 14:36:37 +00002482 ArgTypes.push_back(t);
2483 }
Chris Lattner5c6b2c62009-02-20 18:43:26 +00002484 returnType = OMD->getResultType()->isObjCQualifiedIdType()
2485 ? Context->getObjCIdType() : OMD->getResultType();
Steve Naroff0744c472007-11-04 22:37:50 +00002486 } else {
Ted Kremenek42730c52008-01-07 19:49:32 +00002487 returnType = Context->getObjCIdType();
Steve Naroff0744c472007-11-04 22:37:50 +00002488 }
2489 // Get the type, we will need to reference it in a couple spots.
Steve Naroff764c1ae2007-11-15 10:28:18 +00002490 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroff0744c472007-11-04 22:37:50 +00002491
2492 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek0c97e042009-02-07 01:47:29 +00002493 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002494 SourceLocation());
Steve Naroff0744c472007-11-04 22:37:50 +00002495
2496 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2497 // If we don't do this cast, we get the following bizarre warning/note:
2498 // xx.m:13: warning: function called through a non-compatible type
2499 // xx.m:13: note: if this code is reached, the program will abort
Ted Kremenek0c97e042009-02-07 01:47:29 +00002500 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy), DRE,
Douglas Gregor21a04f32008-10-27 19:41:14 +00002501 Context->getPointerType(Context->VoidTy),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002502 SourceLocation(), SourceLocation());
Steve Naroff29fe7462007-11-15 12:35:21 +00002503
Steve Naroff0744c472007-11-04 22:37:50 +00002504 // Now do the "normal" pointer to function cast.
2505 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00002506 &ArgTypes[0], ArgTypes.size(),
Steve Naroff3b8b4e32008-03-18 02:02:04 +00002507 // If we don't have a method decl, force a variadic cast.
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002508 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Naroff0744c472007-11-04 22:37:50 +00002509 castType = Context->getPointerType(castType);
Ted Kremenek0c97e042009-02-07 01:47:29 +00002510 cast = new (Context) CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Steve Naroff0744c472007-11-04 22:37:50 +00002511
2512 // Don't forget the parens to enforce the proper binding.
Ted Kremenek0c97e042009-02-07 01:47:29 +00002513 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Steve Naroff0744c472007-11-04 22:37:50 +00002514
2515 const FunctionType *FT = msgSendType->getAsFunctionType();
Ted Kremenek362abcd2009-02-09 20:51:47 +00002516 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2517 MsgExprs.size(),
2518 FT->getResultType(), SourceLocation());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002519 Stmt *ReplacingStmt = CE;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002520 if (MsgSendStretFlavor) {
2521 // We have the method which returns a struct/union. Must also generate
2522 // call to objc_msgSend_stret and hang both varieties on a conditional
2523 // expression which dictate which one to envoke depending on size of
2524 // method's return type.
2525
2526 // Create a reference to the objc_msgSend_stret() declaration.
Ted Kremenek0c97e042009-02-07 01:47:29 +00002527 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002528 SourceLocation());
2529 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Ted Kremenek0c97e042009-02-07 01:47:29 +00002530 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy), STDRE,
Douglas Gregor21a04f32008-10-27 19:41:14 +00002531 Context->getPointerType(Context->VoidTy),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002532 SourceLocation(), SourceLocation());
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002533 // Now do the "normal" pointer to function cast.
2534 castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00002535 &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002536 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002537 castType = Context->getPointerType(castType);
Ted Kremenek0c97e042009-02-07 01:47:29 +00002538 cast = new (Context) CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002539
2540 // Don't forget the parens to enforce the proper binding.
Ted Kremenek0c97e042009-02-07 01:47:29 +00002541 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002542
2543 FT = msgSendType->getAsFunctionType();
Ted Kremenek362abcd2009-02-09 20:51:47 +00002544 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2545 MsgExprs.size(),
2546 FT->getResultType(), SourceLocation());
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002547
2548 // Build sizeof(returnType)
Douglas Gregor396f1142009-03-13 21:01:28 +00002549 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
2550 returnType,
Sebastian Redl0cb7c872008-11-11 17:56:53 +00002551 Context->getSizeType(),
2552 SourceLocation(), SourceLocation());
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002553 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2554 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2555 // For X86 it is more complicated and some kind of target specific routine
2556 // is needed to decide what to do.
Chris Lattner8cd0e932008-03-05 18:54:05 +00002557 unsigned IntSize =
2558 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Ted Kremenek0c97e042009-02-07 01:47:29 +00002559 IntegerLiteral *limit = new (Context) IntegerLiteral(llvm::APInt(IntSize, 8),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002560 Context->IntTy,
2561 SourceLocation());
Ted Kremenek0c97e042009-02-07 01:47:29 +00002562 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002563 BinaryOperator::LE,
2564 Context->IntTy,
2565 SourceLocation());
2566 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2567 ConditionalOperator *CondExpr =
Ted Kremenek0c97e042009-02-07 01:47:29 +00002568 new (Context) ConditionalOperator(lessThanExpr, CE, STCE, returnType);
2569 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002570 }
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002571 return ReplacingStmt;
2572}
2573
Steve Naroff44e81222008-04-14 22:03:09 +00002574Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002575 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroffe8efe892008-10-27 20:54:44 +00002576
Steve Naroff0e948412008-12-04 16:24:46 +00002577 //ReplacingStmt->dump();
Steve Naroff71226032007-10-24 22:48:43 +00002578 // Now do the actual rewrite.
Chris Lattnerb1548372008-01-31 19:37:57 +00002579 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff71226032007-10-24 22:48:43 +00002580
Steve Naroff102c3f22008-12-04 23:50:32 +00002581 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002582 return ReplacingStmt;
Steve Naroffe9780582007-10-23 23:50:29 +00002583}
2584
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002585/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2586/// call to objc_getProtocol("proto-name").
Steve Naroff44e81222008-04-14 22:03:09 +00002587Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002588 if (!GetProtocolFunctionDecl)
2589 SynthGetProtocolFunctionDecl();
2590 // Create a call to objc_getProtocol("ProtocolName").
2591 llvm::SmallVector<Expr*, 8> ProtoExprs;
2592 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattneraa491192009-02-18 06:40:38 +00002593 ProtoExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek4f530a92009-02-06 19:55:15 +00002594 Exp->getProtocol()->getNameAsCString(),
2595 strlen(Exp->getProtocol()->getNameAsCString()),
Chris Lattnerc3144742009-02-18 05:49:11 +00002596 false, argType, SourceLocation()));
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002597 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2598 &ProtoExprs[0],
2599 ProtoExprs.size());
Chris Lattnerb1548372008-01-31 19:37:57 +00002600 ReplaceStmt(Exp, ProtoExp);
Steve Naroff102c3f22008-12-04 23:50:32 +00002601 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002602 return ProtoExp;
2603
2604}
2605
Steve Naroffef82b742008-05-31 14:15:04 +00002606bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
2607 const char *endBuf) {
2608 while (startBuf < endBuf) {
2609 if (*startBuf == '#') {
2610 // Skip whitespace.
2611 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2612 ;
2613 if (!strncmp(startBuf, "if", strlen("if")) ||
2614 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2615 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2616 !strncmp(startBuf, "define", strlen("define")) ||
2617 !strncmp(startBuf, "undef", strlen("undef")) ||
2618 !strncmp(startBuf, "else", strlen("else")) ||
2619 !strncmp(startBuf, "elif", strlen("elif")) ||
2620 !strncmp(startBuf, "endif", strlen("endif")) ||
2621 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2622 !strncmp(startBuf, "include", strlen("include")) ||
2623 !strncmp(startBuf, "import", strlen("import")) ||
2624 !strncmp(startBuf, "include_next", strlen("include_next")))
2625 return true;
2626 }
2627 startBuf++;
2628 }
2629 return false;
2630}
2631
Ted Kremenek42730c52008-01-07 19:49:32 +00002632/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002633/// an objective-c class with ivars.
Steve Naroff44e81222008-04-14 22:03:09 +00002634void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002635 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002636 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Chris Lattnerd120b9e2008-11-24 03:54:41 +00002637 assert(CDecl->getNameAsCString() &&
Douglas Gregor24afd4a2008-11-17 14:58:09 +00002638 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00002639 // Do not synthesize more than once.
Ted Kremenek42730c52008-01-07 19:49:32 +00002640 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00002641 return;
Ted Kremenek42730c52008-01-07 19:49:32 +00002642 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerec4979b2008-03-16 21:08:55 +00002643 int NumIvars = CDecl->ivar_size();
Steve Naroff2c7afc92007-11-14 19:25:57 +00002644 SourceLocation LocStart = CDecl->getLocStart();
2645 SourceLocation LocEnd = CDecl->getLocEnd();
2646
2647 const char *startBuf = SM->getCharacterData(LocStart);
2648 const char *endBuf = SM->getCharacterData(LocEnd);
Steve Naroffef82b742008-05-31 14:15:04 +00002649
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002650 // If no ivars and no root or if its root, directly or indirectly,
2651 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerec4979b2008-03-16 21:08:55 +00002652 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2653 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002654 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattnerb8a1b042008-01-31 19:51:04 +00002655 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002656 return;
2657 }
2658
2659 // FIXME: This has potential of causing problem. If
Ted Kremenek42730c52008-01-07 19:49:32 +00002660 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002661 Result += "\nstruct ";
Chris Lattner271d4c22008-11-24 05:29:24 +00002662 Result += CDecl->getNameAsString();
Steve Naroffde0da102008-03-10 23:16:54 +00002663 if (LangOpts.Microsoft)
2664 Result += "_IMPL";
Steve Naroff60dfb6b2008-03-12 00:25:36 +00002665
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002666 if (NumIvars > 0) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00002667 const char *cursor = strchr(startBuf, '{');
2668 assert((cursor && endBuf)
Ted Kremenek42730c52008-01-07 19:49:32 +00002669 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffef82b742008-05-31 14:15:04 +00002670 // If the buffer contains preprocessor directives, we do more fine-grained
2671 // rewrites. This is intended to fix code that looks like (which occurs in
2672 // NSURL.h, for example):
2673 //
2674 // #ifdef XYZ
2675 // @interface Foo : NSObject
2676 // #else
2677 // @interface FooBar : NSObject
2678 // #endif
2679 // {
2680 // int i;
2681 // }
2682 // @end
2683 //
2684 // This clause is segregated to avoid breaking the common case.
2685 if (BufferContainsPPDirectives(startBuf, cursor)) {
2686 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
2687 CDecl->getClassLoc();
2688 const char *endHeader = SM->getCharacterData(L);
2689 endHeader += Lexer::MeasureTokenLength(L, *SM);
2690
Chris Lattner179fd522009-02-20 18:18:36 +00002691 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffef82b742008-05-31 14:15:04 +00002692 // advance to the end of the referenced protocols.
2693 while (endHeader < cursor && *endHeader != '>') endHeader++;
2694 endHeader++;
2695 }
2696 // rewrite the original header
2697 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2698 } else {
2699 // rewrite the original header *without* disturbing the '{'
2700 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
2701 }
Ted Kremenek42730c52008-01-07 19:49:32 +00002702 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00002703 Result = "\n struct ";
Chris Lattner271d4c22008-11-24 05:29:24 +00002704 Result += RCDecl->getNameAsString();
Steve Naroffcbf88fe2008-03-12 21:09:20 +00002705 Result += "_IMPL ";
Chris Lattner271d4c22008-11-24 05:29:24 +00002706 Result += RCDecl->getNameAsString();
Steve Naroff4850dfe2008-03-12 21:22:52 +00002707 Result += "_IVARS;\n";
Steve Naroff2c7afc92007-11-14 19:25:57 +00002708
2709 // insert the super class structure definition.
Chris Lattner6216f292008-01-31 19:42:41 +00002710 SourceLocation OnePastCurly =
2711 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2712 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Naroff2c7afc92007-11-14 19:25:57 +00002713 }
2714 cursor++; // past '{'
2715
2716 // Now comment out any visibility specifiers.
2717 while (cursor < endBuf) {
2718 if (*cursor == '@') {
2719 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf04ead52007-11-14 22:57:51 +00002720 // Skip whitespace.
2721 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2722 /*scan*/;
2723
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002724 // FIXME: presence of @public, etc. inside comment results in
2725 // this transformation as well, which is still correct c-code.
Steve Naroff2c7afc92007-11-14 19:25:57 +00002726 if (!strncmp(cursor, "public", strlen("public")) ||
2727 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffa93924a2008-04-04 22:34:24 +00002728 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002729 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattner6216f292008-01-31 19:42:41 +00002730 InsertText(atLoc, "// ", 3);
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002731 }
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002732 // FIXME: If there are cases where '<' is used in ivar declaration part
2733 // of user code, then scan the ivar list and use needToScanForQualifiers
2734 // for type checking.
2735 else if (*cursor == '<') {
2736 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner6216f292008-01-31 19:42:41 +00002737 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002738 cursor = strchr(cursor, '>');
2739 cursor++;
2740 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner6216f292008-01-31 19:42:41 +00002741 InsertText(atLoc, " */", 3);
Steve Naroff6449c6c2008-10-30 12:09:33 +00002742 } else if (*cursor == '^') { // rewrite block specifier.
2743 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2744 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002745 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00002746 cursor++;
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002747 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00002748 // Don't forget to add a ';'!!
Chris Lattner6216f292008-01-31 19:42:41 +00002749 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Naroff2c7afc92007-11-14 19:25:57 +00002750 } else { // we don't have any instance variables - insert super struct.
2751 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2752 Result += " {\n struct ";
Chris Lattner271d4c22008-11-24 05:29:24 +00002753 Result += RCDecl->getNameAsString();
Steve Naroffcbf88fe2008-03-12 21:09:20 +00002754 Result += "_IMPL ";
Chris Lattner271d4c22008-11-24 05:29:24 +00002755 Result += RCDecl->getNameAsString();
Steve Naroff4850dfe2008-03-12 21:22:52 +00002756 Result += "_IVARS;\n};\n";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00002757 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002758 }
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002759 // Mark this struct as having been generated.
Ted Kremenek42730c52008-01-07 19:49:32 +00002760 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Naroff04eaa192008-05-06 18:26:51 +00002761 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002762}
2763
Ted Kremenek42730c52008-01-07 19:49:32 +00002764// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002765/// class methods.
Steve Naroff44e81222008-04-14 22:03:09 +00002766void RewriteObjC::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002767 instmeth_iterator MethodEnd,
Fariborz Jahaniana3986372007-10-25 00:14:44 +00002768 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002769 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00002770 const char *ClassName,
2771 std::string &Result) {
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002772 if (MethodBegin == MethodEnd) return;
2773
Fariborz Jahanian04455192007-10-22 21:41:37 +00002774 static bool objc_impl_method = false;
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002775 if (!objc_impl_method) {
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002776 /* struct _objc_method {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002777 SEL _cmd;
2778 char *method_types;
2779 void *_imp;
2780 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002781 */
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00002782 Result += "\nstruct _objc_method {\n";
2783 Result += "\tSEL _cmd;\n";
2784 Result += "\tchar *method_types;\n";
2785 Result += "\tvoid *_imp;\n";
2786 Result += "};\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002787
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002788 objc_impl_method = true;
Fariborz Jahanian96b55da2007-10-19 00:36:46 +00002789 }
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002790
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002791 // Build _objc_method_list for class's methods if needed
Steve Naroffc723eec2008-03-11 00:12:29 +00002792
2793 /* struct {
2794 struct _objc_method_list *next_method;
2795 int method_count;
2796 struct _objc_method method_list[];
2797 }
2798 */
2799 Result += "\nstatic struct {\n";
2800 Result += "\tstruct _objc_method_list *next_method;\n";
2801 Result += "\tint method_count;\n";
2802 Result += "\tstruct _objc_method method_list[";
2803 Result += utostr(MethodEnd-MethodBegin);
2804 Result += "];\n} _OBJC_";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002805 Result += prefix;
2806 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2807 Result += "_METHODS_";
2808 Result += ClassName;
Steve Naroff5ce4a242008-03-12 17:18:30 +00002809 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002810 Result += IsInstanceMethod ? "inst" : "cls";
2811 Result += "_meth\")))= ";
2812 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002813
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002814 Result += "\t,{{(SEL)\"";
Chris Lattner3a8f2942008-11-24 03:33:13 +00002815 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002816 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002817 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002818 Result += "\", \"";
2819 Result += MethodTypeString;
Steve Naroffc723eec2008-03-11 00:12:29 +00002820 Result += "\", (void *)";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002821 Result += MethodInternalNames[*MethodBegin];
2822 Result += "}\n";
2823 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2824 Result += "\t ,{(SEL)\"";
Chris Lattner3a8f2942008-11-24 03:33:13 +00002825 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002826 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002827 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002828 Result += "\", \"";
2829 Result += MethodTypeString;
Steve Naroffc723eec2008-03-11 00:12:29 +00002830 Result += "\", (void *)";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002831 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +00002832 Result += "}\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002833 }
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002834 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002835}
2836
Ted Kremenek42730c52008-01-07 19:49:32 +00002837/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
Chris Lattner0be08822008-07-21 21:32:27 +00002838void RewriteObjC::
2839RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
2840 const char *prefix,
2841 const char *ClassName,
2842 std::string &Result) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002843 static bool objc_protocol_methods = false;
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002844 if (Protocols.empty()) return;
2845
2846 for (unsigned i = 0; i != Protocols.size(); i++) {
2847 ObjCProtocolDecl *PDecl = Protocols[i];
2848 // Output struct protocol_methods holder of method selector and type.
2849 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
2850 /* struct protocol_methods {
2851 SEL _cmd;
2852 char *method_types;
2853 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002854 */
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002855 Result += "\nstruct protocol_methods {\n";
2856 Result += "\tSEL _cmd;\n";
2857 Result += "\tchar *method_types;\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002858 Result += "};\n";
Steve Naroff04eaa192008-05-06 18:26:51 +00002859
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002860 objc_protocol_methods = true;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002861 }
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002862 // Do not synthesize the protocol more than once.
2863 if (ObjCSynthesizedProtocols.count(PDecl))
2864 continue;
2865
2866 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Chris Lattner179fd522009-02-20 18:18:36 +00002867 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
2868 PDecl->instmeth_end());
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002869 /* struct _objc_protocol_method_list {
2870 int protocol_method_count;
2871 struct protocol_methods protocols[];
2872 }
2873 */
2874 Result += "\nstatic struct {\n";
2875 Result += "\tint protocol_method_count;\n";
2876 Result += "\tstruct protocol_methods protocols[";
2877 Result += utostr(NumMethods);
2878 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00002879 Result += PDecl->getNameAsString();
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002880 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
2881 "{\n\t" + utostr(NumMethods) + "\n";
2882
2883 // Output instance methods declared in this protocol.
2884 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
2885 E = PDecl->instmeth_end(); I != E; ++I) {
2886 if (I == PDecl->instmeth_begin())
2887 Result += "\t ,{{(SEL)\"";
2888 else
2889 Result += "\t ,{(SEL)\"";
Chris Lattner3a8f2942008-11-24 03:33:13 +00002890 Result += (*I)->getSelector().getAsString().c_str();
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002891 std::string MethodTypeString;
2892 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2893 Result += "\", \"";
2894 Result += MethodTypeString;
2895 Result += "\"}\n";
2896 }
2897 Result += "\t }\n};\n";
2898 }
2899
2900 // Output class methods declared in this protocol.
Chris Lattner179fd522009-02-20 18:18:36 +00002901 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
2902 PDecl->classmeth_end());
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002903 if (NumMethods > 0) {
2904 /* struct _objc_protocol_method_list {
2905 int protocol_method_count;
2906 struct protocol_methods protocols[];
2907 }
2908 */
2909 Result += "\nstatic struct {\n";
2910 Result += "\tint protocol_method_count;\n";
2911 Result += "\tstruct protocol_methods protocols[";
2912 Result += utostr(NumMethods);
2913 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00002914 Result += PDecl->getNameAsString();
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002915 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2916 "{\n\t";
2917 Result += utostr(NumMethods);
2918 Result += "\n";
2919
2920 // Output instance methods declared in this protocol.
2921 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
2922 E = PDecl->classmeth_end(); I != E; ++I) {
2923 if (I == PDecl->classmeth_begin())
2924 Result += "\t ,{{(SEL)\"";
2925 else
2926 Result += "\t ,{(SEL)\"";
Chris Lattner3a8f2942008-11-24 03:33:13 +00002927 Result += (*I)->getSelector().getAsString().c_str();
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002928 std::string MethodTypeString;
2929 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2930 Result += "\", \"";
2931 Result += MethodTypeString;
2932 Result += "\"}\n";
2933 }
2934 Result += "\t }\n};\n";
2935 }
2936
2937 // Output:
2938 /* struct _objc_protocol {
2939 // Objective-C 1.0 extensions
2940 struct _objc_protocol_extension *isa;
2941 char *protocol_name;
2942 struct _objc_protocol **protocol_list;
2943 struct _objc_protocol_method_list *instance_methods;
2944 struct _objc_protocol_method_list *class_methods;
2945 };
Steve Naroff27429432008-03-12 01:06:30 +00002946 */
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002947 static bool objc_protocol = false;
2948 if (!objc_protocol) {
2949 Result += "\nstruct _objc_protocol {\n";
2950 Result += "\tstruct _objc_protocol_extension *isa;\n";
2951 Result += "\tchar *protocol_name;\n";
2952 Result += "\tstruct _objc_protocol **protocol_list;\n";
2953 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2954 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2955 Result += "};\n";
2956
2957 objc_protocol = true;
2958 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002959
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002960 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
Chris Lattner271d4c22008-11-24 05:29:24 +00002961 Result += PDecl->getNameAsString();
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002962 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
2963 "{\n\t0, \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00002964 Result += PDecl->getNameAsString();
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002965 Result += "\", 0, ";
2966 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2967 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00002968 Result += PDecl->getNameAsString();
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002969 Result += ", ";
2970 }
2971 else
2972 Result += "0, ";
Chris Lattner179fd522009-02-20 18:18:36 +00002973 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002974 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00002975 Result += PDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002976 Result += "\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002977 }
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002978 else
2979 Result += "0\n";
2980 Result += "};\n";
2981
2982 // Mark this protocol as having been generated.
2983 if (!ObjCSynthesizedProtocols.insert(PDecl))
2984 assert(false && "protocol already synthesized");
2985 }
2986 // Output the top lovel protocol meta-data for the class.
2987 /* struct _objc_protocol_list {
2988 struct _objc_protocol_list *next;
2989 int protocol_count;
2990 struct _objc_protocol *class_protocols[];
2991 }
2992 */
2993 Result += "\nstatic struct {\n";
2994 Result += "\tstruct _objc_protocol_list *next;\n";
2995 Result += "\tint protocol_count;\n";
2996 Result += "\tstruct _objc_protocol *class_protocols[";
2997 Result += utostr(Protocols.size());
2998 Result += "];\n} _OBJC_";
2999 Result += prefix;
3000 Result += "_PROTOCOLS_";
3001 Result += ClassName;
3002 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3003 "{\n\t0, ";
3004 Result += utostr(Protocols.size());
3005 Result += "\n";
3006
3007 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003008 Result += Protocols[0]->getNameAsString();
Chris Lattnera19b5ec2008-07-21 21:33:21 +00003009 Result += " \n";
3010
3011 for (unsigned i = 1; i != Protocols.size(); i++) {
3012 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003013 Result += Protocols[i]->getNameAsString();
Chris Lattnera19b5ec2008-07-21 21:33:21 +00003014 Result += "\n";
3015 }
3016 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003017}
3018
Ted Kremenek42730c52008-01-07 19:49:32 +00003019/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003020/// implementation.
Steve Naroff44e81222008-04-14 22:03:09 +00003021void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003022 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00003023 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003024 // Find category declaration for this implementation.
Ted Kremenek42730c52008-01-07 19:49:32 +00003025 ObjCCategoryDecl *CDecl;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003026 for (CDecl = ClassDecl->getCategoryList(); CDecl;
3027 CDecl = CDecl->getNextClassCategory())
3028 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3029 break;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003030
Chris Lattner271d4c22008-11-24 05:29:24 +00003031 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnera661a4d2007-12-23 01:40:15 +00003032 FullCategoryName += '_';
Chris Lattner271d4c22008-11-24 05:29:24 +00003033 FullCategoryName += IDecl->getNameAsString();
Chris Lattnera661a4d2007-12-23 01:40:15 +00003034
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003035 // Build _objc_method_list for class's instance methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00003036 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnera661a4d2007-12-23 01:40:15 +00003037 true, "CATEGORY_", FullCategoryName.c_str(),
3038 Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003039
3040 // Build _objc_method_list for class's class methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00003041 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnera661a4d2007-12-23 01:40:15 +00003042 false, "CATEGORY_", FullCategoryName.c_str(),
3043 Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003044
3045 // Protocols referenced in class declaration?
Fariborz Jahaniand256e062007-11-13 22:09:49 +00003046 // Null CDecl is case of a category implementation with no category interface
3047 if (CDecl)
Chris Lattner0be08822008-07-21 21:32:27 +00003048 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Chris Lattnera661a4d2007-12-23 01:40:15 +00003049 FullCategoryName.c_str(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003050
3051 /* struct _objc_category {
3052 char *category_name;
3053 char *class_name;
3054 struct _objc_method_list *instance_methods;
3055 struct _objc_method_list *class_methods;
3056 struct _objc_protocol_list *protocols;
3057 // Objective-C 1.0 extensions
3058 uint32_t size; // sizeof (struct _objc_category)
3059 struct _objc_property_list *instance_properties; // category's own
3060 // @property decl.
3061 };
3062 */
3063
3064 static bool objc_category = false;
3065 if (!objc_category) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003066 Result += "\nstruct _objc_category {\n";
3067 Result += "\tchar *category_name;\n";
3068 Result += "\tchar *class_name;\n";
3069 Result += "\tstruct _objc_method_list *instance_methods;\n";
3070 Result += "\tstruct _objc_method_list *class_methods;\n";
3071 Result += "\tstruct _objc_protocol_list *protocols;\n";
3072 Result += "\tunsigned int size;\n";
3073 Result += "\tstruct _objc_property_list *instance_properties;\n";
3074 Result += "};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003075 objc_category = true;
Fariborz Jahanian04455192007-10-22 21:41:37 +00003076 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003077 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3078 Result += FullCategoryName;
Steve Naroff5ce4a242008-03-12 17:18:30 +00003079 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003080 Result += IDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003081 Result += "\"\n\t, \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003082 Result += ClassDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003083 Result += "\"\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003084
Chris Lattner179fd522009-02-20 18:18:36 +00003085 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003086 Result += "\t, (struct _objc_method_list *)"
3087 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3088 Result += FullCategoryName;
3089 Result += "\n";
3090 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003091 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003092 Result += "\t, 0\n";
Chris Lattner179fd522009-02-20 18:18:36 +00003093 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003094 Result += "\t, (struct _objc_method_list *)"
3095 "&_OBJC_CATEGORY_CLASS_METHODS_";
3096 Result += FullCategoryName;
3097 Result += "\n";
3098 }
3099 else
3100 Result += "\t, 0\n";
3101
Chris Lattner179fd522009-02-20 18:18:36 +00003102 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003103 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
3104 Result += FullCategoryName;
3105 Result += "\n";
3106 }
3107 else
3108 Result += "\t, 0\n";
3109 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003110}
3111
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00003112/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3113/// ivar offset.
Steve Naroff44e81222008-04-14 22:03:09 +00003114void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
Ted Kremenek42730c52008-01-07 19:49:32 +00003115 ObjCIvarDecl *ivar,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00003116 std::string &Result) {
Steve Naroffd3354222008-07-16 18:22:22 +00003117 if (ivar->isBitField()) {
3118 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3119 // place all bitfields at offset 0.
3120 Result += "0";
3121 } else {
3122 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003123 Result += IDecl->getNameAsString();
Steve Naroffd3354222008-07-16 18:22:22 +00003124 if (LangOpts.Microsoft)
3125 Result += "_IMPL";
3126 Result += ", ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003127 Result += ivar->getNameAsString();
Steve Naroffd3354222008-07-16 18:22:22 +00003128 Result += ")";
3129 }
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00003130}
3131
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003132//===----------------------------------------------------------------------===//
3133// Meta Data Emission
3134//===----------------------------------------------------------------------===//
3135
Steve Naroff44e81222008-04-14 22:03:09 +00003136void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003137 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00003138 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003139
Fariborz Jahanian7e216522007-11-26 20:59:57 +00003140 // Explictly declared @interface's are already synthesized.
3141 if (CDecl->ImplicitInterfaceDecl()) {
3142 // FIXME: Implementation of a class with no @interface (legacy) doese not
3143 // produce correct synthesis as yet.
Ted Kremenek42730c52008-01-07 19:49:32 +00003144 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian7e216522007-11-26 20:59:57 +00003145 }
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00003146
Chris Lattnerc7b06752007-12-12 07:56:42 +00003147 // Build _objc_ivar_list metadata for classes ivars if needed
Chris Lattnerec4979b2008-03-16 21:08:55 +00003148 unsigned NumIvars = !IDecl->ivar_empty()
3149 ? IDecl->ivar_size()
3150 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003151 if (NumIvars > 0) {
3152 static bool objc_ivar = false;
3153 if (!objc_ivar) {
3154 /* struct _objc_ivar {
3155 char *ivar_name;
3156 char *ivar_type;
3157 int ivar_offset;
3158 };
3159 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003160 Result += "\nstruct _objc_ivar {\n";
3161 Result += "\tchar *ivar_name;\n";
3162 Result += "\tchar *ivar_type;\n";
3163 Result += "\tint ivar_offset;\n";
3164 Result += "};\n";
3165
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003166 objc_ivar = true;
3167 }
3168
Steve Naroffc723eec2008-03-11 00:12:29 +00003169 /* struct {
3170 int ivar_count;
3171 struct _objc_ivar ivar_list[nIvars];
3172 };
3173 */
3174 Result += "\nstatic struct {\n";
3175 Result += "\tint ivar_count;\n";
3176 Result += "\tstruct _objc_ivar ivar_list[";
3177 Result += utostr(NumIvars);
3178 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003179 Result += IDecl->getNameAsString();
Steve Naroff5ce4a242008-03-12 17:18:30 +00003180 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003181 "{\n\t";
3182 Result += utostr(NumIvars);
3183 Result += "\n";
Chris Lattnerc7b06752007-12-12 07:56:42 +00003184
Ted Kremenek42730c52008-01-07 19:49:32 +00003185 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerec4979b2008-03-16 21:08:55 +00003186 if (!IDecl->ivar_empty()) {
Chris Lattnerc7b06752007-12-12 07:56:42 +00003187 IVI = IDecl->ivar_begin();
3188 IVE = IDecl->ivar_end();
3189 } else {
3190 IVI = CDecl->ivar_begin();
3191 IVE = CDecl->ivar_end();
3192 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003193 Result += "\t,{{\"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003194 Result += (*IVI)->getNameAsString();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00003195 Result += "\", \"";
3196 std::string StrEncoding;
Daniel Dunbarc9197cd2008-10-17 20:21:44 +00003197 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00003198 Result += StrEncoding;
3199 Result += "\", ";
Chris Lattnerc7b06752007-12-12 07:56:42 +00003200 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00003201 Result += "}\n";
Chris Lattnerc7b06752007-12-12 07:56:42 +00003202 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003203 Result += "\t ,{\"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003204 Result += (*IVI)->getNameAsString();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00003205 Result += "\", \"";
3206 std::string StrEncoding;
Daniel Dunbarc9197cd2008-10-17 20:21:44 +00003207 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00003208 Result += StrEncoding;
3209 Result += "\", ";
Chris Lattnerc7b06752007-12-12 07:56:42 +00003210 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00003211 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003212 }
3213
3214 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003215 }
3216
3217 // Build _objc_method_list for class's instance methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00003218 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnerd120b9e2008-11-24 03:54:41 +00003219 true, "", IDecl->getNameAsCString(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003220
3221 // Build _objc_method_list for class's class methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00003222 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerd120b9e2008-11-24 03:54:41 +00003223 false, "", IDecl->getNameAsCString(), Result);
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003224
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003225 // Protocols referenced in class declaration?
Chris Lattner0be08822008-07-21 21:32:27 +00003226 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Chris Lattnerd120b9e2008-11-24 03:54:41 +00003227 "CLASS", CDecl->getNameAsCString(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003228
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003229
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003230 // Declaration of class/meta-class metadata
3231 /* struct _objc_class {
3232 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003233 const char *super_class_name;
3234 char *name;
3235 long version;
3236 long info;
3237 long instance_size;
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003238 struct _objc_ivar_list *ivars;
3239 struct _objc_method_list *methods;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003240 struct objc_cache *cache;
3241 struct objc_protocol_list *protocols;
3242 const char *ivar_layout;
3243 struct _objc_class_ext *ext;
3244 };
3245 */
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003246 static bool objc_class = false;
3247 if (!objc_class) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003248 Result += "\nstruct _objc_class {\n";
3249 Result += "\tstruct _objc_class *isa;\n";
3250 Result += "\tconst char *super_class_name;\n";
3251 Result += "\tchar *name;\n";
3252 Result += "\tlong version;\n";
3253 Result += "\tlong info;\n";
3254 Result += "\tlong instance_size;\n";
3255 Result += "\tstruct _objc_ivar_list *ivars;\n";
3256 Result += "\tstruct _objc_method_list *methods;\n";
3257 Result += "\tstruct objc_cache *cache;\n";
3258 Result += "\tstruct _objc_protocol_list *protocols;\n";
3259 Result += "\tconst char *ivar_layout;\n";
3260 Result += "\tstruct _objc_class_ext *ext;\n";
3261 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003262 objc_class = true;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003263 }
3264
3265 // Meta-class metadata generation.
Ted Kremenek42730c52008-01-07 19:49:32 +00003266 ObjCInterfaceDecl *RootClass = 0;
3267 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003268 while (SuperClass) {
3269 RootClass = SuperClass;
3270 SuperClass = SuperClass->getSuperClass();
3271 }
3272 SuperClass = CDecl->getSuperClass();
3273
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003274 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003275 Result += CDecl->getNameAsString();
Steve Naroff5ce4a242008-03-12 17:18:30 +00003276 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003277 "{\n\t(struct _objc_class *)\"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003278 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003279 Result += "\"";
3280
3281 if (SuperClass) {
3282 Result += ", \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003283 Result += SuperClass->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003284 Result += "\", \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003285 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003286 Result += "\"";
3287 }
3288 else {
3289 Result += ", 0, \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003290 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003291 Result += "\"";
3292 }
Ted Kremenek42730c52008-01-07 19:49:32 +00003293 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003294 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003295 Result += ", 0,2, sizeof(struct _objc_class), 0";
Chris Lattner5c6b2c62009-02-20 18:43:26 +00003296 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroffdee066b2008-03-11 18:14:26 +00003297 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003298 Result += IDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003299 Result += "\n";
3300 }
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003301 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003302 Result += ", 0\n";
Chris Lattner179fd522009-02-20 18:18:36 +00003303 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff27429432008-03-12 01:06:30 +00003304 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003305 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003306 Result += ",0,0\n";
3307 }
Fariborz Jahanian0cb4d922007-10-24 20:54:23 +00003308 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003309 Result += "\t,0,0,0,0\n";
3310 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003311
3312 // class metadata generation.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003313 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003314 Result += CDecl->getNameAsString();
Steve Naroff5ce4a242008-03-12 17:18:30 +00003315 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003316 "{\n\t&_OBJC_METACLASS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003317 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003318 if (SuperClass) {
3319 Result += ", \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003320 Result += SuperClass->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003321 Result += "\", \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003322 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003323 Result += "\"";
3324 }
3325 else {
3326 Result += ", 0, \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003327 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003328 Result += "\"";
3329 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003330 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00003331 Result += ", 0,1";
Ted Kremenek42730c52008-01-07 19:49:32 +00003332 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00003333 Result += ",0";
3334 else {
3335 // class has size. Must synthesize its size.
Fariborz Jahanian9447e462007-11-05 17:47:33 +00003336 Result += ",sizeof(struct ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003337 Result += CDecl->getNameAsString();
Steve Naroffc302e5b2008-03-10 23:33:22 +00003338 if (LangOpts.Microsoft)
3339 Result += "_IMPL";
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00003340 Result += ")";
3341 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003342 if (NumIvars > 0) {
Steve Naroffbec4bf52008-03-11 17:37:02 +00003343 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003344 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003345 Result += "\n\t";
3346 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003347 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003348 Result += ",0";
Chris Lattner5c6b2c62009-02-20 18:43:26 +00003349 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroffc723eec2008-03-11 00:12:29 +00003350 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003351 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003352 Result += ", 0\n\t";
3353 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003354 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003355 Result += ",0,0";
Chris Lattner179fd522009-02-20 18:18:36 +00003356 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff27429432008-03-12 01:06:30 +00003357 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003358 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003359 Result += ", 0,0\n";
3360 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003361 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003362 Result += ",0,0,0\n";
3363 Result += "};\n";
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003364}
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00003365
Fariborz Jahanian8c664912007-11-13 19:21:13 +00003366/// RewriteImplementations - This routine rewrites all method implementations
3367/// and emits meta-data.
3368
Steve Naroff21658f62008-11-13 20:07:04 +00003369void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003370 int ClsDefCount = ClassImplementation.size();
3371 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian8c664912007-11-13 19:21:13 +00003372
Fariborz Jahanian8c664912007-11-13 19:21:13 +00003373 // Rewrite implemented methods
3374 for (int i = 0; i < ClsDefCount; i++)
3375 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00003376
Fariborz Jahanian0136e372007-11-13 20:04:28 +00003377 for (int i = 0; i < CatDefCount; i++)
3378 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Naroff21658f62008-11-13 20:07:04 +00003379}
Fariborz Jahanian0136e372007-11-13 20:04:28 +00003380
Steve Naroff21658f62008-11-13 20:07:04 +00003381void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3382 int ClsDefCount = ClassImplementation.size();
3383 int CatDefCount = CategoryImplementation.size();
3384
Steve Naroff5bf10222008-05-07 21:23:49 +00003385 // This is needed for determining instance variable offsets.
Steve Naroff314c1a62008-08-05 18:47:23 +00003386 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003387 // For each implemented class, write out all its meta data.
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00003388 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek42730c52008-01-07 19:49:32 +00003389 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003390
3391 // For each implemented category, write out all its meta data.
3392 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek42730c52008-01-07 19:49:32 +00003393 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00003394
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003395 // Write objc_symtab metadata
3396 /*
3397 struct _objc_symtab
3398 {
3399 long sel_ref_cnt;
3400 SEL *refs;
3401 short cls_def_cnt;
3402 short cat_def_cnt;
3403 void *defs[cls_def_cnt + cat_def_cnt];
3404 };
3405 */
3406
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003407 Result += "\nstruct _objc_symtab {\n";
3408 Result += "\tlong sel_ref_cnt;\n";
3409 Result += "\tSEL *refs;\n";
3410 Result += "\tshort cls_def_cnt;\n";
3411 Result += "\tshort cat_def_cnt;\n";
3412 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3413 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003414
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003415 Result += "static struct _objc_symtab "
Steve Naroff5ce4a242008-03-12 17:18:30 +00003416 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003417 Result += "\t0, 0, " + utostr(ClsDefCount)
3418 + ", " + utostr(CatDefCount) + "\n";
3419 for (int i = 0; i < ClsDefCount; i++) {
3420 Result += "\t,&_OBJC_CLASS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003421 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003422 Result += "\n";
3423 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003424
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003425 for (int i = 0; i < CatDefCount; i++) {
3426 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003427 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003428 Result += "_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003429 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003430 Result += "\n";
3431 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003432
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003433 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003434
3435 // Write objc_module metadata
3436
3437 /*
3438 struct _objc_module {
3439 long version;
3440 long size;
3441 const char *name;
3442 struct _objc_symtab *symtab;
3443 }
3444 */
3445
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003446 Result += "\nstruct _objc_module {\n";
3447 Result += "\tlong version;\n";
3448 Result += "\tlong size;\n";
3449 Result += "\tconst char *name;\n";
3450 Result += "\tstruct _objc_symtab *symtab;\n";
3451 Result += "};\n\n";
3452 Result += "static struct _objc_module "
Steve Naroff5ce4a242008-03-12 17:18:30 +00003453 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00003454 Result += "\t" + utostr(OBJC_ABI_VERSION) +
3455 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003456 Result += "};\n\n";
Steve Naroff7fd0aff2008-03-10 20:43:59 +00003457
3458 if (LangOpts.Microsoft) {
3459 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroffbdd2dba2008-05-07 00:06:16 +00003460 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff7fd0aff2008-03-10 20:43:59 +00003461 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3462 Result += "&_OBJC_MODULES;\n";
3463 Result += "#pragma data_seg(pop)\n\n";
3464 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003465}
Chris Lattner6fe8b272007-10-16 22:36:42 +00003466
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003467std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3468 const char *funcName,
3469 std::string Tag) {
3470 const FunctionType *AFT = CE->getFunctionType();
3471 QualType RT = AFT->getResultType();
3472 std::string StructRef = "struct " + Tag;
3473 std::string S = "static " + RT.getAsString() + " __" +
3474 funcName + "_" + "block_func_" + utostr(i);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00003475
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003476 BlockDecl *BD = CE->getBlockDecl();
3477
Douglas Gregor4fa58902009-02-26 23:50:07 +00003478 if (isa<FunctionNoProtoType>(AFT)) {
Steve Naroff16478cf2009-02-02 17:19:26 +00003479 // No user-supplied arguments. Still need to pass in a pointer to the
3480 // block (to reference imported block decl refs).
3481 S += "(" + StructRef + " *__cself)";
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003482 } else if (BD->param_empty()) {
3483 S += "(" + StructRef + " *__cself)";
3484 } else {
Douglas Gregor4fa58902009-02-26 23:50:07 +00003485 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003486 assert(FT && "SynthesizeBlockFunc: No function proto");
3487 S += '(';
3488 // first add the implicit argument.
3489 S += StructRef + " *__cself, ";
3490 std::string ParamStr;
3491 for (BlockDecl::param_iterator AI = BD->param_begin(),
3492 E = BD->param_end(); AI != E; ++AI) {
3493 if (AI != BD->param_begin()) S += ", ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003494 ParamStr = (*AI)->getNameAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003495 (*AI)->getType().getAsStringInternal(ParamStr);
3496 S += ParamStr;
3497 }
3498 if (FT->isVariadic()) {
3499 if (!BD->param_empty()) S += ", ";
3500 S += "...";
3501 }
3502 S += ')';
3503 }
3504 S += " {\n";
3505
3506 // Create local declarations to avoid rewriting all closure decl ref exprs.
3507 // First, emit a declaration for all "by ref" decls.
3508 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3509 E = BlockByRefDecls.end(); I != E; ++I) {
3510 S += " ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003511 std::string Name = (*I)->getNameAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003512 Context->getPointerType((*I)->getType()).getAsStringInternal(Name);
Chris Lattner271d4c22008-11-24 05:29:24 +00003513 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003514 }
3515 // Next, emit a declaration for all "by copy" declarations.
3516 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3517 E = BlockByCopyDecls.end(); I != E; ++I) {
3518 S += " ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003519 std::string Name = (*I)->getNameAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003520 // Handle nested closure invocation. For example:
3521 //
3522 // void (^myImportedClosure)(void);
3523 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3524 //
3525 // void (^anotherClosure)(void);
3526 // anotherClosure = ^(void) {
3527 // myImportedClosure(); // import and invoke the closure
3528 // };
3529 //
Steve Naroffd896f4b2008-12-11 21:05:33 +00003530 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003531 S += "struct __block_impl *";
3532 else
3533 (*I)->getType().getAsStringInternal(Name);
Chris Lattner271d4c22008-11-24 05:29:24 +00003534 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003535 }
3536 std::string RewrittenStr = RewrittenBlockExprs[CE];
3537 const char *cstr = RewrittenStr.c_str();
3538 while (*cstr++ != '{') ;
3539 S += cstr;
3540 S += "\n";
3541 return S;
3542}
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00003543
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003544std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3545 const char *funcName,
3546 std::string Tag) {
3547 std::string StructRef = "struct " + Tag;
3548 std::string S = "static void __";
3549
3550 S += funcName;
3551 S += "_block_copy_" + utostr(i);
3552 S += "(" + StructRef;
3553 S += "*dst, " + StructRef;
3554 S += "*src) {";
3555 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3556 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff44fe1e32008-12-16 15:50:30 +00003557 S += "_Block_object_assign((void*)&dst->";
Chris Lattner271d4c22008-11-24 05:29:24 +00003558 S += (*I)->getNameAsString();
Steve Naroff1d56d9e2008-12-11 20:51:38 +00003559 S += ", (void*)src->";
Chris Lattner271d4c22008-11-24 05:29:24 +00003560 S += (*I)->getNameAsString();
Steve Naroff44fe1e32008-12-16 15:50:30 +00003561 S += ", 3/*BLOCK_FIELD_IS_OBJECT*/);}";
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003562 }
3563 S += "\nstatic void __";
3564 S += funcName;
3565 S += "_block_dispose_" + utostr(i);
3566 S += "(" + StructRef;
3567 S += "*src) {";
3568 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3569 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff44fe1e32008-12-16 15:50:30 +00003570 S += "_Block_object_dispose((void*)src->";
Chris Lattner271d4c22008-11-24 05:29:24 +00003571 S += (*I)->getNameAsString();
Steve Naroff44fe1e32008-12-16 15:50:30 +00003572 S += ", 3/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003573 }
3574 S += "}\n";
3575 return S;
3576}
3577
3578std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3579 bool hasCopyDisposeHelpers) {
Steve Naroff6449c6c2008-10-30 12:09:33 +00003580 std::string S = "\nstruct " + Tag;
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003581 std::string Constructor = " " + Tag;
3582
3583 S += " {\n struct __block_impl impl;\n";
3584
3585 if (hasCopyDisposeHelpers)
3586 S += " void *copy;\n void *dispose;\n";
3587
3588 Constructor += "(void *fp";
3589
3590 if (hasCopyDisposeHelpers)
3591 Constructor += ", void *copyHelp, void *disposeHelp";
3592
3593 if (BlockDeclRefs.size()) {
3594 // Output all "by copy" declarations.
3595 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3596 E = BlockByCopyDecls.end(); I != E; ++I) {
3597 S += " ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003598 std::string FieldName = (*I)->getNameAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003599 std::string ArgName = "_" + FieldName;
3600 // Handle nested closure invocation. For example:
3601 //
3602 // void (^myImportedBlock)(void);
3603 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3604 //
3605 // void (^anotherBlock)(void);
3606 // anotherBlock = ^(void) {
3607 // myImportedBlock(); // import and invoke the closure
3608 // };
3609 //
Steve Naroffd896f4b2008-12-11 21:05:33 +00003610 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003611 S += "struct __block_impl *";
3612 Constructor += ", void *" + ArgName;
3613 } else {
3614 (*I)->getType().getAsStringInternal(FieldName);
3615 (*I)->getType().getAsStringInternal(ArgName);
3616 Constructor += ", " + ArgName;
3617 }
3618 S += FieldName + ";\n";
3619 }
3620 // Output all "by ref" declarations.
3621 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3622 E = BlockByRefDecls.end(); I != E; ++I) {
3623 S += " ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003624 std::string FieldName = (*I)->getNameAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003625 std::string ArgName = "_" + FieldName;
3626 // Handle nested closure invocation. For example:
3627 //
3628 // void (^myImportedBlock)(void);
3629 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3630 //
3631 // void (^anotherBlock)(void);
3632 // anotherBlock = ^(void) {
3633 // myImportedBlock(); // import and invoke the closure
3634 // };
3635 //
Steve Naroffd896f4b2008-12-11 21:05:33 +00003636 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003637 S += "struct __block_impl *";
3638 Constructor += ", void *" + ArgName;
3639 } else {
3640 Context->getPointerType((*I)->getType()).getAsStringInternal(FieldName);
3641 Context->getPointerType((*I)->getType()).getAsStringInternal(ArgName);
3642 Constructor += ", " + ArgName;
3643 }
3644 S += FieldName + "; // by ref\n";
3645 }
3646 // Finish writing the constructor.
3647 // FIXME: handle NSConcreteGlobalBlock.
3648 Constructor += ", int flags=0) {\n";
3649 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3650 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3651
3652 if (hasCopyDisposeHelpers)
3653 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3654
3655 // Initialize all "by copy" arguments.
3656 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3657 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattner271d4c22008-11-24 05:29:24 +00003658 std::string Name = (*I)->getNameAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003659 Constructor += " ";
Steve Naroffd896f4b2008-12-11 21:05:33 +00003660 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003661 Constructor += Name + " = (struct __block_impl *)_";
3662 else
3663 Constructor += Name + " = _";
3664 Constructor += Name + ";\n";
3665 }
3666 // Initialize all "by ref" arguments.
3667 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3668 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattner271d4c22008-11-24 05:29:24 +00003669 std::string Name = (*I)->getNameAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003670 Constructor += " ";
Steve Naroffd896f4b2008-12-11 21:05:33 +00003671 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003672 Constructor += Name + " = (struct __block_impl *)_";
3673 else
3674 Constructor += Name + " = _";
3675 Constructor += Name + ";\n";
3676 }
3677 } else {
3678 // Finish writing the constructor.
3679 // FIXME: handle NSConcreteGlobalBlock.
3680 Constructor += ", int flags=0) {\n";
3681 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3682 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3683 if (hasCopyDisposeHelpers)
3684 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3685 }
3686 Constructor += " ";
3687 Constructor += "}\n";
3688 S += Constructor;
3689 S += "};\n";
3690 return S;
3691}
3692
3693void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3694 const char *FunName) {
3695 // Insert closures that were part of the function.
3696 for (unsigned i = 0; i < Blocks.size(); i++) {
3697
3698 CollectBlockDeclRefInfo(Blocks[i]);
3699
3700 std::string Tag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
3701
3702 std::string CI = SynthesizeBlockImpl(Blocks[i], Tag,
3703 ImportedBlockDecls.size() > 0);
3704
3705 InsertText(FunLocStart, CI.c_str(), CI.size());
3706
3707 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, Tag);
3708
3709 InsertText(FunLocStart, CF.c_str(), CF.size());
3710
3711 if (ImportedBlockDecls.size()) {
3712 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, Tag);
3713 InsertText(FunLocStart, HF.c_str(), HF.size());
3714 }
3715
3716 BlockDeclRefs.clear();
3717 BlockByRefDecls.clear();
3718 BlockByCopyDecls.clear();
3719 BlockCallExprs.clear();
3720 ImportedBlockDecls.clear();
3721 }
3722 Blocks.clear();
3723 RewrittenBlockExprs.clear();
3724}
3725
3726void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3727 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattnerd120b9e2008-11-24 03:54:41 +00003728 const char *FuncName = FD->getNameAsCString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003729
3730 SynthesizeBlockLiterals(FunLocStart, FuncName);
3731}
3732
3733void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroff6449c6c2008-10-30 12:09:33 +00003734 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3735 //SourceLocation FunLocStart = MD->getLocStart();
3736 // FIXME: This hack works around a bug in Rewrite.InsertText().
3737 SourceLocation FunLocStart = MD->getLocStart().getFileLocWithOffset(-1);
Chris Lattner3a8f2942008-11-24 03:33:13 +00003738 std::string FuncName = MD->getSelector().getAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003739 // Convert colons to underscores.
3740 std::string::size_type loc = 0;
3741 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3742 FuncName.replace(loc, 1, "_");
3743
3744 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
3745}
3746
3747void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
3748 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3749 CI != E; ++CI)
3750 if (*CI) {
3751 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3752 GetBlockDeclRefExprs(CBE->getBody());
3753 else
3754 GetBlockDeclRefExprs(*CI);
3755 }
3756 // Handle specific things.
3757 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
3758 // FIXME: Handle enums.
3759 if (!isa<FunctionDecl>(CDRE->getDecl()))
3760 BlockDeclRefs.push_back(CDRE);
3761 return;
3762}
3763
3764void RewriteObjC::GetBlockCallExprs(Stmt *S) {
3765 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3766 CI != E; ++CI)
3767 if (*CI) {
3768 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3769 GetBlockCallExprs(CBE->getBody());
3770 else
3771 GetBlockCallExprs(*CI);
3772 }
3773
3774 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
3775 if (CE->getCallee()->getType()->isBlockPointerType()) {
3776 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
3777 }
3778 }
3779 return;
3780}
3781
Steve Naroff85eb17b2008-10-30 10:07:53 +00003782Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp) {
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003783 // Navigate to relevant type information.
3784 const char *closureName = 0;
3785 const BlockPointerType *CPT = 0;
3786
3787 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp->getCallee())) {
Chris Lattnerd120b9e2008-11-24 03:54:41 +00003788 closureName = DRE->getDecl()->getNameAsCString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003789 CPT = DRE->getType()->getAsBlockPointerType();
3790 } else if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(Exp->getCallee())) {
Chris Lattnerd120b9e2008-11-24 03:54:41 +00003791 closureName = CDRE->getDecl()->getNameAsCString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003792 CPT = CDRE->getType()->getAsBlockPointerType();
3793 } else if (MemberExpr *MExpr = dyn_cast<MemberExpr>(Exp->getCallee())) {
Chris Lattnerd120b9e2008-11-24 03:54:41 +00003794 closureName = MExpr->getMemberDecl()->getNameAsCString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003795 CPT = MExpr->getType()->getAsBlockPointerType();
3796 } else {
3797 assert(1 && "RewriteBlockClass: Bad type");
3798 }
3799 assert(CPT && "RewriteBlockClass: Bad type");
3800 const FunctionType *FT = CPT->getPointeeType()->getAsFunctionType();
3801 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor4fa58902009-02-26 23:50:07 +00003802 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003803 // FTP will be null for closures that don't take arguments.
3804
Steve Naroff85eb17b2008-10-30 10:07:53 +00003805 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
3806 SourceLocation(),
3807 &Context->Idents.get("__block_impl"));
3808 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003809
Steve Naroff85eb17b2008-10-30 10:07:53 +00003810 // Generate a funky cast.
3811 llvm::SmallVector<QualType, 8> ArgTypes;
3812
3813 // Push the block argument type.
3814 ArgTypes.push_back(PtrBlock);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003815 if (FTP) {
Douglas Gregor4fa58902009-02-26 23:50:07 +00003816 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff85eb17b2008-10-30 10:07:53 +00003817 E = FTP->arg_type_end(); I && (I != E); ++I) {
3818 QualType t = *I;
3819 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffd896f4b2008-12-11 21:05:33 +00003820 if (isTopLevelBlockPointerType(t)) {
Steve Naroff85eb17b2008-10-30 10:07:53 +00003821 const BlockPointerType *BPT = t->getAsBlockPointerType();
3822 t = Context->getPointerType(BPT->getPointeeType());
3823 }
3824 ArgTypes.push_back(t);
3825 }
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003826 }
Steve Naroff85eb17b2008-10-30 10:07:53 +00003827 // Now do the pointer to function cast.
3828 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
3829 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
3830
3831 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003832
Ted Kremenek0c97e042009-02-07 01:47:29 +00003833 CastExpr *BlkCast = new (Context) CStyleCastExpr(PtrBlock, Exp->getCallee(),
3834 PtrBlock, SourceLocation(),
3835 SourceLocation());
Steve Naroff85eb17b2008-10-30 10:07:53 +00003836 // Don't forget the parens to enforce the proper binding.
Ted Kremenek0c97e042009-02-07 01:47:29 +00003837 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3838 BlkCast);
Steve Naroff85eb17b2008-10-30 10:07:53 +00003839 //PE->dump();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003840
Douglas Gregor8acb7272008-12-11 16:49:14 +00003841 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
3842 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00003843 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek0c97e042009-02-07 01:47:29 +00003844 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
3845 FD->getType());
Steve Naroff85eb17b2008-10-30 10:07:53 +00003846
Ted Kremenek0c97e042009-02-07 01:47:29 +00003847 CastExpr *FunkCast = new (Context) CStyleCastExpr(PtrToFuncCastType, ME,
3848 PtrToFuncCastType,
3849 SourceLocation(),
3850 SourceLocation());
3851 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Steve Naroff85eb17b2008-10-30 10:07:53 +00003852
3853 llvm::SmallVector<Expr*, 8> BlkExprs;
3854 // Add the implicit argument.
3855 BlkExprs.push_back(BlkCast);
3856 // Add the user arguments.
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003857 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3858 E = Exp->arg_end(); I != E; ++I) {
Steve Naroff85eb17b2008-10-30 10:07:53 +00003859 BlkExprs.push_back(*I);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003860 }
Ted Kremenek362abcd2009-02-09 20:51:47 +00003861 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
3862 BlkExprs.size(),
Ted Kremenek0c97e042009-02-07 01:47:29 +00003863 Exp->getType(), SourceLocation());
Steve Naroff85eb17b2008-10-30 10:07:53 +00003864 return CE;
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003865}
3866
3867void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Steve Naroff85eb17b2008-10-30 10:07:53 +00003868 Stmt *BlockCall = SynthesizeBlockCall(Exp);
3869 ReplaceStmt(Exp, BlockCall);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003870}
3871
3872void RewriteObjC::RewriteBlockDeclRefExpr(BlockDeclRefExpr *BDRE) {
3873 // FIXME: Add more elaborate code generation required by the ABI.
Ted Kremenek0c97e042009-02-07 01:47:29 +00003874 Expr *DerefExpr = new (Context) UnaryOperator(BDRE, UnaryOperator::Deref,
Steve Naroff16478cf2009-02-02 17:19:26 +00003875 Context->getPointerType(BDRE->getType()),
3876 SourceLocation());
3877 // Need parens to enforce precedence.
Ted Kremenek0c97e042009-02-07 01:47:29 +00003878 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), DerefExpr);
Steve Naroff16478cf2009-02-02 17:19:26 +00003879 ReplaceStmt(BDRE, PE);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003880}
3881
Steve Naroff7f1412d2008-11-03 23:29:32 +00003882void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3883 SourceLocation LocStart = CE->getLParenLoc();
3884 SourceLocation LocEnd = CE->getRParenLoc();
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00003885
3886 // Need to avoid trying to rewrite synthesized casts.
3887 if (LocStart.isInvalid())
3888 return;
Steve Naroff1c53c022008-11-03 11:20:24 +00003889 // Need to avoid trying to rewrite casts contained in macros.
3890 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3891 return;
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00003892
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003893 const char *startBuf = SM->getCharacterData(LocStart);
3894 const char *endBuf = SM->getCharacterData(LocEnd);
3895
3896 // advance the location to startArgList.
3897 const char *argPtr = startBuf;
3898
3899 while (*argPtr++ && (argPtr < endBuf)) {
3900 switch (*argPtr) {
3901 case '^':
3902 // Replace the '^' with '*'.
3903 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
3904 ReplaceText(LocStart, 1, "*", 1);
3905 break;
3906 }
3907 }
3908 return;
3909}
3910
3911void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
3912 SourceLocation DeclLoc = FD->getLocation();
3913 unsigned parenCount = 0;
3914
3915 // We have 1 or more arguments that have closure pointers.
3916 const char *startBuf = SM->getCharacterData(DeclLoc);
3917 const char *startArgList = strchr(startBuf, '(');
3918
3919 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
3920
3921 parenCount++;
3922 // advance the location to startArgList.
3923 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
3924 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
3925
3926 const char *argPtr = startArgList;
3927
3928 while (*argPtr++ && parenCount) {
3929 switch (*argPtr) {
3930 case '^':
3931 // Replace the '^' with '*'.
3932 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
3933 ReplaceText(DeclLoc, 1, "*", 1);
3934 break;
3935 case '(':
3936 parenCount++;
3937 break;
3938 case ')':
3939 parenCount--;
3940 break;
3941 }
3942 }
3943 return;
3944}
3945
3946bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor4fa58902009-02-26 23:50:07 +00003947 const FunctionProtoType *FTP;
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003948 const PointerType *PT = QT->getAsPointerType();
3949 if (PT) {
Douglas Gregor4fa58902009-02-26 23:50:07 +00003950 FTP = PT->getPointeeType()->getAsFunctionProtoType();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003951 } else {
3952 const BlockPointerType *BPT = QT->getAsBlockPointerType();
3953 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
Douglas Gregor4fa58902009-02-26 23:50:07 +00003954 FTP = BPT->getPointeeType()->getAsFunctionProtoType();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003955 }
3956 if (FTP) {
Douglas Gregor4fa58902009-02-26 23:50:07 +00003957 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003958 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroffd896f4b2008-12-11 21:05:33 +00003959 if (isTopLevelBlockPointerType(*I))
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003960 return true;
3961 }
3962 return false;
3963}
3964
Ted Kremenek0c97e042009-02-07 01:47:29 +00003965void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
3966 const char *&RParen) {
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003967 const char *argPtr = strchr(Name, '(');
3968 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
3969
3970 LParen = argPtr; // output the start.
3971 argPtr++; // skip past the left paren.
3972 unsigned parenCount = 1;
3973
3974 while (*argPtr && parenCount) {
3975 switch (*argPtr) {
3976 case '(': parenCount++; break;
3977 case ')': parenCount--; break;
3978 default: break;
3979 }
3980 if (parenCount) argPtr++;
3981 }
3982 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
3983 RParen = argPtr; // output the end
3984}
3985
3986void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
3987 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3988 RewriteBlockPointerFunctionArgs(FD);
3989 return;
3990 }
3991 // Handle Variables and Typedefs.
3992 SourceLocation DeclLoc = ND->getLocation();
3993 QualType DeclT;
3994 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3995 DeclT = VD->getType();
3996 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
3997 DeclT = TDD->getUnderlyingType();
3998 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
3999 DeclT = FD->getType();
4000 else
4001 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
4002
4003 const char *startBuf = SM->getCharacterData(DeclLoc);
4004 const char *endBuf = startBuf;
4005 // scan backward (from the decl location) for the end of the previous decl.
4006 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4007 startBuf--;
4008
4009 // *startBuf != '^' if we are dealing with a pointer to function that
4010 // may take block argument types (which will be handled below).
4011 if (*startBuf == '^') {
4012 // Replace the '^' with '*', computing a negative offset.
4013 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
4014 ReplaceText(DeclLoc, 1, "*", 1);
4015 }
4016 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4017 // Replace the '^' with '*' for arguments.
4018 DeclLoc = ND->getLocation();
4019 startBuf = SM->getCharacterData(DeclLoc);
4020 const char *argListBegin, *argListEnd;
4021 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4022 while (argListBegin < argListEnd) {
4023 if (*argListBegin == '^') {
4024 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
4025 ReplaceText(CaretLoc, 1, "*", 1);
4026 }
4027 argListBegin++;
4028 }
4029 }
4030 return;
4031}
4032
4033void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
4034 // Add initializers for any closure decl refs.
4035 GetBlockDeclRefExprs(Exp->getBody());
4036 if (BlockDeclRefs.size()) {
4037 // Unique all "by copy" declarations.
4038 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4039 if (!BlockDeclRefs[i]->isByRef())
4040 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
4041 // Unique all "by ref" declarations.
4042 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4043 if (BlockDeclRefs[i]->isByRef()) {
4044 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
4045 }
4046 // Find any imported blocks...they will need special attention.
4047 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Steve Naroff1d56d9e2008-12-11 20:51:38 +00004048 if (BlockDeclRefs[i]->getType()->isBlockPointerType()) {
Steve Naroffe59c8b12008-11-13 17:40:07 +00004049 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00004050 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4051 }
4052 }
4053}
4054
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004055FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
4056 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor4fa58902009-02-26 23:50:07 +00004057 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004058 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
Douglas Gregor1f88aa72009-02-25 16:33:18 +00004059 ID, FType, FunctionDecl::Extern, false,
4060 false);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004061}
4062
Steve Naroff80c54752008-10-29 18:15:37 +00004063Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004064 Blocks.push_back(Exp);
4065
4066 CollectBlockDeclRefInfo(Exp);
4067 std::string FuncName;
4068
4069 if (CurFunctionDef)
Chris Lattner3a8f2942008-11-24 03:33:13 +00004070 FuncName = CurFunctionDef->getNameAsString();
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004071 else if (CurMethodDef) {
Chris Lattner3a8f2942008-11-24 03:33:13 +00004072 FuncName = CurMethodDef->getSelector().getAsString();
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004073 // Convert colons to underscores.
4074 std::string::size_type loc = 0;
4075 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4076 FuncName.replace(loc, 1, "_");
Steve Naroff80c54752008-10-29 18:15:37 +00004077 } else if (GlobalVarDecl)
Chris Lattner271d4c22008-11-24 05:29:24 +00004078 FuncName = std::string(GlobalVarDecl->getNameAsString());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004079
4080 std::string BlockNumber = utostr(Blocks.size()-1);
4081
4082 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4083 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
4084
4085 // Get a pointer to the function type so we can cast appropriately.
4086 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
4087
4088 FunctionDecl *FD;
4089 Expr *NewRep;
4090
4091 // Simulate a contructor call...
4092 FD = SynthBlockInitFunctionDecl(Tag.c_str());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004093 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004094
4095 llvm::SmallVector<Expr*, 4> InitExprs;
4096
Steve Naroffd0419d62008-10-29 21:23:59 +00004097 // Initialize the block function.
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004098 FD = SynthBlockInitFunctionDecl(Func.c_str());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004099 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
4100 SourceLocation());
4101 CastExpr *castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy, Arg,
4102 Context->VoidPtrTy, SourceLocation(),
4103 SourceLocation());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004104 InitExprs.push_back(castExpr);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004105
4106 if (ImportedBlockDecls.size()) {
4107 std::string Buf = "__" + FuncName + "_block_copy_" + BlockNumber;
Steve Naroffd0419d62008-10-29 21:23:59 +00004108 FD = SynthBlockInitFunctionDecl(Buf.c_str());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004109 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4110 castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy, Arg,
4111 Context->VoidPtrTy, SourceLocation(),
4112 SourceLocation());
Steve Naroffd0419d62008-10-29 21:23:59 +00004113 InitExprs.push_back(castExpr);
4114
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004115 Buf = "__" + FuncName + "_block_dispose_" + BlockNumber;
Steve Naroffd0419d62008-10-29 21:23:59 +00004116 FD = SynthBlockInitFunctionDecl(Buf.c_str());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004117 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4118 castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy, Arg,
4119 Context->VoidPtrTy, SourceLocation(),
4120 SourceLocation());
Steve Naroffd0419d62008-10-29 21:23:59 +00004121 InitExprs.push_back(castExpr);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004122 }
4123 // Add initializers for any closure decl refs.
4124 if (BlockDeclRefs.size()) {
Steve Naroffd0419d62008-10-29 21:23:59 +00004125 Expr *Exp;
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004126 // Output all "by copy" declarations.
4127 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4128 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004129 if (isObjCType((*I)->getType())) {
Steve Naroffd0419d62008-10-29 21:23:59 +00004130 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattnerd120b9e2008-11-24 03:54:41 +00004131 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004132 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroffd896f4b2008-12-11 21:05:33 +00004133 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Chris Lattnerd120b9e2008-11-24 03:54:41 +00004134 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004135 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4136 Exp = new (Context) CStyleCastExpr(Context->VoidPtrTy, Arg,
4137 Context->VoidPtrTy, SourceLocation(),
4138 SourceLocation());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004139 } else {
Chris Lattnerd120b9e2008-11-24 03:54:41 +00004140 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004141 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004142 }
Steve Naroffd0419d62008-10-29 21:23:59 +00004143 InitExprs.push_back(Exp);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004144 }
4145 // Output all "by ref" declarations.
4146 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4147 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerd120b9e2008-11-24 03:54:41 +00004148 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004149 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4150 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf,
Steve Naroffd0419d62008-10-29 21:23:59 +00004151 Context->getPointerType(Exp->getType()),
4152 SourceLocation());
Steve Naroff362c7562008-11-14 21:36:12 +00004153 InitExprs.push_back(Exp);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004154 }
4155 }
Ted Kremenek362abcd2009-02-09 20:51:47 +00004156 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4157 FType, SourceLocation());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004158 NewRep = new (Context) UnaryOperator(NewRep, UnaryOperator::AddrOf,
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004159 Context->getPointerType(NewRep->getType()),
4160 SourceLocation());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004161 NewRep = new (Context) CStyleCastExpr(FType, NewRep, FType, SourceLocation(),
4162 SourceLocation());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004163 BlockDeclRefs.clear();
4164 BlockByRefDecls.clear();
4165 BlockByCopyDecls.clear();
4166 ImportedBlockDecls.clear();
4167 return NewRep;
4168}
4169
4170//===----------------------------------------------------------------------===//
4171// Function Body / Expression rewriting
4172//===----------------------------------------------------------------------===//
4173
Steve Naroff0e948412008-12-04 16:24:46 +00004174// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
4175// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
4176// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
4177// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
4178// Since the rewriter isn't capable of rewriting rewritten code, it's important
4179// we get this right.
4180void RewriteObjC::CollectPropertySetters(Stmt *S) {
4181 // Perform a bottom up traversal of all children.
4182 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4183 CI != E; ++CI)
4184 if (*CI)
4185 CollectPropertySetters(*CI);
4186
4187 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
4188 if (BinOp->isAssignmentOp()) {
4189 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
4190 PropSetters[PRE] = BinOp;
4191 }
4192 }
4193}
4194
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004195Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
4196 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4197 isa<DoStmt>(S) || isa<ForStmt>(S))
4198 Stmts.push_back(S);
4199 else if (isa<ObjCForCollectionStmt>(S)) {
4200 Stmts.push_back(S);
4201 ObjCBcLabelNo.push_back(++BcLabelCount);
4202 }
4203
4204 SourceRange OrigStmtRange = S->getSourceRange();
4205
4206 // Perform a bottom up rewrite of all children.
4207 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4208 CI != E; ++CI)
4209 if (*CI) {
4210 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
4211 if (newStmt)
4212 *CI = newStmt;
4213 }
4214
4215 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4216 // Rewrite the block body in place.
4217 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
4218
4219 // Now we snarf the rewritten text and stash it away for later use.
Steve Naroff80c54752008-10-29 18:15:37 +00004220 std::string Str = Rewrite.getRewritenText(BE->getSourceRange());
4221 RewrittenBlockExprs[BE] = Str;
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004222
4223 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
4224 //blockTranscribed->dump();
Steve Naroff80c54752008-10-29 18:15:37 +00004225 ReplaceStmt(S, blockTranscribed);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004226 return blockTranscribed;
4227 }
4228 // Handle specific things.
4229 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4230 return RewriteAtEncode(AtEncode);
4231
4232 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
4233 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
4234
Steve Naroff0e948412008-12-04 16:24:46 +00004235 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
4236 BinaryOperator *BinOp = PropSetters[PropRefExpr];
4237 if (BinOp) {
4238 // Because the rewriter doesn't allow us to rewrite rewritten code,
4239 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroffedb4bc92008-12-09 12:56:34 +00004240 DisableReplaceStmt = true;
4241 // Save the source range. Even if we disable the replacement, the
4242 // rewritten node will have been inserted into the tree. If the synthesized
4243 // node is at the 'end', the rewriter will fail. Consider this:
4244 // self.errorHandler = handler ? handler :
4245 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
4246 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroff0e948412008-12-04 16:24:46 +00004247 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroffedb4bc92008-12-09 12:56:34 +00004248 DisableReplaceStmt = false;
Steve Naroff102c3f22008-12-04 23:50:32 +00004249 //
4250 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
4251 // we changed the RHS of BinOp, the rewriter would fail (since it needs
4252 // to see the original expression). Consider this example:
4253 //
4254 // Foo *obj1, *obj2;
4255 //
4256 // obj1.i = [obj2 rrrr];
4257 //
4258 // 'BinOp' for the previous expression looks like:
4259 //
4260 // (BinaryOperator 0x231ccf0 'int' '='
4261 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
4262 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
4263 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
4264 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
4265 //
4266 // 'newStmt' represents the rewritten message expression. For example:
4267 //
4268 // (CallExpr 0x231d300 'id':'struct objc_object *'
4269 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
4270 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
4271 // (CStyleCastExpr 0x231d220 'void *'
4272 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
4273 //
4274 // Note that 'newStmt' is passed to RewritePropertySetter so that it
4275 // can be used as the setter argument. ReplaceStmt() will still 'see'
4276 // the original RHS (since we haven't altered BinOp).
4277 //
4278 // This implies the Rewrite* routines can no longer delete the original
4279 // node. As a result, we now leak the original AST nodes.
4280 //
Steve Naroffedb4bc92008-12-09 12:56:34 +00004281 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroff0e948412008-12-04 16:24:46 +00004282 } else {
4283 return RewritePropertyGetter(PropRefExpr);
Steve Narofff6ce8a12008-12-03 00:56:33 +00004284 }
4285 }
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004286 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4287 return RewriteAtSelector(AtSelector);
4288
4289 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4290 return RewriteObjCStringLiteral(AtString);
4291
4292 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroff0e948412008-12-04 16:24:46 +00004293#if 0
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004294 // Before we rewrite it, put the original message expression in a comment.
4295 SourceLocation startLoc = MessExpr->getLocStart();
4296 SourceLocation endLoc = MessExpr->getLocEnd();
4297
4298 const char *startBuf = SM->getCharacterData(startLoc);
4299 const char *endBuf = SM->getCharacterData(endLoc);
4300
4301 std::string messString;
4302 messString += "// ";
4303 messString.append(startBuf, endBuf-startBuf+1);
4304 messString += "\n";
4305
4306 // FIXME: Missing definition of
4307 // InsertText(clang::SourceLocation, char const*, unsigned int).
4308 // InsertText(startLoc, messString.c_str(), messString.size());
4309 // Tried this, but it didn't work either...
4310 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroff0e948412008-12-04 16:24:46 +00004311#endif
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004312 return RewriteMessageExpr(MessExpr);
4313 }
4314
4315 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4316 return RewriteObjCTryStmt(StmtTry);
4317
4318 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4319 return RewriteObjCSynchronizedStmt(StmtTry);
4320
4321 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4322 return RewriteObjCThrowStmt(StmtThrow);
4323
4324 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4325 return RewriteObjCProtocolExpr(ProtocolExp);
4326
4327 if (ObjCForCollectionStmt *StmtForCollection =
4328 dyn_cast<ObjCForCollectionStmt>(S))
4329 return RewriteObjCForCollectionStmt(StmtForCollection,
4330 OrigStmtRange.getEnd());
4331 if (BreakStmt *StmtBreakStmt =
4332 dyn_cast<BreakStmt>(S))
4333 return RewriteBreakStmt(StmtBreakStmt);
4334 if (ContinueStmt *StmtContinueStmt =
4335 dyn_cast<ContinueStmt>(S))
4336 return RewriteContinueStmt(StmtContinueStmt);
4337
4338 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
4339 // and cast exprs.
4340 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4341 // FIXME: What we're doing here is modifying the type-specifier that
4342 // precedes the first Decl. In the future the DeclGroup should have
4343 // a separate type-specifier that we can rewrite.
4344 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
4345
4346 // Blocks rewrite rules.
4347 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4348 DI != DE; ++DI) {
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00004349 Decl *SD = *DI;
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004350 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroffd896f4b2008-12-11 21:05:33 +00004351 if (isTopLevelBlockPointerType(ND->getType()))
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004352 RewriteBlockPointerDecl(ND);
4353 else if (ND->getType()->isFunctionPointerType())
4354 CheckFunctionPointerDecl(ND->getType(), ND);
4355 }
4356 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroffd896f4b2008-12-11 21:05:33 +00004357 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004358 RewriteBlockPointerDecl(TD);
4359 else if (TD->getUnderlyingType()->isFunctionPointerType())
4360 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4361 }
4362 }
4363 }
4364
4365 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4366 RewriteObjCQualifiedInterfaceTypes(CE);
4367
4368 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4369 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4370 assert(!Stmts.empty() && "Statement stack is empty");
4371 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4372 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
4373 && "Statement stack mismatch");
4374 Stmts.pop_back();
4375 }
4376 // Handle blocks rewriting.
4377 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4378 if (BDRE->isByRef())
4379 RewriteBlockDeclRefExpr(BDRE);
4380 }
4381 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroff85eb17b2008-10-30 10:07:53 +00004382 if (CE->getCallee()->getType()->isBlockPointerType()) {
4383 Stmt *BlockCall = SynthesizeBlockCall(CE);
4384 ReplaceStmt(S, BlockCall);
4385 return BlockCall;
4386 }
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004387 }
Steve Naroff7f1412d2008-11-03 23:29:32 +00004388 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004389 RewriteCastExpr(CE);
4390 }
4391#if 0
4392 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Ted Kremenek0c97e042009-02-07 01:47:29 +00004393 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004394 // Get the new text.
4395 std::string SStr;
4396 llvm::raw_string_ostream Buf(SStr);
4397 Replacement->printPretty(Buf);
4398 const std::string &Str = Buf.str();
4399
4400 printf("CAST = %s\n", &Str[0]);
4401 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4402 delete S;
4403 return Replacement;
4404 }
4405#endif
4406 // Return this stmt unmodified.
4407 return S;
4408}
4409
4410/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4411/// main file of the input.
4412void RewriteObjC::HandleDeclInMainFile(Decl *D) {
4413 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffee8d4972008-12-17 00:20:22 +00004414 if (FD->isOverloadedOperator())
4415 return;
4416
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004417 // Since function prototypes don't have ParmDecl's, we check the function
4418 // prototype. This enables us to rewrite function declarations and
4419 // definitions using the same code.
Douglas Gregor4fa58902009-02-26 23:50:07 +00004420 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004421
Ted Kremenek30916072009-03-12 18:33:24 +00004422 if (CompoundStmt *Body = FD->getBody()) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004423 CurFunctionDef = FD;
Steve Naroff0e948412008-12-04 16:24:46 +00004424 CollectPropertySetters(Body);
Steve Narofffbed6802008-12-08 16:43:47 +00004425 CurrentBody = Body;
Ted Kremenek30916072009-03-12 18:33:24 +00004426 Body =
4427 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4428 FD->setBody(Body);
Steve Narofffbed6802008-12-08 16:43:47 +00004429 CurrentBody = 0;
4430 if (PropParentMap) {
4431 delete PropParentMap;
4432 PropParentMap = 0;
4433 }
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004434 // This synthesizes and inserts the block "impl" struct, invoke function,
4435 // and any copy/dispose helper functions.
4436 InsertBlockLiteralsWithinFunction(FD);
4437 CurFunctionDef = 0;
4438 }
4439 return;
4440 }
4441 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Ted Kremenek30916072009-03-12 18:33:24 +00004442 if (CompoundStmt *Body = MD->getBody()) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004443 CurMethodDef = MD;
Steve Naroff0e948412008-12-04 16:24:46 +00004444 CollectPropertySetters(Body);
Steve Narofffbed6802008-12-08 16:43:47 +00004445 CurrentBody = Body;
Ted Kremenek30916072009-03-12 18:33:24 +00004446 Body =
4447 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4448 MD->setBody(Body);
Steve Narofffbed6802008-12-08 16:43:47 +00004449 CurrentBody = 0;
4450 if (PropParentMap) {
4451 delete PropParentMap;
4452 PropParentMap = 0;
4453 }
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004454 InsertBlockLiteralsWithinMethod(MD);
4455 CurMethodDef = 0;
4456 }
4457 }
4458 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
4459 ClassImplementation.push_back(CI);
4460 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
4461 CategoryImplementation.push_back(CI);
4462 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
4463 RewriteForwardClassDecl(CD);
4464 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4465 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroffd896f4b2008-12-11 21:05:33 +00004466 if (isTopLevelBlockPointerType(VD->getType()))
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004467 RewriteBlockPointerDecl(VD);
Steve Naroff80c54752008-10-29 18:15:37 +00004468 else if (VD->getType()->isFunctionPointerType()) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004469 CheckFunctionPointerDecl(VD->getType(), VD);
4470 if (VD->getInit()) {
Steve Naroff7f1412d2008-11-03 23:29:32 +00004471 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004472 RewriteCastExpr(CE);
4473 }
4474 }
4475 }
Steve Naroff80c54752008-10-29 18:15:37 +00004476 if (VD->getInit()) {
4477 GlobalVarDecl = VD;
Steve Naroff0e948412008-12-04 16:24:46 +00004478 CollectPropertySetters(VD->getInit());
Steve Narofffbed6802008-12-08 16:43:47 +00004479 CurrentBody = VD->getInit();
Steve Naroff80c54752008-10-29 18:15:37 +00004480 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Narofffbed6802008-12-08 16:43:47 +00004481 CurrentBody = 0;
4482 if (PropParentMap) {
4483 delete PropParentMap;
4484 PropParentMap = 0;
4485 }
Douglas Gregor24afd4a2008-11-17 14:58:09 +00004486 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattnerd120b9e2008-11-24 03:54:41 +00004487 VD->getNameAsCString());
Steve Naroff80c54752008-10-29 18:15:37 +00004488 GlobalVarDecl = 0;
4489
4490 // This is needed for blocks.
Steve Naroff7f1412d2008-11-03 23:29:32 +00004491 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff80c54752008-10-29 18:15:37 +00004492 RewriteCastExpr(CE);
4493 }
4494 }
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004495 return;
4496 }
4497 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroffd896f4b2008-12-11 21:05:33 +00004498 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004499 RewriteBlockPointerDecl(TD);
4500 else if (TD->getUnderlyingType()->isFunctionPointerType())
4501 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4502 return;
4503 }
4504 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
4505 if (RD->isDefinition()) {
Douglas Gregor640a04b2008-12-11 17:59:21 +00004506 for (RecordDecl::field_iterator i = RD->field_begin(),
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004507 e = RD->field_end(); i != e; ++i) {
4508 FieldDecl *FD = *i;
Steve Naroffd896f4b2008-12-11 21:05:33 +00004509 if (isTopLevelBlockPointerType(FD->getType()))
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004510 RewriteBlockPointerDecl(FD);
4511 }
4512 }
4513 return;
4514 }
4515 // Nothing yet.
4516}
4517
Chris Lattner2a594d02009-03-28 04:11:33 +00004518void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004519 // Get the top-level buffer that this corresponds to.
4520
4521 // Rewrite tabs if we care.
4522 //RewriteTabs();
4523
4524 if (Diags.hasErrorOccurred())
4525 return;
4526
4527 // Create the output file.
4528
4529 llvm::OwningPtr<llvm::raw_ostream> OwnedStream;
4530 llvm::raw_ostream *OutFile;
4531 if (OutFileName == "-") {
4532 OutFile = &llvm::outs();
4533 } else if (!OutFileName.empty()) {
4534 std::string Err;
Steve Naroff08299f82009-02-03 20:39:18 +00004535 OutFile = new llvm::raw_fd_ostream(OutFileName.c_str(),
4536 // set binary mode (critical for Windoze)
4537 true,
4538 Err);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004539 OwnedStream.reset(OutFile);
4540 } else if (InFileName == "-") {
4541 OutFile = &llvm::outs();
4542 } else {
4543 llvm::sys::Path Path(InFileName);
4544 Path.eraseSuffix();
4545 Path.appendSuffix("cpp");
4546 std::string Err;
Steve Naroff08299f82009-02-03 20:39:18 +00004547 OutFile = new llvm::raw_fd_ostream(Path.toString().c_str(),
4548 // set binary mode (critical for Windoze)
4549 true,
4550 Err);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004551 OwnedStream.reset(OutFile);
4552 }
4553
4554 RewriteInclude();
4555
Chris Lattnerf4f776a2009-01-17 06:22:33 +00004556 InsertText(SM->getLocForStartOfFile(MainFileID),
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004557 Preamble.c_str(), Preamble.size(), false);
4558
Steve Naroff901d8fd2008-11-14 14:10:01 +00004559 if (ClassImplementation.size() || CategoryImplementation.size())
4560 RewriteImplementations();
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004561
4562 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
4563 // we are done.
4564 if (const RewriteBuffer *RewriteBuf =
4565 Rewrite.getRewriteBufferFor(MainFileID)) {
4566 //printf("Changed:\n");
4567 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4568 } else {
4569 fprintf(stderr, "No changes\n");
4570 }
Steve Naroff21658f62008-11-13 20:07:04 +00004571
Steve Naroff901d8fd2008-11-14 14:10:01 +00004572 if (ClassImplementation.size() || CategoryImplementation.size()) {
4573 // Rewrite Objective-c meta data*
4574 std::string ResultStr;
4575 SynthesizeMetaDataIntoBuffer(ResultStr);
4576 // Emit metadata.
4577 *OutFile << ResultStr;
4578 }
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004579 OutFile->flush();
4580}
4581