blob: b3de53671b7de0153c8412cc4e5a2c3286658a9d [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
Eli Friedman22a4efd2009-05-18 22:50:54 +000014#include "clang/Frontend/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"
Dan Gohman6da15102008-05-21 20:19:16 +000027#include "llvm/Support/Streams.h"
Ted Kremenek7b6f67b2008-09-13 05:16:45 +000028#include "llvm/Support/raw_ostream.h"
Chris Lattnerb429ae42007-10-11 00:43:27 +000029using namespace clang;
Chris Lattnerc3aa5c42007-10-25 17:07:24 +000030using llvm::utostr;
Chris Lattnerb429ae42007-10-11 00:43:27 +000031
Chris Lattnerb429ae42007-10-11 00:43:27 +000032namespace {
Steve Naroff44e81222008-04-14 22:03:09 +000033 class RewriteObjC : public ASTConsumer {
Chris Lattner74db1682007-10-16 21:07:07 +000034 Rewriter Rewrite;
Chris Lattner258f26c2007-11-30 22:25:36 +000035 Diagnostic &Diags;
Steve Naroff7fd0aff2008-03-10 20:43:59 +000036 const LangOptions &LangOpts;
Steve Naroff53b6f4c2008-01-30 19:17:43 +000037 unsigned RewriteFailedDiag;
Steve Naroff43964fb2008-12-05 17:03:39 +000038 unsigned TryFinallyContainsReturnDiag;
39
Chris Lattnerbf0bfa62007-10-17 22:35:30 +000040 ASTContext *Context;
Chris Lattnerb429ae42007-10-11 00:43:27 +000041 SourceManager *SM;
Argiris Kirtzidisd3586002008-04-17 14:40:12 +000042 TranslationUnitDecl *TUDecl;
Chris Lattnerf4f776a2009-01-17 06:22:33 +000043 FileID MainFileID;
Chris Lattnerae43eb72007-12-02 01:13:47 +000044 const char *MainFileStart, *MainFileEnd;
Chris Lattner74db1682007-10-16 21:07:07 +000045 SourceLocation LastIncLoc;
Steve Narofffef037c2008-03-27 22:29:16 +000046
Ted Kremenek42730c52008-01-07 19:49:32 +000047 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
48 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
49 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Naroff04eaa192008-05-06 18:26:51 +000050 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremenek42730c52008-01-07 19:49:32 +000051 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
52 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanian13dad332008-01-15 23:58:23 +000053 llvm::SmallVector<Stmt *, 32> Stmts;
54 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroff450d2fc2009-04-29 16:37:50 +000055 // Remember all the @protocol(<expr>) expressions.
56 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Steve Naroffe9780582007-10-23 23:50:29 +000057
Steve Naroff47e7fa22008-03-15 00:55:56 +000058 unsigned NumObjCStringLiterals;
59
Steve Naroffe9780582007-10-23 23:50:29 +000060 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +000061 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +000062 FunctionDecl *MsgSendStretFunctionDecl;
63 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +000064 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffe9780582007-10-23 23:50:29 +000065 FunctionDecl *GetClassFunctionDecl;
Steve Naroff3b1caac2007-12-07 03:50:46 +000066 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff71226032007-10-24 22:48:43 +000067 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroffabb96362007-11-08 14:30:50 +000068 FunctionDecl *CFStringFunctionDecl;
Steve Naroffbec4bf52008-03-11 17:37:02 +000069 FunctionDecl *SuperContructorFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +000070
Steve Naroff0add5d22007-11-03 11:27:19 +000071 // ObjC string constant support.
Steve Naroff72a6ebc2008-04-15 22:42:06 +000072 VarDecl *ConstantStringClassReference;
Steve Naroff0add5d22007-11-03 11:27:19 +000073 RecordDecl *NSStringRecord;
Steve Naroff0744c472007-11-04 22:37:50 +000074
Fariborz Jahanian22277422008-01-16 00:09:11 +000075 // ObjC foreach break/continue generation support.
Fariborz Jahanian13dad332008-01-15 23:58:23 +000076 int BcLabelCount;
77
Steve Naroff764c1ae2007-11-15 10:28:18 +000078 // Needed for super.
Steve Naroff38a9e3f2008-10-27 17:20:55 +000079 ObjCMethodDecl *CurMethodDef;
Steve Naroff764c1ae2007-11-15 10:28:18 +000080 RecordDecl *SuperStructDecl;
Steve Naroff47e7fa22008-03-15 00:55:56 +000081 RecordDecl *ConstantStringDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +000082
Steve Naroff450d2fc2009-04-29 16:37:50 +000083 TypeDecl *ProtocolTypeDecl;
84 QualType getProtocolType();
85
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +000086 // Needed for header files being rewritten
87 bool IsHeader;
88
Steve Naroffcfd9f4c2008-03-28 22:26:09 +000089 std::string InFileName;
Eli Friedmana9c310842009-05-18 22:20:00 +000090 llvm::raw_ostream* OutFile;
Eli Friedman35ba7a62009-05-18 22:39:16 +000091
92 bool SilenceRewriteMacroWarning;
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.
Chris Lattnera17991f2009-03-29 16:50:03 +0000129 virtual void HandleTopLevelDecl(DeclGroupRef D) {
130 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I)
131 HandleTopLevelSingleDecl(*I);
132 }
133 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner74db1682007-10-16 21:07:07 +0000134 void HandleDeclInMainFile(Decl *D);
Eli Friedmana9c310842009-05-18 22:20:00 +0000135 RewriteObjC(std::string inFile, llvm::raw_ostream *OS,
Eli Friedman35ba7a62009-05-18 22:39:16 +0000136 Diagnostic &D, const LangOptions &LOpts,
137 bool silenceMacroWarn);
Ted Kremenekcab0b0c2008-08-08 04:15:52 +0000138
139 ~RewriteObjC() {}
140
Chris Lattner2a594d02009-03-28 04:11:33 +0000141 virtual void HandleTranslationUnit(ASTContext &C);
Chris Lattnerb1548372008-01-31 19:37:57 +0000142
143 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff102c3f22008-12-04 23:50:32 +0000144 Stmt *ReplacingStmt = ReplacedNodes[Old];
145
146 if (ReplacingStmt)
147 return; // We can't rewrite the same node twice.
Chris Lattnerb1548372008-01-31 19:37:57 +0000148
Steve Naroffedb4bc92008-12-09 12:56:34 +0000149 if (DisableReplaceStmt)
150 return; // Used when rewriting the assignment of a property setter.
151
Steve Naroff102c3f22008-12-04 23:50:32 +0000152 // If replacement succeeded or warning disabled return with no warning.
153 if (!Rewrite.ReplaceStmt(Old, New)) {
154 ReplacedNodes[Old] = New;
155 return;
156 }
157 if (SilenceRewriteMacroWarning)
158 return;
Chris Lattner6948ae62008-11-18 07:04:44 +0000159 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
160 << Old->getSourceRange();
Chris Lattnerb1548372008-01-31 19:37:57 +0000161 }
Steve Naroffedb4bc92008-12-09 12:56:34 +0000162
163 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
164 // Measaure the old text.
165 int Size = Rewrite.getRangeSize(SrcRange);
166 if (Size == -1) {
167 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
168 << Old->getSourceRange();
169 return;
170 }
171 // Get the new text.
172 std::string SStr;
173 llvm::raw_string_ostream S(SStr);
Chris Lattner7099c782009-06-30 01:26:17 +0000174 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
Steve Naroffedb4bc92008-12-09 12:56:34 +0000175 const std::string &Str = S.str();
176
177 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbar60987c92009-08-19 19:10:30 +0000178 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroffedb4bc92008-12-09 12:56:34 +0000179 ReplacedNodes[Old] = New;
180 return;
181 }
182 if (SilenceRewriteMacroWarning)
183 return;
184 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
185 << Old->getSourceRange();
186 }
187
Steve Narofffef037c2008-03-27 22:29:16 +0000188 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
189 bool InsertAfter = true) {
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000190 // If insertion succeeded or warning disabled return with no warning.
Daniel Dunbar60987c92009-08-19 19:10:30 +0000191 if (!Rewrite.InsertText(Loc, llvm::StringRef(StrData, StrLen),
192 InsertAfter) ||
Chris Lattner6216f292008-01-31 19:42:41 +0000193 SilenceRewriteMacroWarning)
194 return;
195
196 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
197 }
Chris Lattnerb1548372008-01-31 19:37:57 +0000198
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000199 void RemoveText(SourceLocation Loc, unsigned StrLen) {
200 // If removal succeeded or warning disabled return with no warning.
201 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
202 return;
203
204 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
205 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000206
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000207 void ReplaceText(SourceLocation Start, unsigned OrigLength,
208 const char *NewStr, unsigned NewLength) {
209 // If removal succeeded or warning disabled return with no warning.
Daniel Dunbar60987c92009-08-19 19:10:30 +0000210 if (!Rewrite.ReplaceText(Start, OrigLength,
211 llvm::StringRef(NewStr, NewLength)) ||
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000212 SilenceRewriteMacroWarning)
213 return;
214
215 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
216 }
217
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000218 // Syntactic Rewriting.
Steve Naroff0744c472007-11-04 22:37:50 +0000219 void RewritePrologue(SourceLocation Loc);
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000220 void RewriteInclude();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000221 void RewriteTabs();
Ted Kremenek42730c52008-01-07 19:49:32 +0000222 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffea6610f2008-12-02 17:36:43 +0000223 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
224 ObjCImplementationDecl *IMD,
225 ObjCCategoryImplDecl *CID);
Ted Kremenek42730c52008-01-07 19:49:32 +0000226 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000227 void RewriteImplementationDecl(Decl *Dcl);
Ted Kremenek42730c52008-01-07 19:49:32 +0000228 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
229 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
230 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
231 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
232 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff56af2002009-01-11 01:06:09 +0000233 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff02a82aa2007-10-30 23:14:51 +0000234 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000235 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroffd06c88d2008-07-29 18:15:38 +0000236 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffc8a92d12007-11-01 13:24:47 +0000237 bool needToScanForQualifiers(QualType T);
Ted Kremenek42730c52008-01-07 19:49:32 +0000238 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff764c1ae2007-11-15 10:28:18 +0000239 QualType getSuperStructType();
Steve Naroff47e7fa22008-03-15 00:55:56 +0000240 QualType getConstantStringStructType();
Steve Naroffef82b742008-05-31 14:15:04 +0000241 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Chris Lattner6fe8b272007-10-16 22:36:42 +0000242
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000243 // Expression Rewriting.
Steve Naroff334fbc22007-11-09 15:20:18 +0000244 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroff0e948412008-12-04 16:24:46 +0000245 void CollectPropertySetters(Stmt *S);
246
Steve Narofffbed6802008-12-08 16:43:47 +0000247 Stmt *CurrentBody;
248 ParentMap *PropParentMap; // created lazily.
249
Chris Lattner0021f452007-10-24 16:57:36 +0000250 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner343c82b2008-05-23 20:40:52 +0000251 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart);
Steve Naroff0e948412008-12-04 16:24:46 +0000252 Stmt *RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr);
Steve Naroffedb4bc92008-12-09 12:56:34 +0000253 Stmt *RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
254 SourceRange SrcRange);
Steve Naroff296b74f2007-11-05 14:50:49 +0000255 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner0021f452007-10-24 16:57:36 +0000256 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroff0add5d22007-11-03 11:27:19 +0000257 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000258 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroff43964fb2008-12-05 17:03:39 +0000259 void WarnAboutReturnGotoContinueOrBreakStmts(Stmt *S);
Ted Kremenek42730c52008-01-07 19:49:32 +0000260 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian499bf412008-01-29 22:59:37 +0000261 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremenek42730c52008-01-07 19:49:32 +0000262 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
263 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
264 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner2c022162008-01-31 05:10:40 +0000265 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
266 SourceLocation OrigEnd);
Steve Naroff71226032007-10-24 22:48:43 +0000267 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
268 Expr **args, unsigned nargs);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000269 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000270 Stmt *RewriteBreakStmt(BreakStmt *S);
271 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000272 void SynthCountByEnumWithState(std::string &buf);
273
Steve Naroff02a82aa2007-10-30 23:14:51 +0000274 void SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +0000275 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000276 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +0000277 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000278 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +0000279 void SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +0000280 void SynthGetMetaClassFunctionDecl();
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +0000281 void SynthSelGetUidFunctionDecl();
Steve Naroffbec4bf52008-03-11 17:37:02 +0000282 void SynthSuperContructorFunctionDecl();
Steve Naroffabb96362007-11-08 14:30:50 +0000283
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000284 // Metadata emission.
Ted Kremenek42730c52008-01-07 19:49:32 +0000285 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000286 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000287
Ted Kremenek42730c52008-01-07 19:49:32 +0000288 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000289 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000290
Douglas Gregorcd19b572009-04-23 01:02:12 +0000291 template<typename MethodIterator>
292 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
293 MethodIterator MethodEnd,
Fariborz Jahaniana3986372007-10-25 00:14:44 +0000294 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000295 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +0000296 const char *ClassName,
297 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000298
Steve Naroff450d2fc2009-04-29 16:37:50 +0000299 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
300 const char *prefix,
301 const char *ClassName,
302 std::string &Result);
303 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
304 const char *prefix,
305 const char *ClassName,
306 std::string &Result);
Ted Kremenek42730c52008-01-07 19:49:32 +0000307 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000308 std::string &Result);
Ted Kremenek42730c52008-01-07 19:49:32 +0000309 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
310 ObjCIvarDecl *ivar,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000311 std::string &Result);
Steve Naroff21658f62008-11-13 20:07:04 +0000312 void RewriteImplementations();
313 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000314
315 // Block rewriting.
Douglas Gregor4fa58902009-02-26 23:50:07 +0000316 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000317 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
318
319 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
320 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
321
Steve Naroff80c54752008-10-29 18:15:37 +0000322 // Block specific rewrite rules.
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000323 void RewriteBlockCall(CallExpr *Exp);
324 void RewriteBlockPointerDecl(NamedDecl *VD);
Steve Naroff450d2fc2009-04-29 16:37:50 +0000325 Stmt *RewriteBlockDeclRefExpr(BlockDeclRefExpr *VD);
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000326 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
327
328 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
329 const char *funcName, std::string Tag);
330 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
331 const char *funcName, std::string Tag);
332 std::string SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
333 bool hasCopyDisposeHelpers);
Steve Naroff85eb17b2008-10-30 10:07:53 +0000334 Stmt *SynthesizeBlockCall(CallExpr *Exp);
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000335 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
336 const char *FunName);
337
338 void CollectBlockDeclRefInfo(BlockExpr *Exp);
339 void GetBlockCallExprs(Stmt *S);
340 void GetBlockDeclRefExprs(Stmt *S);
341
342 // We avoid calling Type::isBlockPointerType(), since it operates on the
343 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek0c97e042009-02-07 01:47:29 +0000344 bool isTopLevelBlockPointerType(QualType T) {
345 return isa<BlockPointerType>(T);
346 }
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000347
348 // FIXME: This predicate seems like it would be useful to add to ASTContext.
349 bool isObjCType(QualType T) {
350 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
351 return false;
352
353 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
354
355 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
356 OCT == Context->getCanonicalType(Context->getObjCClassType()))
357 return true;
358
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000359 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000360 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Naroffc75c1a82009-06-17 22:40:22 +0000361 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000362 return true;
363 }
364 return false;
365 }
366 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Ted Kremenek0c97e042009-02-07 01:47:29 +0000367 void GetExtentOfArgList(const char *Name, const char *&LParen,
368 const char *&RParen);
Steve Naroff7f1412d2008-11-03 23:29:32 +0000369 void RewriteCastExpr(CStyleCastExpr *CE);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +0000370
371 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Steve Naroff80c54752008-10-29 18:15:37 +0000372 Stmt *SynthBlockInitExpr(BlockExpr *Exp);
Steve Naroff450d2fc2009-04-29 16:37:50 +0000373
374 void QuoteDoublequotes(std::string &From, std::string &To) {
375 for(unsigned i = 0; i < From.length(); i++) {
376 if (From[i] == '"')
377 To += "\\\"";
378 else
379 To += From[i];
380 }
381 }
Chris Lattnerb429ae42007-10-11 00:43:27 +0000382 };
383}
384
Douglas Gregor4fa58902009-02-26 23:50:07 +0000385void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000386 NamedDecl *D) {
Douglas Gregor4fa58902009-02-26 23:50:07 +0000387 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
388 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000389 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroffd896f4b2008-12-11 21:05:33 +0000390 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000391 // All the args are checked/rewritten. Don't call twice!
392 RewriteBlockPointerDecl(D);
393 break;
394 }
395 }
396}
397
398void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000399 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000400 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor4fa58902009-02-26 23:50:07 +0000401 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000402}
403
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +0000404static bool IsHeaderFile(const std::string &Filename) {
405 std::string::size_type DotPos = Filename.rfind('.');
406
407 if (DotPos == std::string::npos) {
408 // no file extension
409 return false;
410 }
411
412 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
413 // C header: .h
414 // C++ header: .hh or .H;
415 return Ext == "h" || Ext == "hh" || Ext == "H";
416}
417
Eli Friedmana9c310842009-05-18 22:20:00 +0000418RewriteObjC::RewriteObjC(std::string inFile, llvm::raw_ostream* OS,
Eli Friedman35ba7a62009-05-18 22:39:16 +0000419 Diagnostic &D, const LangOptions &LOpts,
420 bool silenceMacroWarn)
421 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
422 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Naroffcfd9f4c2008-03-28 22:26:09 +0000423 IsHeader = IsHeaderFile(inFile);
Steve Naroffcfd9f4c2008-03-28 22:26:09 +0000424 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
425 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff43964fb2008-12-05 17:03:39 +0000426 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek0c97e042009-02-07 01:47:29 +0000427 "rewriter doesn't support user-specified control flow semantics "
428 "for @try/@finally (code may not execute properly)");
Steve Naroffcfd9f4c2008-03-28 22:26:09 +0000429}
430
Eli Friedman848763f2009-05-18 22:29:17 +0000431ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
432 llvm::raw_ostream* OS,
433 Diagnostic &Diags,
Eli Friedman35ba7a62009-05-18 22:39:16 +0000434 const LangOptions &LOpts,
435 bool SilenceRewriteMacroWarning) {
436 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattner258f26c2007-11-30 22:25:36 +0000437}
Chris Lattnerb429ae42007-10-11 00:43:27 +0000438
Steve Naroff44e81222008-04-14 22:03:09 +0000439void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner12499682008-01-31 19:38:44 +0000440 Context = &context;
441 SM = &Context->getSourceManager();
Argiris Kirtzidisd3586002008-04-17 14:40:12 +0000442 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner12499682008-01-31 19:38:44 +0000443 MsgSendFunctionDecl = 0;
444 MsgSendSuperFunctionDecl = 0;
445 MsgSendStretFunctionDecl = 0;
446 MsgSendSuperStretFunctionDecl = 0;
447 MsgSendFpretFunctionDecl = 0;
448 GetClassFunctionDecl = 0;
449 GetMetaClassFunctionDecl = 0;
450 SelGetUidFunctionDecl = 0;
451 CFStringFunctionDecl = 0;
Chris Lattner12499682008-01-31 19:38:44 +0000452 ConstantStringClassReference = 0;
453 NSStringRecord = 0;
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000454 CurMethodDef = 0;
455 CurFunctionDef = 0;
Steve Naroffedb4bc92008-12-09 12:56:34 +0000456 GlobalVarDecl = 0;
Chris Lattner12499682008-01-31 19:38:44 +0000457 SuperStructDecl = 0;
Steve Naroff450d2fc2009-04-29 16:37:50 +0000458 ProtocolTypeDecl = 0;
Steve Naroff053ae3f2008-03-27 22:59:54 +0000459 ConstantStringDecl = 0;
Chris Lattner12499682008-01-31 19:38:44 +0000460 BcLabelCount = 0;
Steve Naroffbec4bf52008-03-11 17:37:02 +0000461 SuperContructorFunctionDecl = 0;
Steve Naroff47e7fa22008-03-15 00:55:56 +0000462 NumObjCStringLiterals = 0;
Steve Naroffbad6f3b2008-12-08 20:01:41 +0000463 PropParentMap = 0;
464 CurrentBody = 0;
Steve Naroffedb4bc92008-12-09 12:56:34 +0000465 DisableReplaceStmt = false;
466
Chris Lattner12499682008-01-31 19:38:44 +0000467 // Get the ID and start/end of the main file.
468 MainFileID = SM->getMainFileID();
469 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
470 MainFileStart = MainBuf->getBufferStart();
471 MainFileEnd = MainBuf->getBufferEnd();
Steve Narofffef037c2008-03-27 22:29:16 +0000472
Chris Lattnere1be6022009-04-14 23:22:57 +0000473 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Steve Naroffde0da102008-03-10 23:16:54 +0000474
Chris Lattner12499682008-01-31 19:38:44 +0000475 // declaring objc_selector outside the parameter list removes a silly
476 // scope related warning...
Steve Narofffef037c2008-03-27 22:29:16 +0000477 if (IsHeader)
Steve Naroff08299f82009-02-03 20:39:18 +0000478 Preamble = "#pragma once\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000479 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff12673622008-12-23 20:11:22 +0000480 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Narofffef037c2008-03-27 22:29:16 +0000481 Preamble += "struct objc_object *superClass; ";
Steve Naroffbec4bf52008-03-11 17:37:02 +0000482 if (LangOpts.Microsoft) {
483 // Add a constructor for creating temporary objects.
Ted Kremenek0c97e042009-02-07 01:47:29 +0000484 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
485 ": ";
Steve Narofffef037c2008-03-27 22:29:16 +0000486 Preamble += "object(o), superClass(s) {} ";
Steve Naroffbec4bf52008-03-11 17:37:02 +0000487 }
Steve Narofffef037c2008-03-27 22:29:16 +0000488 Preamble += "};\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000489 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
490 Preamble += "typedef struct objc_object Protocol;\n";
491 Preamble += "#define _REWRITER_typedef_Protocol\n";
492 Preamble += "#endif\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000493 if (LangOpts.Microsoft) {
494 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
495 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
496 } else
497 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
498 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Narofffef037c2008-03-27 22:29:16 +0000499 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000500 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Narofffef037c2008-03-27 22:29:16 +0000501 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000502 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Narofffef037c2008-03-27 22:29:16 +0000503 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000504 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Narofffef037c2008-03-27 22:29:16 +0000505 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000506 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Narofffef037c2008-03-27 22:29:16 +0000507 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000508 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Narofffef037c2008-03-27 22:29:16 +0000509 Preamble += "(const char *);\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000510 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Narofffef037c2008-03-27 22:29:16 +0000511 Preamble += "(const char *);\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000512 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
513 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
514 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
515 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
516 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroff3e2c98c2008-05-09 21:17:56 +0000517 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroffcd25d782008-07-16 18:58:11 +0000518 // @synchronized hooks.
Steve Naroff1b208d72008-12-08 17:30:33 +0000519 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
520 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
521 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000522 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
523 Preamble += "struct __objcFastEnumerationState {\n\t";
524 Preamble += "unsigned long state;\n\t";
Steve Naroffc960e9d2008-04-04 22:58:22 +0000525 Preamble += "void **itemsPtr;\n\t";
Steve Narofffef037c2008-03-27 22:29:16 +0000526 Preamble += "unsigned long *mutationsPtr;\n\t";
527 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000528 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000529 Preamble += "#define __FASTENUMERATIONSTATE\n";
530 Preamble += "#endif\n";
531 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
532 Preamble += "struct __NSConstantStringImpl {\n";
533 Preamble += " int *isa;\n";
534 Preamble += " int flags;\n";
535 Preamble += " char *str;\n";
536 Preamble += " long length;\n";
537 Preamble += "};\n";
Steve Naroffc6e571e2008-08-05 20:04:48 +0000538 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
539 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
540 Preamble += "#else\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000541 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroffc6e571e2008-08-05 20:04:48 +0000542 Preamble += "#endif\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000543 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
544 Preamble += "#endif\n";
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000545 // Blocks preamble.
546 Preamble += "#ifndef BLOCK_IMPL\n";
547 Preamble += "#define BLOCK_IMPL\n";
548 Preamble += "struct __block_impl {\n";
549 Preamble += " void *isa;\n";
550 Preamble += " int Flags;\n";
551 Preamble += " int Size;\n";
552 Preamble += " void *FuncPtr;\n";
553 Preamble += "};\n";
Steve Naroff44fe1e32008-12-16 15:50:30 +0000554 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
555 Preamble += "__OBJC_RW_STATICIMPORT void _Block_object_assign(void *, const void *, const int);\n";
556 Preamble += "__OBJC_RW_STATICIMPORT void _Block_object_dispose(const void *, const int);\n";
557 Preamble += "__OBJC_RW_STATICIMPORT void *_NSConcreteGlobalBlock[32];\n";
558 Preamble += "__OBJC_RW_STATICIMPORT void *_NSConcreteStackBlock[32];\n";
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000559 Preamble += "#endif\n";
Steve Naroff39ba90e2008-10-27 18:50:14 +0000560 if (LangOpts.Microsoft) {
Steve Naroff1b208d72008-12-08 17:30:33 +0000561 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
562 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Steve Naroff39ba90e2008-10-27 18:50:14 +0000563 Preamble += "#define __attribute__(X)\n";
564 }
Chris Lattner12499682008-01-31 19:38:44 +0000565}
566
567
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000568//===----------------------------------------------------------------------===//
569// Top Level Driver Code
570//===----------------------------------------------------------------------===//
571
Chris Lattnera17991f2009-03-29 16:50:03 +0000572void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Chris Lattner74db1682007-10-16 21:07:07 +0000573 // Two cases: either the decl could be in the main file, or it could be in a
574 // #included file. If the former, rewrite it now. If the later, check to see
575 // if we rewrote the #include/#import.
576 SourceLocation Loc = D->getLocation();
Chris Lattner18c8dc02009-01-16 07:36:28 +0000577 Loc = SM->getInstantiationLoc(Loc);
Chris Lattner74db1682007-10-16 21:07:07 +0000578
579 // If this is for a builtin, ignore it.
580 if (Loc.isInvalid()) return;
581
Steve Naroffe9780582007-10-23 23:50:29 +0000582 // Look for built-in declarations that we need to refer during the rewrite.
583 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff02a82aa2007-10-30 23:14:51 +0000584 RewriteFunctionDecl(FD);
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000585 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroff0add5d22007-11-03 11:27:19 +0000586 // declared in <Foundation/NSString.h>
Chris Lattnerd120b9e2008-11-24 03:54:41 +0000587 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroff0add5d22007-11-03 11:27:19 +0000588 ConstantStringClassReference = FVD;
589 return;
590 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000591 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroff3774dd92007-10-26 20:53:56 +0000592 RewriteInterfaceDecl(MD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000593 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff667f1682007-10-30 13:30:57 +0000594 RewriteCategoryDecl(CD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000595 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000596 RewriteProtocolDecl(PD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000597 } else if (ObjCForwardProtocolDecl *FP =
598 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000599 RewriteForwardProtocolDecl(FP);
Douglas Gregor6e4fa2c2009-01-09 00:49:46 +0000600 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
601 // Recurse into linkage specifications
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000602 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
603 DIEnd = LSD->decls_end();
Douglas Gregor6e4fa2c2009-01-09 00:49:46 +0000604 DI != DIEnd; ++DI)
Chris Lattnera17991f2009-03-29 16:50:03 +0000605 HandleTopLevelSingleDecl(*DI);
Steve Naroffe9780582007-10-23 23:50:29 +0000606 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000607 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenek2450c262008-04-14 21:24:13 +0000608 if (SM->isFromMainFile(Loc))
Chris Lattner74db1682007-10-16 21:07:07 +0000609 return HandleDeclInMainFile(D);
Chris Lattner74db1682007-10-16 21:07:07 +0000610}
611
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000612//===----------------------------------------------------------------------===//
613// Syntactic (non-AST) Rewriting Code
614//===----------------------------------------------------------------------===//
615
Steve Naroff44e81222008-04-14 22:03:09 +0000616void RewriteObjC::RewriteInclude() {
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000617 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000618 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
619 const char *MainBufStart = MainBuf.first;
620 const char *MainBufEnd = MainBuf.second;
621 size_t ImportLen = strlen("import");
622 size_t IncludeLen = strlen("include");
623
Fariborz Jahanianc81ed742008-01-19 01:03:17 +0000624 // Loop over the whole file, looking for includes.
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000625 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
626 if (*BufPtr == '#') {
627 if (++BufPtr == MainBufEnd)
628 return;
629 while (*BufPtr == ' ' || *BufPtr == '\t')
630 if (++BufPtr == MainBufEnd)
631 return;
632 if (!strncmp(BufPtr, "import", ImportLen)) {
633 // replace import with include
634 SourceLocation ImportLoc =
635 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000636 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000637 BufPtr += ImportLen;
638 }
639 }
640 }
Chris Lattner74db1682007-10-16 21:07:07 +0000641}
642
Steve Naroff44e81222008-04-14 22:03:09 +0000643void RewriteObjC::RewriteTabs() {
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000644 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
645 const char *MainBufStart = MainBuf.first;
646 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian640a01f2007-10-18 19:23:00 +0000647
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000648 // Loop over the whole file, looking for tabs.
649 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
650 if (*BufPtr != '\t')
651 continue;
652
653 // Okay, we found a tab. This tab will turn into at least one character,
654 // but it depends on which 'virtual column' it is in. Compute that now.
655 unsigned VCol = 0;
656 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
657 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
658 ++VCol;
659
660 // Okay, now that we know the virtual column, we know how many spaces to
661 // insert. We assume 8-character tab-stops.
662 unsigned Spaces = 8-(VCol & 7);
663
664 // Get the location of the tab.
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000665 SourceLocation TabLoc = SM->getLocForStartOfFile(MainFileID);
666 TabLoc = TabLoc.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000667
668 // Rewrite the single tab character into a sequence of spaces.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000669 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000670 }
Chris Lattner569faa62007-10-11 18:38:32 +0000671}
672
Steve Naroff121ed222008-12-02 15:48:25 +0000673static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
674 ObjCIvarDecl *OID) {
675 std::string S;
676 S = "((struct ";
677 S += ClassDecl->getIdentifier()->getName();
678 S += "_IMPL *)self)->";
679 S += OID->getNameAsCString();
680 return S;
681}
682
Steve Naroffea6610f2008-12-02 17:36:43 +0000683void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
684 ObjCImplementationDecl *IMD,
685 ObjCCategoryImplDecl *CID) {
Steve Naroff110be842008-12-01 20:33:01 +0000686 SourceLocation startLoc = PID->getLocStart();
687 InsertText(startLoc, "// ", 3);
Steve Naroff121ed222008-12-02 15:48:25 +0000688 const char *startBuf = SM->getCharacterData(startLoc);
689 assert((*startBuf == '@') && "bogus @synthesize location");
690 const char *semiBuf = strchr(startBuf, ';');
691 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek0c97e042009-02-07 01:47:29 +0000692 SourceLocation onePastSemiLoc =
693 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroff121ed222008-12-02 15:48:25 +0000694
695 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
696 return; // FIXME: is this correct?
697
698 // Generate the 'getter' function.
Steve Naroff121ed222008-12-02 15:48:25 +0000699 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroff121ed222008-12-02 15:48:25 +0000700 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroff121ed222008-12-02 15:48:25 +0000701 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Steve Naroff1e7b7962008-12-02 16:05:55 +0000702
703 if (!OID)
704 return;
705
706 std::string Getr;
707 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
708 Getr += "{ ";
709 // Synthesize an explicit cast to gain access to the ivar.
Steve Naroff11671e72008-12-02 17:54:50 +0000710 // FIXME: deal with code generation implications for various property
711 // attributes (copy, retain, nonatomic).
712 // See objc-act.c:objc_synthesize_new_getter() for details.
Steve Naroff1e7b7962008-12-02 16:05:55 +0000713 Getr += "return " + getIvarAccessString(ClassDecl, OID);
714 Getr += "; }";
Steve Naroff121ed222008-12-02 15:48:25 +0000715 InsertText(onePastSemiLoc, Getr.c_str(), Getr.size());
Steve Naroff121ed222008-12-02 15:48:25 +0000716 if (PD->isReadOnly())
717 return;
718
719 // Generate the 'setter' function.
720 std::string Setr;
721 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroff121ed222008-12-02 15:48:25 +0000722 Setr += "{ ";
Steve Naroff1e7b7962008-12-02 16:05:55 +0000723 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff11671e72008-12-02 17:54:50 +0000724 // FIXME: deal with code generation implications for various property
725 // attributes (copy, retain, nonatomic).
Steve Narofff6ce8a12008-12-03 00:56:33 +0000726 // See objc-act.c:objc_synthesize_new_setter() for details.
Steve Naroff1e7b7962008-12-02 16:05:55 +0000727 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
Steve Naroff20f67392008-12-11 19:29:16 +0000728 Setr += PD->getNameAsCString();
Steve Naroff1e7b7962008-12-02 16:05:55 +0000729 Setr += "; }";
Steve Naroff121ed222008-12-02 15:48:25 +0000730 InsertText(onePastSemiLoc, Setr.c_str(), Setr.size());
Steve Naroff110be842008-12-01 20:33:01 +0000731}
Chris Lattner569faa62007-10-11 18:38:32 +0000732
Steve Naroff44e81222008-04-14 22:03:09 +0000733void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000734 // Get the start location and compute the semi location.
735 SourceLocation startLoc = ClassDecl->getLocation();
736 const char *startBuf = SM->getCharacterData(startLoc);
737 const char *semiPtr = strchr(startBuf, ';');
738
739 // Translate to typedef's that forward reference structs with the same name
740 // as the class. As a convenience, we include the original declaration
741 // as a comment.
742 std::string typedefString;
743 typedefString += "// ";
Steve Naroff71226032007-10-24 22:48:43 +0000744 typedefString.append(startBuf, semiPtr-startBuf+1);
745 typedefString += "\n";
Chris Lattner6a028742009-02-20 18:04:31 +0000746 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
747 I != E; ++I) {
748 ObjCInterfaceDecl *ForwardDecl = *I;
Steve Naroff2aeae312007-11-09 12:50:28 +0000749 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattner271d4c22008-11-24 05:29:24 +0000750 typedefString += ForwardDecl->getNameAsString();
Steve Naroff2aeae312007-11-09 12:50:28 +0000751 typedefString += "\n";
752 typedefString += "#define _REWRITER_typedef_";
Chris Lattner271d4c22008-11-24 05:29:24 +0000753 typedefString += ForwardDecl->getNameAsString();
Steve Naroff2aeae312007-11-09 12:50:28 +0000754 typedefString += "\n";
Steve Naroff4242b972007-11-05 14:36:37 +0000755 typedefString += "typedef struct objc_object ";
Chris Lattner271d4c22008-11-24 05:29:24 +0000756 typedefString += ForwardDecl->getNameAsString();
Steve Naroff2aeae312007-11-09 12:50:28 +0000757 typedefString += ";\n#endif\n";
Steve Naroff71226032007-10-24 22:48:43 +0000758 }
759
760 // Replace the @class with typedefs corresponding to the classes.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000761 ReplaceText(startLoc, semiPtr-startBuf+1,
762 typedefString.c_str(), typedefString.size());
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000763}
764
Steve Naroff44e81222008-04-14 22:03:09 +0000765void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff2ce399a2007-12-14 23:37:57 +0000766 SourceLocation LocStart = Method->getLocStart();
767 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff667f1682007-10-30 13:30:57 +0000768
Chris Lattner2d89c562009-02-04 01:06:56 +0000769 if (SM->getInstantiationLineNumber(LocEnd) >
770 SM->getInstantiationLineNumber(LocStart)) {
Steve Naroff99f50fe2008-10-21 13:37:27 +0000771 InsertText(LocStart, "#if 0\n", 6);
772 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff2ce399a2007-12-14 23:37:57 +0000773 } else {
Chris Lattner6216f292008-01-31 19:42:41 +0000774 InsertText(LocStart, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000775 }
776}
777
Steve Naroff56af2002009-01-11 01:06:09 +0000778void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop)
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000779{
Steve Naroff56af2002009-01-11 01:06:09 +0000780 SourceLocation Loc = prop->getLocation();
781
782 ReplaceText(Loc, 0, "// ", 3);
783
784 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000785}
786
Steve Naroff44e81222008-04-14 22:03:09 +0000787void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff667f1682007-10-30 13:30:57 +0000788 SourceLocation LocStart = CatDecl->getLocStart();
789
790 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000791 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000792
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000793 for (ObjCCategoryDecl::instmeth_iterator
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000794 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000795 I != E; ++I)
Steve Naroff2ce399a2007-12-14 23:37:57 +0000796 RewriteMethodDeclaration(*I);
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000797 for (ObjCCategoryDecl::classmeth_iterator
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000798 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000799 I != E; ++I)
Steve Naroff2ce399a2007-12-14 23:37:57 +0000800 RewriteMethodDeclaration(*I);
801
Steve Naroff667f1682007-10-30 13:30:57 +0000802 // Lastly, comment out the @end.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000803 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000804}
805
Steve Naroff44e81222008-04-14 22:03:09 +0000806void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000807 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000808
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000809 SourceLocation LocStart = PDecl->getLocStart();
810
811 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000812 ReplaceText(LocStart, 0, "// ", 3);
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000813
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000814 for (ObjCProtocolDecl::instmeth_iterator
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000815 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000816 I != E; ++I)
Steve Naroff2ce399a2007-12-14 23:37:57 +0000817 RewriteMethodDeclaration(*I);
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000818 for (ObjCProtocolDecl::classmeth_iterator
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000819 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000820 I != E; ++I)
Steve Naroff2ce399a2007-12-14 23:37:57 +0000821 RewriteMethodDeclaration(*I);
822
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000823 // Lastly, comment out the @end.
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000824 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000825 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff268fa592007-11-14 15:03:57 +0000826
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000827 // Must comment out @optional/@required
828 const char *startBuf = SM->getCharacterData(LocStart);
829 const char *endBuf = SM->getCharacterData(LocEnd);
830 for (const char *p = startBuf; p < endBuf; p++) {
831 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
832 std::string CommentedOptional = "/* @optional */";
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("@optional"),
835 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000836
837 }
838 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
839 std::string CommentedRequired = "/* @required */";
Steve Naroff268fa592007-11-14 15:03:57 +0000840 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000841 ReplaceText(OptionalLoc, strlen("@required"),
842 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000843
844 }
845 }
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000846}
847
Steve Naroff44e81222008-04-14 22:03:09 +0000848void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000849 SourceLocation LocStart = PDecl->getLocation();
Steve Naroff0540f3f2007-11-14 03:37:28 +0000850 if (LocStart.isInvalid())
851 assert(false && "Invalid SourceLocation");
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000852 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000853 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000854}
855
Steve Naroff44e81222008-04-14 22:03:09 +0000856void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000857 std::string &ResultStr) {
Steve Naroff6449c6c2008-10-30 12:09:33 +0000858 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroff91044cf2008-07-16 14:40:40 +0000859 const FunctionType *FPRetType = 0;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000860 ResultStr += "\nstatic ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000861 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000862 ResultStr += "id";
Steve Naroff20f67392008-12-11 19:29:16 +0000863 else if (OMD->getResultType()->isFunctionPointerType() ||
864 OMD->getResultType()->isBlockPointerType()) {
Steve Naroff91044cf2008-07-16 14:40:40 +0000865 // needs special handling, since pointer-to-functions have special
866 // syntax (where a decaration models use).
867 QualType retType = OMD->getResultType();
Steve Naroff20f67392008-12-11 19:29:16 +0000868 QualType PointeeTy;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000869 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Naroff20f67392008-12-11 19:29:16 +0000870 PointeeTy = PT->getPointeeType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000871 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Naroff20f67392008-12-11 19:29:16 +0000872 PointeeTy = BPT->getPointeeType();
873 if ((FPRetType = PointeeTy->getAsFunctionType())) {
874 ResultStr += FPRetType->getResultType().getAsString();
875 ResultStr += "(*";
Steve Naroff91044cf2008-07-16 14:40:40 +0000876 }
877 } else
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000878 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian7202d982008-01-10 01:39:52 +0000879 ResultStr += " ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000880
881 // Unique method name
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000882 std::string NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000883
Douglas Gregor5d764842009-01-09 17:18:27 +0000884 if (OMD->isInstanceMethod())
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000885 NameStr += "_I_";
886 else
887 NameStr += "_C_";
888
Chris Lattner271d4c22008-11-24 05:29:24 +0000889 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000890 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000891
Ted Kremenek42730c52008-01-07 19:49:32 +0000892 if (ObjCCategoryImplDecl *CID =
Steve Naroff438be772009-01-08 19:41:02 +0000893 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattner271d4c22008-11-24 05:29:24 +0000894 NameStr += CID->getNameAsString();
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000895 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000896 }
Steve Naroff5cb1e6e2008-04-04 22:23:44 +0000897 // Append selector names, replacing ':' with '_'
Chris Lattner3a8f2942008-11-24 03:33:13 +0000898 {
899 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000900 int len = selString.size();
901 for (int i = 0; i < len; i++)
902 if (selString[i] == ':')
903 selString[i] = '_';
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000904 NameStr += selString;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000905 }
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000906 // Remember this name for metadata emission
907 MethodInternalNames[OMD] = NameStr;
908 ResultStr += NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000909
910 // Rewrite arguments
911 ResultStr += "(";
912
913 // invisible arguments
Douglas Gregor5d764842009-01-09 17:18:27 +0000914 if (OMD->isInstanceMethod()) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000915 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000916 selfTy = Context->getPointerType(selfTy);
Steve Naroff60dfb6b2008-03-12 00:25:36 +0000917 if (!LangOpts.Microsoft) {
918 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
919 ResultStr += "struct ";
920 }
921 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattner271d4c22008-11-24 05:29:24 +0000922 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroffde0da102008-03-10 23:16:54 +0000923 ResultStr += " *";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000924 }
925 else
Steve Naroff450d2fc2009-04-29 16:37:50 +0000926 ResultStr += Context->getObjCClassType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000927
928 ResultStr += " self, ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000929 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000930 ResultStr += " _cmd";
931
932 // Method arguments.
Chris Lattner5c6b2c62009-02-20 18:43:26 +0000933 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
934 E = OMD->param_end(); PI != E; ++PI) {
935 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000936 ResultStr += ", ";
Steve Naroff133dfda2008-04-18 21:13:19 +0000937 if (PDecl->getType()->isObjCQualifiedIdType()) {
938 ResultStr += "id ";
Chris Lattner271d4c22008-11-24 05:29:24 +0000939 ResultStr += PDecl->getNameAsString();
Steve Naroff133dfda2008-04-18 21:13:19 +0000940 } else {
Chris Lattner271d4c22008-11-24 05:29:24 +0000941 std::string Name = PDecl->getNameAsString();
Steve Naroffd896f4b2008-12-11 21:05:33 +0000942 if (isTopLevelBlockPointerType(PDecl->getType())) {
Steve Naroff4e2ae512008-10-30 14:45:29 +0000943 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000944 const BlockPointerType *BPT = PDecl->getType()->getAs<BlockPointerType>();
Douglas Gregor3bf3bbc2009-05-29 20:38:28 +0000945 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name,
946 Context->PrintingPolicy);
Steve Naroff4e2ae512008-10-30 14:45:29 +0000947 } else
Douglas Gregor3bf3bbc2009-05-29 20:38:28 +0000948 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroff133dfda2008-04-18 21:13:19 +0000949 ResultStr += Name;
950 }
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000951 }
Fariborz Jahanian2fab94e2008-01-21 20:14:23 +0000952 if (OMD->isVariadic())
953 ResultStr += ", ...";
Fariborz Jahanian7202d982008-01-10 01:39:52 +0000954 ResultStr += ") ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000955
Steve Naroff91044cf2008-07-16 14:40:40 +0000956 if (FPRetType) {
957 ResultStr += ")"; // close the precedence "scope" for "*".
958
959 // Now, emit the argument types (if any).
Douglas Gregor4fa58902009-02-26 23:50:07 +0000960 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff91044cf2008-07-16 14:40:40 +0000961 ResultStr += "(";
962 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
963 if (i) ResultStr += ", ";
964 std::string ParamStr = FT->getArgType(i).getAsString();
965 ResultStr += ParamStr;
966 }
967 if (FT->isVariadic()) {
968 if (FT->getNumArgs()) ResultStr += ", ";
969 ResultStr += "...";
970 }
971 ResultStr += ")";
972 } else {
973 ResultStr += "()";
974 }
975 }
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000976}
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000977void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000978 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
979 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000980
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000981 if (IMD)
Chris Lattner6216f292008-01-31 19:42:41 +0000982 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000983 else
Chris Lattner6216f292008-01-31 19:42:41 +0000984 InsertText(CID->getLocStart(), "// ", 3);
Steve Naroff21658f62008-11-13 20:07:04 +0000985
Ted Kremenek42730c52008-01-07 19:49:32 +0000986 for (ObjCCategoryImplDecl::instmeth_iterator
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000987 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
988 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregorcd19b572009-04-23 01:02:12 +0000989 I != E; ++I) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000990 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000991 ObjCMethodDecl *OMD = *I;
992 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000993 SourceLocation LocStart = OMD->getLocStart();
Argiris Kirtzidisccb9efe2009-06-30 02:35:26 +0000994 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redlbc9ef252009-04-26 20:35:05 +0000995
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000996 const char *startBuf = SM->getCharacterData(LocStart);
997 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000998 ReplaceText(LocStart, endBuf-startBuf,
999 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +00001000 }
1001
Ted Kremenek42730c52008-01-07 19:49:32 +00001002 for (ObjCCategoryImplDecl::classmeth_iterator
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001003 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1004 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregorcd19b572009-04-23 01:02:12 +00001005 I != E; ++I) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +00001006 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +00001007 ObjCMethodDecl *OMD = *I;
1008 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +00001009 SourceLocation LocStart = OMD->getLocStart();
Argiris Kirtzidisccb9efe2009-06-30 02:35:26 +00001010 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +00001011
1012 const char *startBuf = SM->getCharacterData(LocStart);
1013 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001014 ReplaceText(LocStart, endBuf-startBuf,
1015 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +00001016 }
Steve Naroff110be842008-12-01 20:33:01 +00001017 for (ObjCCategoryImplDecl::propimpl_iterator
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001018 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1019 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregorcd19b572009-04-23 01:02:12 +00001020 I != E; ++I) {
Steve Naroffea6610f2008-12-02 17:36:43 +00001021 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroff110be842008-12-01 20:33:01 +00001022 }
1023
Fariborz Jahanian0136e372007-11-13 20:04:28 +00001024 if (IMD)
Chris Lattner6216f292008-01-31 19:42:41 +00001025 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian0136e372007-11-13 20:04:28 +00001026 else
Chris Lattner6216f292008-01-31 19:42:41 +00001027 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +00001028}
1029
Steve Naroff44e81222008-04-14 22:03:09 +00001030void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffef20ed32007-10-30 02:23:23 +00001031 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +00001032 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff77d081b2007-11-01 03:35:41 +00001033 // we haven't seen a forward decl - generate a typedef.
Steve Naroff2adead72007-11-14 23:02:56 +00001034 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattner271d4c22008-11-24 05:29:24 +00001035 ResultStr += ClassDecl->getNameAsString();
Steve Naroff2aeae312007-11-09 12:50:28 +00001036 ResultStr += "\n";
1037 ResultStr += "#define _REWRITER_typedef_";
Chris Lattner271d4c22008-11-24 05:29:24 +00001038 ResultStr += ClassDecl->getNameAsString();
Steve Naroff2aeae312007-11-09 12:50:28 +00001039 ResultStr += "\n";
Steve Naroffde0da102008-03-10 23:16:54 +00001040 ResultStr += "typedef struct objc_object ";
Chris Lattner271d4c22008-11-24 05:29:24 +00001041 ResultStr += ClassDecl->getNameAsString();
Steve Naroff2aeae312007-11-09 12:50:28 +00001042 ResultStr += ";\n#endif\n";
Steve Naroff77d081b2007-11-01 03:35:41 +00001043 // Mark this typedef as having been generated.
Ted Kremenek42730c52008-01-07 19:49:32 +00001044 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff77d081b2007-11-01 03:35:41 +00001045 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001046 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Naroffef20ed32007-10-30 02:23:23 +00001047
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001048 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
1049 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff56af2002009-01-11 01:06:09 +00001050 RewriteProperty(*I);
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001051 for (ObjCInterfaceDecl::instmeth_iterator
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001052 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001053 I != E; ++I)
Steve Naroff2ce399a2007-12-14 23:37:57 +00001054 RewriteMethodDeclaration(*I);
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001055 for (ObjCInterfaceDecl::classmeth_iterator
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001056 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001057 I != E; ++I)
Steve Naroff2ce399a2007-12-14 23:37:57 +00001058 RewriteMethodDeclaration(*I);
1059
Steve Naroff1ccf4632007-10-30 03:43:13 +00001060 // Lastly, comment out the @end.
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001061 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff3774dd92007-10-26 20:53:56 +00001062}
1063
Steve Naroffedb4bc92008-12-09 12:56:34 +00001064Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1065 SourceRange SrcRange) {
Steve Naroff0e948412008-12-04 16:24:46 +00001066 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1067 // This allows us to reuse all the fun and games in SynthMessageExpr().
1068 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1069 ObjCMessageExpr *MsgExpr;
1070 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1071 llvm::SmallVector<Expr *, 1> ExprVec;
1072 ExprVec.push_back(newStmt);
1073
Steve Narofffbed6802008-12-08 16:43:47 +00001074 Stmt *Receiver = PropRefExpr->getBase();
1075 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1076 if (PRE && PropGetters[PRE]) {
1077 // This allows us to handle chain/nested property getters.
1078 Receiver = PropGetters[PRE];
1079 }
Ted Kremenek0c97e042009-02-07 01:47:29 +00001080 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
Steve Naroff0e948412008-12-04 16:24:46 +00001081 PDecl->getSetterName(), PDecl->getType(),
1082 PDecl->getSetterMethodDecl(),
1083 SourceLocation(), SourceLocation(),
1084 &ExprVec[0], 1);
1085 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
1086
1087 // Now do the actual rewrite.
Steve Naroffedb4bc92008-12-09 12:56:34 +00001088 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroff478f7382008-12-10 14:53:27 +00001089 //delete BinOp;
Ted Kremenek0c97e042009-02-07 01:47:29 +00001090 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1091 // to things that stay around.
1092 Context->Deallocate(MsgExpr);
Steve Naroff0e948412008-12-04 16:24:46 +00001093 return ReplacingStmt;
Steve Narofff6ce8a12008-12-03 00:56:33 +00001094}
1095
Steve Naroff0e948412008-12-04 16:24:46 +00001096Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Narofff6ce8a12008-12-03 00:56:33 +00001097 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1098 // This allows us to reuse all the fun and games in SynthMessageExpr().
1099 ObjCMessageExpr *MsgExpr;
1100 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1101
Steve Narofffbed6802008-12-08 16:43:47 +00001102 Stmt *Receiver = PropRefExpr->getBase();
1103
1104 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1105 if (PRE && PropGetters[PRE]) {
1106 // This allows us to handle chain/nested property getters.
1107 Receiver = PropGetters[PRE];
1108 }
Ted Kremenek0c97e042009-02-07 01:47:29 +00001109 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
Steve Narofff6ce8a12008-12-03 00:56:33 +00001110 PDecl->getGetterName(), PDecl->getType(),
1111 PDecl->getGetterMethodDecl(),
1112 SourceLocation(), SourceLocation(),
1113 0, 0);
1114
Steve Naroff102c3f22008-12-04 23:50:32 +00001115 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Narofffbed6802008-12-08 16:43:47 +00001116
1117 if (!PropParentMap)
1118 PropParentMap = new ParentMap(CurrentBody);
1119
1120 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1121 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1122 // We stash away the ReplacingStmt since actually doing the
1123 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1124 PropGetters[PropRefExpr] = ReplacingStmt;
Ted Kremenek0c97e042009-02-07 01:47:29 +00001125 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1126 // to things that stay around.
1127 Context->Deallocate(MsgExpr);
Steve Narofffbed6802008-12-08 16:43:47 +00001128 return PropRefExpr; // return the original...
1129 } else {
1130 ReplaceStmt(PropRefExpr, ReplacingStmt);
Ted Kremenek0c97e042009-02-07 01:47:29 +00001131 // delete PropRefExpr; elsewhere...
1132 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1133 // to things that stay around.
1134 Context->Deallocate(MsgExpr);
Steve Narofffbed6802008-12-08 16:43:47 +00001135 return ReplacingStmt;
1136 }
Steve Narofff6ce8a12008-12-03 00:56:33 +00001137}
1138
Chris Lattner343c82b2008-05-23 20:40:52 +00001139Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
1140 SourceLocation OrigStart) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001141 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00001142 if (CurMethodDef) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001143 if (const PointerType *pType = IV->getBase()->getType()->getAs<PointerType>()) {
Ted Kremenek0c97e042009-02-07 01:47:29 +00001144 ObjCInterfaceType *iFaceDecl =
1145 dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroffa9636222008-05-08 17:52:16 +00001146 // lookup which class implements the instance variable.
1147 ObjCInterfaceDecl *clsDeclared = 0;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001148 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001149 clsDeclared);
Steve Naroffa9636222008-05-08 17:52:16 +00001150 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1151
1152 // Synthesize an explicit cast to gain access to the ivar.
1153 std::string RecName = clsDeclared->getIdentifier()->getName();
1154 RecName += "_IMPL";
1155 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001156 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek2c984042008-09-05 01:34:33 +00001157 SourceLocation(), II);
Steve Naroffa9636222008-05-08 17:52:16 +00001158 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1159 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Anders Carlsson7ef181c2009-07-31 00:48:10 +00001160 CastExpr *castExpr = new (Context) CStyleCastExpr(castT,
1161 CastExpr::CK_Unknown,
1162 IV->getBase(),
1163 castT,SourceLocation(),
1164 SourceLocation());
Steve Naroffa9636222008-05-08 17:52:16 +00001165 // Don't forget the parens to enforce the proper binding.
Ted Kremenek0c97e042009-02-07 01:47:29 +00001166 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1167 IV->getBase()->getLocEnd(),
1168 castExpr);
Steve Naroffa9636222008-05-08 17:52:16 +00001169 if (IV->isFreeIvar() &&
Steve Naroff38a9e3f2008-10-27 17:20:55 +00001170 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek0c97e042009-02-07 01:47:29 +00001171 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1172 IV->getLocation(),
1173 D->getType());
Steve Naroffa9636222008-05-08 17:52:16 +00001174 ReplaceStmt(IV, ME);
Steve Naroff102c3f22008-12-04 23:50:32 +00001175 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffa9636222008-05-08 17:52:16 +00001176 return ME;
Steve Naroff292b7b92007-11-15 11:33:00 +00001177 }
Chris Lattner343c82b2008-05-23 20:40:52 +00001178
1179 ReplaceStmt(IV->getBase(), PE);
1180 // Cannot delete IV->getBase(), since PE points to it.
1181 // Replace the old base with the cast. This is important when doing
1182 // embedded rewrites. For example, [newInv->_container addObject:0].
1183 IV->setBase(PE);
1184 return IV;
Steve Naroff292b7b92007-11-15 11:33:00 +00001185 }
Steve Naroffe6155362008-04-18 21:55:08 +00001186 } else { // we are outside a method.
Steve Naroffd8d30b92008-05-06 23:20:07 +00001187 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
1188
1189 // Explicit ivar refs need to have a cast inserted.
1190 // FIXME: consider sharing some of this code with the code above.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001191 if (const PointerType *pType = IV->getBase()->getType()->getAs<PointerType>()) {
Steve Naroffa9636222008-05-08 17:52:16 +00001192 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroffd8d30b92008-05-06 23:20:07 +00001193 // lookup which class implements the instance variable.
1194 ObjCInterfaceDecl *clsDeclared = 0;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001195 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001196 clsDeclared);
Steve Naroffd8d30b92008-05-06 23:20:07 +00001197 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1198
1199 // Synthesize an explicit cast to gain access to the ivar.
1200 std::string RecName = clsDeclared->getIdentifier()->getName();
1201 RecName += "_IMPL";
1202 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001203 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek2c984042008-09-05 01:34:33 +00001204 SourceLocation(), II);
Steve Naroffd8d30b92008-05-06 23:20:07 +00001205 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1206 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Anders Carlsson7ef181c2009-07-31 00:48:10 +00001207 CastExpr *castExpr = new (Context) CStyleCastExpr(castT,
1208 CastExpr::CK_Unknown,
1209 IV->getBase(),
Ted Kremenek0c97e042009-02-07 01:47:29 +00001210 castT, SourceLocation(),
1211 SourceLocation());
Steve Naroffd8d30b92008-05-06 23:20:07 +00001212 // Don't forget the parens to enforce the proper binding.
Ted Kremenek0c97e042009-02-07 01:47:29 +00001213 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner3cca6612008-05-28 16:38:23 +00001214 IV->getBase()->getLocEnd(), castExpr);
Steve Naroffd8d30b92008-05-06 23:20:07 +00001215 ReplaceStmt(IV->getBase(), PE);
1216 // Cannot delete IV->getBase(), since PE points to it.
1217 // Replace the old base with the cast. This is important when doing
1218 // embedded rewrites. For example, [newInv->_container addObject:0].
1219 IV->setBase(PE);
1220 return IV;
1221 }
Steve Naroff292b7b92007-11-15 11:33:00 +00001222 }
Steve Naroffe6155362008-04-18 21:55:08 +00001223 return IV;
Steve Naroff6b759ce2007-11-15 02:58:25 +00001224}
1225
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001226/// SynthCountByEnumWithState - To print:
1227/// ((unsigned int (*)
1228/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1229/// (void *)objc_msgSend)((id)l_collection,
1230/// sel_registerName(
1231/// "countByEnumeratingWithState:objects:count:"),
1232/// &enumState,
1233/// (id *)items, (unsigned int)16)
1234///
Steve Naroff44e81222008-04-14 22:03:09 +00001235void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001236 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1237 "id *, unsigned int))(void *)objc_msgSend)";
1238 buf += "\n\t\t";
1239 buf += "((id)l_collection,\n\t\t";
1240 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1241 buf += "\n\t\t";
1242 buf += "&enumState, "
1243 "(id *)items, (unsigned int)16)";
1244}
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001245
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001246/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1247/// statement to exit to its outer synthesized loop.
1248///
Steve Naroff44e81222008-04-14 22:03:09 +00001249Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001250 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1251 return S;
1252 // replace break with goto __break_label
1253 std::string buf;
1254
1255 SourceLocation startLoc = S->getLocStart();
1256 buf = "goto __break_label_";
1257 buf += utostr(ObjCBcLabelNo.back());
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001258 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001259
1260 return 0;
1261}
1262
1263/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1264/// statement to continue with its inner synthesized loop.
1265///
Steve Naroff44e81222008-04-14 22:03:09 +00001266Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001267 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1268 return S;
1269 // replace continue with goto __continue_label
1270 std::string buf;
1271
1272 SourceLocation startLoc = S->getLocStart();
1273 buf = "goto __continue_label_";
1274 buf += utostr(ObjCBcLabelNo.back());
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001275 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001276
1277 return 0;
1278}
1279
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001280/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001281/// It rewrites:
1282/// for ( type elem in collection) { stmts; }
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00001283
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001284/// Into:
1285/// {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001286/// type elem;
1287/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001288/// id items[16];
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001289/// id l_collection = (id)collection;
1290/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1291/// objects:items count:16];
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001292/// if (limit) {
1293/// unsigned long startMutations = *enumState.mutationsPtr;
1294/// do {
1295/// unsigned long counter = 0;
1296/// do {
1297/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001298/// objc_enumerationMutation(l_collection);
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001299/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001300/// stmts;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001301/// __continue_label: ;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001302/// } while (counter < limit);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001303/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1304/// objects:items count:16]);
1305/// elem = nil;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001306/// __break_label: ;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001307/// }
1308/// else
1309/// elem = nil;
1310/// }
1311///
Steve Naroff44e81222008-04-14 22:03:09 +00001312Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner2c022162008-01-31 05:10:40 +00001313 SourceLocation OrigEnd) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001314 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1315 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1316 "ObjCForCollectionStmt Statement stack mismatch");
1317 assert(!ObjCBcLabelNo.empty() &&
1318 "ObjCForCollectionStmt - Label No stack empty");
1319
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001320 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001321 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001322 const char *elementName;
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001323 std::string elementTypeAsString;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001324 std::string buf;
1325 buf = "\n{\n\t";
1326 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1327 // type elem;
Chris Lattner4a9a85e2009-03-28 06:33:19 +00001328 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek91a2bd32008-10-06 22:16:13 +00001329 QualType ElementType = cast<ValueDecl>(D)->getType();
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001330 elementTypeAsString = ElementType.getAsString();
1331 buf += elementTypeAsString;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001332 buf += " ";
Chris Lattnerd120b9e2008-11-24 03:54:41 +00001333 elementName = D->getNameAsCString();
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001334 buf += elementName;
1335 buf += ";\n\t";
1336 }
Chris Lattner690c2872008-04-08 05:52:18 +00001337 else {
1338 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattnerd120b9e2008-11-24 03:54:41 +00001339 elementName = DR->getDecl()->getNameAsCString();
Douglas Gregord2baafd2008-10-21 16:13:35 +00001340 elementTypeAsString
1341 = cast<ValueDecl>(DR->getDecl())->getType().getAsString();
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001342 }
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001343
1344 // struct __objcFastEnumerationState enumState = { 0 };
1345 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1346 // id items[16];
1347 buf += "id items[16];\n\t";
1348 // id l_collection = (id)
1349 buf += "id l_collection = (id)";
Fariborz Jahaniandf2b0952008-01-10 00:24:29 +00001350 // Find start location of 'collection' the hard way!
1351 const char *startCollectionBuf = startBuf;
1352 startCollectionBuf += 3; // skip 'for'
1353 startCollectionBuf = strchr(startCollectionBuf, '(');
1354 startCollectionBuf++; // skip '('
1355 // find 'in' and skip it.
1356 while (*startCollectionBuf != ' ' ||
1357 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1358 (*(startCollectionBuf+3) != ' ' &&
1359 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1360 startCollectionBuf++;
1361 startCollectionBuf += 3;
1362
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001363 // Replace: "for (type element in" with string constructed thus far.
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001364 ReplaceText(startLoc, startCollectionBuf - startBuf,
1365 buf.c_str(), buf.size());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001366 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahaniandf2b0952008-01-10 00:24:29 +00001367 SourceLocation rightParenLoc = S->getRParenLoc();
1368 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1369 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001370 buf = ";\n\t";
1371
1372 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1373 // objects:items count:16];
1374 // which is synthesized into:
1375 // unsigned int limit =
1376 // ((unsigned int (*)
1377 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1378 // (void *)objc_msgSend)((id)l_collection,
1379 // sel_registerName(
1380 // "countByEnumeratingWithState:objects:count:"),
1381 // (struct __objcFastEnumerationState *)&state,
1382 // (id *)items, (unsigned int)16);
1383 buf += "unsigned long limit =\n\t\t";
1384 SynthCountByEnumWithState(buf);
1385 buf += ";\n\t";
1386 /// if (limit) {
1387 /// unsigned long startMutations = *enumState.mutationsPtr;
1388 /// do {
1389 /// unsigned long counter = 0;
1390 /// do {
1391 /// if (startMutations != *enumState.mutationsPtr)
1392 /// objc_enumerationMutation(l_collection);
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001393 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001394 buf += "if (limit) {\n\t";
1395 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1396 buf += "do {\n\t\t";
1397 buf += "unsigned long counter = 0;\n\t\t";
1398 buf += "do {\n\t\t\t";
1399 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1400 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1401 buf += elementName;
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001402 buf += " = (";
1403 buf += elementTypeAsString;
1404 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001405 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001406 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001407
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001408 /// __continue_label: ;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001409 /// } while (counter < limit);
1410 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1411 /// objects:items count:16]);
1412 /// elem = nil;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001413 /// __break_label: ;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001414 /// }
1415 /// else
1416 /// elem = nil;
1417 /// }
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001418 ///
1419 buf = ";\n\t";
1420 buf += "__continue_label_";
1421 buf += utostr(ObjCBcLabelNo.back());
1422 buf += ": ;";
1423 buf += "\n\t\t";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001424 buf += "} while (counter < limit);\n\t";
1425 buf += "} while (limit = ";
1426 SynthCountByEnumWithState(buf);
1427 buf += ");\n\t";
1428 buf += elementName;
Steve Naroffa9dc0262008-12-17 14:24:39 +00001429 buf += " = ((id)0);\n\t";
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001430 buf += "__break_label_";
1431 buf += utostr(ObjCBcLabelNo.back());
1432 buf += ": ;\n\t";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001433 buf += "}\n\t";
1434 buf += "else\n\t\t";
1435 buf += elementName;
Steve Naroffa9dc0262008-12-17 14:24:39 +00001436 buf += " = ((id)0);\n";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001437 buf += "}\n";
Steve Naroff5f238fe2008-07-21 18:26:02 +00001438
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001439 // Insert all these *after* the statement body.
Sebastian Redlbc9ef252009-04-26 20:35:05 +00001440 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Naroff5f238fe2008-07-21 18:26:02 +00001441 if (isa<CompoundStmt>(S->getBody())) {
1442 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1443 InsertText(endBodyLoc, buf.c_str(), buf.size());
1444 } else {
1445 /* Need to treat single statements specially. For example:
1446 *
1447 * for (A *a in b) if (stuff()) break;
1448 * for (A *a in b) xxxyy;
1449 *
1450 * The following code simply scans ahead to the semi to find the actual end.
1451 */
1452 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1453 const char *semiBuf = strchr(stmtBuf, ';');
1454 assert(semiBuf && "Can't find ';'");
1455 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1456 InsertText(endBodyLoc, buf.c_str(), buf.size());
1457 }
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001458 Stmts.pop_back();
1459 ObjCBcLabelNo.pop_back();
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001460 return 0;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001461}
1462
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001463/// RewriteObjCSynchronizedStmt -
1464/// This routine rewrites @synchronized(expr) stmt;
1465/// into:
1466/// objc_sync_enter(expr);
1467/// @try stmt @finally { objc_sync_exit(expr); }
1468///
Steve Naroff44e81222008-04-14 22:03:09 +00001469Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001470 // Get the start location and compute the semi location.
1471 SourceLocation startLoc = S->getLocStart();
1472 const char *startBuf = SM->getCharacterData(startLoc);
1473
1474 assert((*startBuf == '@') && "bogus @synchronized location");
1475
1476 std::string buf;
Steve Naroffc1656a62008-08-21 13:03:03 +00001477 buf = "objc_sync_enter((id)";
1478 const char *lparenBuf = startBuf;
1479 while (*lparenBuf != '(') lparenBuf++;
1480 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Steve Naroff027cd0b2008-08-19 13:04:19 +00001481 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1482 // the sync expression is typically a message expression that's already
1483 // been rewritten! (which implies the SourceLocation's are invalid).
1484 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001485 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroff027cd0b2008-08-19 13:04:19 +00001486 while (*endBuf != ')') endBuf--;
1487 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001488 buf = ");\n";
1489 // declare a new scope with two variables, _stack and _rethrow.
1490 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1491 buf += "int buf[18/*32-bit i386*/];\n";
1492 buf += "char *pointers[4];} _stack;\n";
1493 buf += "id volatile _rethrow = 0;\n";
1494 buf += "objc_exception_try_enter(&_stack);\n";
1495 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001496 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001497 startLoc = S->getSynchBody()->getLocEnd();
1498 startBuf = SM->getCharacterData(startLoc);
1499
Steve Naroff027cd0b2008-08-19 13:04:19 +00001500 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001501 SourceLocation lastCurlyLoc = startLoc;
1502 buf = "}\nelse {\n";
1503 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroff450d2fc2009-04-29 16:37:50 +00001504 buf += "}\n";
1505 buf += "{ /* implicit finally clause */\n";
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001506 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroff17919b52008-07-16 19:47:39 +00001507 buf += " objc_sync_exit(";
Ted Kremenek0c97e042009-02-07 01:47:29 +00001508 Expr *syncExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlsson7ef181c2009-07-31 00:48:10 +00001509 CastExpr::CK_Unknown,
Ted Kremenek0c97e042009-02-07 01:47:29 +00001510 S->getSynchExpr(),
1511 Context->getObjCIdType(),
1512 SourceLocation(),
1513 SourceLocation());
Ted Kremenek7b6f67b2008-09-13 05:16:45 +00001514 std::string syncExprBufS;
1515 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattner7099c782009-06-30 01:26:17 +00001516 syncExpr->printPretty(syncExprBuf, *Context, 0,
1517 PrintingPolicy(LangOpts));
Steve Naroff17919b52008-07-16 19:47:39 +00001518 buf += syncExprBuf.str();
1519 buf += ");\n";
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001520 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1521 buf += "}\n";
1522 buf += "}";
1523
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001524 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001525 return 0;
1526}
1527
Steve Naroff43964fb2008-12-05 17:03:39 +00001528void RewriteObjC::WarnAboutReturnGotoContinueOrBreakStmts(Stmt *S) {
1529 // Perform a bottom up traversal of all children.
1530 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1531 CI != E; ++CI)
1532 if (*CI)
1533 WarnAboutReturnGotoContinueOrBreakStmts(*CI);
1534
1535 if (isa<ReturnStmt>(S) || isa<ContinueStmt>(S) ||
1536 isa<BreakStmt>(S) || isa<GotoStmt>(S)) {
1537 Diags.Report(Context->getFullLoc(S->getLocStart()),
1538 TryFinallyContainsReturnDiag);
1539 }
1540 return;
1541}
1542
Steve Naroff44e81222008-04-14 22:03:09 +00001543Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001544 // Get the start location and compute the semi location.
1545 SourceLocation startLoc = S->getLocStart();
1546 const char *startBuf = SM->getCharacterData(startLoc);
1547
1548 assert((*startBuf == '@') && "bogus @try location");
1549
1550 std::string buf;
1551 // declare a new scope with two variables, _stack and _rethrow.
1552 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1553 buf += "int buf[18/*32-bit i386*/];\n";
1554 buf += "char *pointers[4];} _stack;\n";
1555 buf += "id volatile _rethrow = 0;\n";
1556 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +00001557 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffe9f69842007-11-07 04:08:17 +00001558
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001559 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001560
1561 startLoc = S->getTryBody()->getLocEnd();
1562 startBuf = SM->getCharacterData(startLoc);
1563
1564 assert((*startBuf == '}') && "bogus @try block");
Steve Naroff9d0ff352008-07-16 15:31:30 +00001565
Steve Naroffe9f69842007-11-07 04:08:17 +00001566 SourceLocation lastCurlyLoc = startLoc;
Steve Naroff9d0ff352008-07-16 15:31:30 +00001567 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1568 if (catchList) {
1569 startLoc = startLoc.getFileLocWithOffset(1);
1570 buf = " /* @catch begin */ else {\n";
1571 buf += " id _caught = objc_exception_extract(&_stack);\n";
1572 buf += " objc_exception_try_enter (&_stack);\n";
1573 buf += " if (_setjmp(_stack.buf))\n";
1574 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1575 buf += " else { /* @catch continue */";
1576
1577 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff36269d22008-09-09 19:59:12 +00001578 } else { /* no catch list */
1579 buf = "}\nelse {\n";
1580 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1581 buf += "}";
1582 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroff9d0ff352008-07-16 15:31:30 +00001583 }
Steve Naroffe9f69842007-11-07 04:08:17 +00001584 bool sawIdTypedCatch = false;
1585 Stmt *lastCatchBody = 0;
Steve Naroffe9f69842007-11-07 04:08:17 +00001586 while (catchList) {
Steve Naroff0e8b96a2009-03-03 19:52:17 +00001587 ParmVarDecl *catchDecl = catchList->getCatchParamDecl();
Steve Naroffe9f69842007-11-07 04:08:17 +00001588
1589 if (catchList == S->getCatchStmts())
1590 buf = "if ("; // we are generating code for the first catch clause
1591 else
1592 buf = "else if (";
1593 startLoc = catchList->getLocStart();
1594 startBuf = SM->getCharacterData(startLoc);
1595
1596 assert((*startBuf == '@') && "bogus @catch location");
1597
1598 const char *lParenLoc = strchr(startBuf, '(');
1599
Steve Naroff397c4ce2008-02-01 22:08:12 +00001600 if (catchList->hasEllipsis()) {
Steve Naroff929c77e2008-02-01 20:02:07 +00001601 // Now rewrite the body...
1602 lastCatchBody = catchList->getCatchBody();
Steve Naroff929c77e2008-02-01 20:02:07 +00001603 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1604 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner690c2872008-04-08 05:52:18 +00001605 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1606 "bogus @catch paren location");
Steve Naroff929c77e2008-02-01 20:02:07 +00001607 assert((*bodyBuf == '{') && "bogus @catch body location");
1608
1609 buf += "1) { id _tmp = _caught;";
Daniel Dunbar60987c92009-08-19 19:10:30 +00001610 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff0e8b96a2009-03-03 19:52:17 +00001611 } else if (catchDecl) {
1612 QualType t = catchDecl->getType();
Ted Kremenek42730c52008-01-07 19:49:32 +00001613 if (t == Context->getObjCIdType()) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001614 buf += "1) { ";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001615 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001616 sawIdTypedCatch = true;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001617 } else if (const PointerType *pType = t->getAs<PointerType>()) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001618 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroffe9f69842007-11-07 04:08:17 +00001619
Ted Kremenek42730c52008-01-07 19:49:32 +00001620 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroffe9f69842007-11-07 04:08:17 +00001621 if (cls) {
Steve Naroffd3287d82007-11-07 18:43:40 +00001622 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattner271d4c22008-11-24 05:29:24 +00001623 buf += cls->getDecl()->getNameAsString();
Steve Naroffd3287d82007-11-07 18:43:40 +00001624 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001625 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001626 }
1627 }
1628 // Now rewrite the body...
1629 lastCatchBody = catchList->getCatchBody();
1630 SourceLocation rParenLoc = catchList->getRParenLoc();
1631 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1632 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1633 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1634 assert((*rParenBuf == ')') && "bogus @catch paren location");
1635 assert((*bodyBuf == '{') && "bogus @catch body location");
1636
1637 buf = " = _caught;";
1638 // Here we replace ") {" with "= _caught;" (which initializes and
1639 // declares the @catch parameter).
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001640 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff0e8b96a2009-03-03 19:52:17 +00001641 } else {
Steve Naroffe9f69842007-11-07 04:08:17 +00001642 assert(false && "@catch rewrite bug");
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001643 }
Steve Naroff929c77e2008-02-01 20:02:07 +00001644 // make sure all the catch bodies get rewritten!
Steve Naroffe9f69842007-11-07 04:08:17 +00001645 catchList = catchList->getNextCatchStmt();
1646 }
1647 // Complete the catch list...
1648 if (lastCatchBody) {
1649 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner690c2872008-04-08 05:52:18 +00001650 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1651 "bogus @catch body location");
Steve Naroffe9f69842007-11-07 04:08:17 +00001652
Steve Naroff31325c12008-09-11 15:29:03 +00001653 // Insert the last (implicit) else clause *before* the right curly brace.
1654 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1655 buf = "} /* last catch end */\n";
1656 buf += "else {\n";
1657 buf += " _rethrow = _caught;\n";
1658 buf += " objc_exception_try_exit(&_stack);\n";
1659 buf += "} } /* @catch end */\n";
1660 if (!S->getFinallyStmt())
1661 buf += "}\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001662 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001663
1664 // Set lastCurlyLoc
1665 lastCurlyLoc = lastCatchBody->getLocEnd();
1666 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001667 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001668 startLoc = finalStmt->getLocStart();
1669 startBuf = SM->getCharacterData(startLoc);
1670 assert((*startBuf == '@') && "bogus @finally start");
1671
1672 buf = "/* @finally */";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001673 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001674
1675 Stmt *body = finalStmt->getFinallyBody();
1676 SourceLocation startLoc = body->getLocStart();
1677 SourceLocation endLoc = body->getLocEnd();
Chris Lattner690c2872008-04-08 05:52:18 +00001678 assert(*SM->getCharacterData(startLoc) == '{' &&
1679 "bogus @finally body location");
1680 assert(*SM->getCharacterData(endLoc) == '}' &&
1681 "bogus @finally body location");
Steve Naroffe9f69842007-11-07 04:08:17 +00001682
1683 startLoc = startLoc.getFileLocWithOffset(1);
1684 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001685 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001686 endLoc = endLoc.getFileLocWithOffset(-1);
1687 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001688 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001689
1690 // Set lastCurlyLoc
1691 lastCurlyLoc = body->getLocEnd();
Steve Naroff43964fb2008-12-05 17:03:39 +00001692
1693 // Now check for any return/continue/go statements within the @try.
1694 WarnAboutReturnGotoContinueOrBreakStmts(S->getTryBody());
Steve Naroff31325c12008-09-11 15:29:03 +00001695 } else { /* no finally clause - make sure we synthesize an implicit one */
1696 buf = "{ /* implicit finally clause */\n";
1697 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1698 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1699 buf += "}";
1700 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001701 }
1702 // Now emit the final closing curly brace...
1703 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1704 buf = " } /* @try scope end */\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001705 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001706 return 0;
1707}
1708
Steve Naroff44e81222008-04-14 22:03:09 +00001709Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001710 return 0;
1711}
1712
Steve Naroff44e81222008-04-14 22:03:09 +00001713Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001714 return 0;
1715}
1716
Chris Lattnerb1548372008-01-31 19:37:57 +00001717// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001718// the throw expression is typically a message expression that's already
1719// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroff44e81222008-04-14 22:03:09 +00001720Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001721 // Get the start location and compute the semi location.
1722 SourceLocation startLoc = S->getLocStart();
1723 const char *startBuf = SM->getCharacterData(startLoc);
1724
1725 assert((*startBuf == '@') && "bogus @throw location");
1726
1727 std::string buf;
1728 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffbe72efa2008-01-19 00:42:38 +00001729 if (S->getThrowExpr())
1730 buf = "objc_exception_throw(";
1731 else // add an implicit argument
1732 buf = "objc_exception_throw(_caught";
Steve Naroff3de6eaa2008-07-25 15:41:30 +00001733
1734 // handle "@ throw" correctly.
1735 const char *wBuf = strchr(startBuf, 'w');
1736 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1737 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
1738
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001739 const char *semiBuf = strchr(startBuf, ';');
1740 assert((*semiBuf == ';') && "@throw: can't find ';'");
1741 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1742 buf = ");";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001743 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001744 return 0;
1745}
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001746
Steve Naroff44e81222008-04-14 22:03:09 +00001747Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerbf0bfa62007-10-17 22:35:30 +00001748 // Create a new string expression.
1749 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson36f07d82007-10-29 05:01:08 +00001750 std::string StrEncoding;
Daniel Dunbarc9197cd2008-10-17 20:21:44 +00001751 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattneraa491192009-02-18 06:40:38 +00001752 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
1753 StrEncoding.length(), false,StrType,
1754 SourceLocation());
Chris Lattnerb1548372008-01-31 19:37:57 +00001755 ReplaceStmt(Exp, Replacement);
Chris Lattner258f26c2007-11-30 22:25:36 +00001756
Chris Lattner4478db92007-11-30 22:53:43 +00001757 // Replace this subexpr in the parent.
Steve Naroff102c3f22008-12-04 23:50:32 +00001758 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattner0021f452007-10-24 16:57:36 +00001759 return Replacement;
Chris Lattner6fe8b272007-10-16 22:36:42 +00001760}
1761
Steve Naroff44e81222008-04-14 22:03:09 +00001762Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff95f6bce2008-12-22 22:16:07 +00001763 if (!SelGetUidFunctionDecl)
1764 SynthSelGetUidFunctionDecl();
Steve Naroff296b74f2007-11-05 14:50:49 +00001765 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1766 // Create a call to sel_registerName("selName").
1767 llvm::SmallVector<Expr*, 8> SelExprs;
1768 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattneraa491192009-02-18 06:40:38 +00001769 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek4f530a92009-02-06 19:55:15 +00001770 Exp->getSelector().getAsString().c_str(),
Chris Lattner3a8f2942008-11-24 03:33:13 +00001771 Exp->getSelector().getAsString().size(),
Chris Lattnerc3144742009-02-18 05:49:11 +00001772 false, argType, SourceLocation()));
Steve Naroff296b74f2007-11-05 14:50:49 +00001773 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1774 &SelExprs[0], SelExprs.size());
Chris Lattnerb1548372008-01-31 19:37:57 +00001775 ReplaceStmt(Exp, SelExp);
Steve Naroff102c3f22008-12-04 23:50:32 +00001776 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff296b74f2007-11-05 14:50:49 +00001777 return SelExp;
1778}
1779
Steve Naroff44e81222008-04-14 22:03:09 +00001780CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff71226032007-10-24 22:48:43 +00001781 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffe9780582007-10-23 23:50:29 +00001782 // Get the type, we will need to reference it in a couple spots.
Steve Naroff71226032007-10-24 22:48:43 +00001783 QualType msgSendType = FD->getType();
Steve Naroffe9780582007-10-23 23:50:29 +00001784
1785 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek0c97e042009-02-07 01:47:29 +00001786 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffe9780582007-10-23 23:50:29 +00001787
1788 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerfce2c5a2007-10-24 17:06:59 +00001789 QualType pToFunc = Context->getPointerType(msgSendType);
Anders Carlsson7ef181c2009-07-31 00:48:10 +00001790 ImplicitCastExpr *ICE = new (Context) ImplicitCastExpr(pToFunc,
1791 CastExpr::CK_Unknown,
1792 DRE,
Douglas Gregor70d26122008-11-12 17:17:38 +00001793 /*isLvalue=*/false);
Steve Naroffe9780582007-10-23 23:50:29 +00001794
1795 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattner0021f452007-10-24 16:57:36 +00001796
Ted Kremenek362abcd2009-02-09 20:51:47 +00001797 return new (Context) CallExpr(*Context, ICE, args, nargs, FT->getResultType(),
1798 SourceLocation());
Steve Naroff71226032007-10-24 22:48:43 +00001799}
1800
Steve Naroffc8a92d12007-11-01 13:24:47 +00001801static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1802 const char *&startRef, const char *&endRef) {
1803 while (startBuf < endBuf) {
1804 if (*startBuf == '<')
1805 startRef = startBuf; // mark the start.
1806 if (*startBuf == '>') {
Steve Naroff2aeae312007-11-09 12:50:28 +00001807 if (startRef && *startRef == '<') {
1808 endRef = startBuf; // mark the end.
1809 return true;
1810 }
1811 return false;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001812 }
1813 startBuf++;
1814 }
1815 return false;
1816}
1817
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001818static void scanToNextArgument(const char *&argRef) {
1819 int angle = 0;
1820 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1821 if (*argRef == '<')
1822 angle++;
1823 else if (*argRef == '>')
1824 angle--;
1825 argRef++;
1826 }
1827 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1828}
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +00001829
Steve Naroff44e81222008-04-14 22:03:09 +00001830bool RewriteObjC::needToScanForQualifiers(QualType T) {
Steve Naroff77763c52009-07-18 15:33:26 +00001831 return T->isObjCQualifiedIdType() || T->isObjCQualifiedInterfaceType();
Steve Naroffc8a92d12007-11-01 13:24:47 +00001832}
1833
Steve Naroffd06c88d2008-07-29 18:15:38 +00001834void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1835 QualType Type = E->getType();
1836 if (needToScanForQualifiers(Type)) {
Steve Narofff31ece92008-11-19 21:15:47 +00001837 SourceLocation Loc, EndLoc;
1838
1839 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
1840 Loc = ECE->getLParenLoc();
1841 EndLoc = ECE->getRParenLoc();
1842 } else {
1843 Loc = E->getLocStart();
1844 EndLoc = E->getLocEnd();
1845 }
1846 // This will defend against trying to rewrite synthesized expressions.
1847 if (Loc.isInvalid() || EndLoc.isInvalid())
1848 return;
1849
Steve Naroffd06c88d2008-07-29 18:15:38 +00001850 const char *startBuf = SM->getCharacterData(Loc);
Steve Narofff31ece92008-11-19 21:15:47 +00001851 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroffd06c88d2008-07-29 18:15:38 +00001852 const char *startRef = 0, *endRef = 0;
1853 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1854 // Get the locations of the startRef, endRef.
1855 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1856 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1857 // Comment out the protocol references.
1858 InsertText(LessLoc, "/*", 2);
1859 InsertText(GreaterLoc, "*/", 2);
1860 }
1861 }
1862}
1863
Steve Naroff44e81222008-04-14 22:03:09 +00001864void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001865 SourceLocation Loc;
1866 QualType Type;
Douglas Gregor4fa58902009-02-26 23:50:07 +00001867 const FunctionProtoType *proto = 0;
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001868 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1869 Loc = VD->getLocation();
1870 Type = VD->getType();
1871 }
1872 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1873 Loc = FD->getLocation();
1874 // Check for ObjC 'id' and class types that have been adorned with protocol
1875 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1876 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1877 assert(funcType && "missing function type");
Douglas Gregor4fa58902009-02-26 23:50:07 +00001878 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001879 if (!proto)
1880 return;
1881 Type = proto->getResultType();
1882 }
1883 else
1884 return;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001885
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001886 if (needToScanForQualifiers(Type)) {
Steve Naroffc8a92d12007-11-01 13:24:47 +00001887 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001888
1889 const char *endBuf = SM->getCharacterData(Loc);
1890 const char *startBuf = endBuf;
Steve Naroffff2fa192008-05-31 05:02:17 +00001891 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffc8a92d12007-11-01 13:24:47 +00001892 startBuf--; // scan backward (from the decl location) for return type.
1893 const char *startRef = 0, *endRef = 0;
1894 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1895 // Get the locations of the startRef, endRef.
1896 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1897 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1898 // Comment out the protocol references.
Chris Lattner6216f292008-01-31 19:42:41 +00001899 InsertText(LessLoc, "/*", 2);
1900 InsertText(GreaterLoc, "*/", 2);
Steve Naroff05d6ff52007-10-31 04:38:33 +00001901 }
1902 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001903 if (!proto)
1904 return; // most likely, was a variable
Steve Naroffc8a92d12007-11-01 13:24:47 +00001905 // Now check arguments.
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001906 const char *startBuf = SM->getCharacterData(Loc);
1907 const char *startFuncBuf = startBuf;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001908 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1909 if (needToScanForQualifiers(proto->getArgType(i))) {
1910 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001911
Steve Naroffc8a92d12007-11-01 13:24:47 +00001912 const char *endBuf = startBuf;
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001913 // scan forward (from the decl location) for argument types.
1914 scanToNextArgument(endBuf);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001915 const char *startRef = 0, *endRef = 0;
1916 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1917 // Get the locations of the startRef, endRef.
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +00001918 SourceLocation LessLoc =
1919 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1920 SourceLocation GreaterLoc =
1921 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001922 // Comment out the protocol references.
Chris Lattner6216f292008-01-31 19:42:41 +00001923 InsertText(LessLoc, "/*", 2);
1924 InsertText(GreaterLoc, "*/", 2);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001925 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001926 startBuf = ++endBuf;
1927 }
1928 else {
Steve Naroff6a1d88b2008-08-06 15:58:23 +00001929 // If the function name is derived from a macro expansion, then the
1930 // argument buffer will not follow the name. Need to speak with Chris.
1931 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001932 startBuf++; // scan forward (from the decl location) for argument types.
1933 startBuf++;
1934 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001935 }
Steve Naroff05d6ff52007-10-31 04:38:33 +00001936}
1937
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001938// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroff44e81222008-04-14 22:03:09 +00001939void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001940 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1941 llvm::SmallVector<QualType, 16> ArgTys;
1942 ArgTys.push_back(Context->getPointerType(
1943 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001944 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001945 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00001946 false /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001947 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001948 SourceLocation(),
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +00001949 SelGetUidIdent, getFuncType, 0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001950 FunctionDecl::Extern, false);
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001951}
1952
Steve Naroff44e81222008-04-14 22:03:09 +00001953void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001954 // declared in <objc/objc.h>
Douglas Gregor7339c9e2009-01-09 01:47:02 +00001955 if (FD->getIdentifier() &&
1956 strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001957 SelGetUidFunctionDecl = FD;
Steve Naroff05d6ff52007-10-31 04:38:33 +00001958 return;
1959 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001960 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff02a82aa2007-10-30 23:14:51 +00001961}
1962
Steve Naroffbec4bf52008-03-11 17:37:02 +00001963// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroff44e81222008-04-14 22:03:09 +00001964void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffbec4bf52008-03-11 17:37:02 +00001965 if (SuperContructorFunctionDecl)
1966 return;
Steve Naroff12673622008-12-23 20:11:22 +00001967 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroffbec4bf52008-03-11 17:37:02 +00001968 llvm::SmallVector<QualType, 16> ArgTys;
1969 QualType argT = Context->getObjCIdType();
1970 assert(!argT.isNull() && "Can't find 'id' type");
1971 ArgTys.push_back(argT);
1972 ArgTys.push_back(argT);
1973 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1974 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00001975 false, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001976 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001977 SourceLocation(),
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +00001978 msgSendIdent, msgSendType, 0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001979 FunctionDecl::Extern, false);
Steve Naroffbec4bf52008-03-11 17:37:02 +00001980}
1981
Steve Naroff02a82aa2007-10-30 23:14:51 +00001982// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00001983void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001984 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1985 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001986 QualType argT = Context->getObjCIdType();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001987 assert(!argT.isNull() && "Can't find 'id' type");
1988 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001989 argT = Context->getObjCSelType();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001990 assert(!argT.isNull() && "Can't find 'SEL' type");
1991 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001992 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001993 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00001994 true /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001995 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001996 SourceLocation(),
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +00001997 msgSendIdent, msgSendType, 0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001998 FunctionDecl::Extern, false);
Steve Naroff02a82aa2007-10-30 23:14:51 +00001999}
2000
Steve Naroff764c1ae2007-11-15 10:28:18 +00002001// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00002002void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff764c1ae2007-11-15 10:28:18 +00002003 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2004 llvm::SmallVector<QualType, 16> ArgTys;
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002005 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00002006 SourceLocation(),
Ted Kremenek2c984042008-09-05 01:34:33 +00002007 &Context->Idents.get("objc_super"));
Steve Naroff764c1ae2007-11-15 10:28:18 +00002008 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2009 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2010 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00002011 argT = Context->getObjCSelType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00002012 assert(!argT.isNull() && "Can't find 'SEL' type");
2013 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00002014 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00002015 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002016 true /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00002017 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00002018 SourceLocation(),
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +00002019 msgSendIdent, msgSendType, 0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002020 FunctionDecl::Extern, false);
Steve Naroff764c1ae2007-11-15 10:28:18 +00002021}
2022
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002023// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00002024void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002025 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2026 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00002027 QualType argT = Context->getObjCIdType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002028 assert(!argT.isNull() && "Can't find 'id' type");
2029 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00002030 argT = Context->getObjCSelType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002031 assert(!argT.isNull() && "Can't find 'SEL' type");
2032 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00002033 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002034 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002035 true /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00002036 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00002037 SourceLocation(),
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +00002038 msgSendIdent, msgSendType, 0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002039 FunctionDecl::Extern, false);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002040}
2041
2042// SynthMsgSendSuperStretFunctionDecl -
2043// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00002044void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002045 IdentifierInfo *msgSendIdent =
2046 &Context->Idents.get("objc_msgSendSuper_stret");
2047 llvm::SmallVector<QualType, 16> ArgTys;
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002048 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00002049 SourceLocation(),
Ted Kremenek2c984042008-09-05 01:34:33 +00002050 &Context->Idents.get("objc_super"));
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002051 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2052 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2053 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00002054 argT = Context->getObjCSelType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002055 assert(!argT.isNull() && "Can't find 'SEL' type");
2056 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00002057 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002058 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002059 true /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00002060 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner4c7802b2008-03-15 21:24:04 +00002061 SourceLocation(),
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +00002062 msgSendIdent, msgSendType, 0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002063 FunctionDecl::Extern, false);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002064}
2065
Steve Naroff31316a12008-05-08 22:02:18 +00002066// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00002067void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002068 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2069 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00002070 QualType argT = Context->getObjCIdType();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002071 assert(!argT.isNull() && "Can't find 'id' type");
2072 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00002073 argT = Context->getObjCSelType();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002074 assert(!argT.isNull() && "Can't find 'SEL' type");
2075 ArgTys.push_back(argT);
Steve Naroff31316a12008-05-08 22:02:18 +00002076 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002077 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002078 true /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00002079 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00002080 SourceLocation(),
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +00002081 msgSendIdent, msgSendType, 0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002082 FunctionDecl::Extern, false);
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002083}
2084
Steve Naroff02a82aa2007-10-30 23:14:51 +00002085// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff44e81222008-04-14 22:03:09 +00002086void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff02a82aa2007-10-30 23:14:51 +00002087 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2088 llvm::SmallVector<QualType, 16> ArgTys;
2089 ArgTys.push_back(Context->getPointerType(
2090 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00002091 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00002092 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002093 false /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00002094 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00002095 SourceLocation(),
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +00002096 getClassIdent, getClassType, 0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002097 FunctionDecl::Extern, false);
Steve Naroff02a82aa2007-10-30 23:14:51 +00002098}
2099
Steve Naroff3b1caac2007-12-07 03:50:46 +00002100// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff44e81222008-04-14 22:03:09 +00002101void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff3b1caac2007-12-07 03:50:46 +00002102 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2103 llvm::SmallVector<QualType, 16> ArgTys;
2104 ArgTys.push_back(Context->getPointerType(
2105 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00002106 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00002107 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002108 false /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00002109 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00002110 SourceLocation(),
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +00002111 getClassIdent, getClassType, 0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002112 FunctionDecl::Extern, false);
Steve Naroff3b1caac2007-12-07 03:50:46 +00002113}
2114
Steve Naroff44e81222008-04-14 22:03:09 +00002115Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroff47e7fa22008-03-15 00:55:56 +00002116 QualType strType = getConstantStringStructType();
2117
2118 std::string S = "__NSConstantStringImpl_";
Steve Naroffa1f00992008-05-31 03:35:42 +00002119
2120 std::string tmpName = InFileName;
2121 unsigned i;
2122 for (i=0; i < tmpName.length(); i++) {
2123 char c = tmpName.at(i);
2124 // replace any non alphanumeric characters with '_'.
2125 if (!isalpha(c) && (c < '0' || c > '9'))
2126 tmpName[i] = '_';
2127 }
2128 S += tmpName;
2129 S += "_";
Steve Naroff47e7fa22008-03-15 00:55:56 +00002130 S += utostr(NumObjCStringLiterals++);
2131
Steve Narofffef037c2008-03-27 22:29:16 +00002132 Preamble += "static __NSConstantStringImpl " + S;
2133 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2134 Preamble += "0x000007c8,"; // utf8_str
Steve Naroff47e7fa22008-03-15 00:55:56 +00002135 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremenek7b6f67b2008-09-13 05:16:45 +00002136 std::string prettyBufS;
2137 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattner7099c782009-06-30 01:26:17 +00002138 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2139 PrintingPolicy(LangOpts));
Steve Narofffef037c2008-03-27 22:29:16 +00002140 Preamble += prettyBuf.str();
2141 Preamble += ",";
Steve Naroff64bce352008-03-15 01:36:04 +00002142 // The minus 2 removes the begin/end double quotes.
Steve Narofffef037c2008-03-27 22:29:16 +00002143 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroff47e7fa22008-03-15 00:55:56 +00002144
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00002145 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +00002146 &Context->Idents.get(S.c_str()), strType, 0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002147 VarDecl::Static);
Ted Kremenek0c97e042009-02-07 01:47:29 +00002148 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
2149 Expr *Unop = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
Steve Naroff47e7fa22008-03-15 00:55:56 +00002150 Context->getPointerType(DRE->getType()),
2151 SourceLocation());
Steve Naroffabb96362007-11-08 14:30:50 +00002152 // cast to NSConstantString *
Anders Carlsson7ef181c2009-07-31 00:48:10 +00002153 CastExpr *cast = new (Context) CStyleCastExpr(Exp->getType(),
2154 CastExpr::CK_Unknown,
2155 Unop, Exp->getType(),
2156 SourceLocation(),
2157 SourceLocation());
Chris Lattnerb1548372008-01-31 19:37:57 +00002158 ReplaceStmt(Exp, cast);
Steve Naroff102c3f22008-12-04 23:50:32 +00002159 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffabb96362007-11-08 14:30:50 +00002160 return cast;
Steve Naroff0add5d22007-11-03 11:27:19 +00002161}
2162
Steve Naroff44e81222008-04-14 22:03:09 +00002163ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff3b1caac2007-12-07 03:50:46 +00002164 // check if we are sending a message to 'super'
Douglas Gregor5d764842009-01-09 17:18:27 +00002165 if (!CurMethodDef || !CurMethodDef->isInstanceMethod()) return 0;
Chris Lattnere4650482008-03-15 06:12:44 +00002166
Douglas Gregord8606632008-11-04 14:56:14 +00002167 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
Steve Naroff329ec222009-07-10 23:34:53 +00002168 const ObjCObjectPointerType *OPT =
2169 Super->getType()->getAsObjCObjectPointerType();
2170 assert(OPT);
2171 const ObjCInterfaceType *IT = OPT->getInterfaceType();
Chris Lattner4423d372008-06-21 18:04:54 +00002172 return IT->getDecl();
2173 }
2174 return 0;
Steve Naroff764c1ae2007-11-15 10:28:18 +00002175}
2176
2177// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroff44e81222008-04-14 22:03:09 +00002178QualType RewriteObjC::getSuperStructType() {
Steve Naroff764c1ae2007-11-15 10:28:18 +00002179 if (!SuperStructDecl) {
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002180 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner58114f02008-03-15 21:32:50 +00002181 SourceLocation(),
Ted Kremenek2c984042008-09-05 01:34:33 +00002182 &Context->Idents.get("objc_super"));
Steve Naroff764c1ae2007-11-15 10:28:18 +00002183 QualType FieldTypes[2];
2184
2185 // struct objc_object *receiver;
Ted Kremenek42730c52008-01-07 19:49:32 +00002186 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00002187 // struct objc_class *super;
Ted Kremenek42730c52008-01-07 19:49:32 +00002188 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor8acb7272008-12-11 16:49:14 +00002189
Steve Naroff764c1ae2007-11-15 10:28:18 +00002190 // Create fields
Douglas Gregor8acb7272008-12-11 16:49:14 +00002191 for (unsigned i = 0; i < 2; ++i) {
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002192 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
Douglas Gregor8acb7272008-12-11 16:49:14 +00002193 SourceLocation(), 0,
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +00002194 FieldTypes[i], 0,
2195 /*BitWidth=*/0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002196 /*Mutable=*/false));
Douglas Gregor8acb7272008-12-11 16:49:14 +00002197 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00002198
Douglas Gregor8acb7272008-12-11 16:49:14 +00002199 SuperStructDecl->completeDefinition(*Context);
Steve Naroff764c1ae2007-11-15 10:28:18 +00002200 }
2201 return Context->getTagDeclType(SuperStructDecl);
2202}
2203
Steve Naroff44e81222008-04-14 22:03:09 +00002204QualType RewriteObjC::getConstantStringStructType() {
Steve Naroff47e7fa22008-03-15 00:55:56 +00002205 if (!ConstantStringDecl) {
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002206 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner58114f02008-03-15 21:32:50 +00002207 SourceLocation(),
Ted Kremenek2c984042008-09-05 01:34:33 +00002208 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroff47e7fa22008-03-15 00:55:56 +00002209 QualType FieldTypes[4];
2210
2211 // struct objc_object *receiver;
2212 FieldTypes[0] = Context->getObjCIdType();
2213 // int flags;
2214 FieldTypes[1] = Context->IntTy;
2215 // char *str;
2216 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2217 // long length;
2218 FieldTypes[3] = Context->LongTy;
Douglas Gregor8acb7272008-12-11 16:49:14 +00002219
Steve Naroff47e7fa22008-03-15 00:55:56 +00002220 // Create fields
Douglas Gregor8acb7272008-12-11 16:49:14 +00002221 for (unsigned i = 0; i < 4; ++i) {
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002222 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
Douglas Gregor8acb7272008-12-11 16:49:14 +00002223 ConstantStringDecl,
2224 SourceLocation(), 0,
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +00002225 FieldTypes[i], 0,
Douglas Gregor8acb7272008-12-11 16:49:14 +00002226 /*BitWidth=*/0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002227 /*Mutable=*/true));
Douglas Gregor8acb7272008-12-11 16:49:14 +00002228 }
2229
2230 ConstantStringDecl->completeDefinition(*Context);
Steve Naroff47e7fa22008-03-15 00:55:56 +00002231 }
2232 return Context->getTagDeclType(ConstantStringDecl);
2233}
2234
Steve Naroff44e81222008-04-14 22:03:09 +00002235Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00002236 if (!SelGetUidFunctionDecl)
2237 SynthSelGetUidFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00002238 if (!MsgSendFunctionDecl)
2239 SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +00002240 if (!MsgSendSuperFunctionDecl)
2241 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002242 if (!MsgSendStretFunctionDecl)
2243 SynthMsgSendStretFunctionDecl();
2244 if (!MsgSendSuperStretFunctionDecl)
2245 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002246 if (!MsgSendFpretFunctionDecl)
2247 SynthMsgSendFpretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00002248 if (!GetClassFunctionDecl)
2249 SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +00002250 if (!GetMetaClassFunctionDecl)
2251 SynthGetMetaClassFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002252
Steve Naroff764c1ae2007-11-15 10:28:18 +00002253 // default to objc_msgSend().
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002254 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2255 // May need to use objc_msgSend_stret() as well.
2256 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroff450d2fc2009-04-29 16:37:50 +00002257 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2258 QualType resultType = mDecl->getResultType();
Chris Lattnerb724ab22008-07-26 22:36:27 +00002259 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002260 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattnerb724ab22008-07-26 22:36:27 +00002261 else if (resultType->isRealFloatingType())
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002262 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002263 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00002264
Steve Naroff71226032007-10-24 22:48:43 +00002265 // Synthesize a call to objc_msgSend().
2266 llvm::SmallVector<Expr*, 8> MsgExprs;
2267 IdentifierInfo *clsName = Exp->getClassName();
2268
2269 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2270 if (clsName) { // class message.
Steve Naroff91a69202008-07-24 19:44:33 +00002271 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2272 // the 'super' idiom within a class method.
Steve Naroff3b1caac2007-12-07 03:50:46 +00002273 if (!strcmp(clsName->getName(), "super")) {
2274 MsgSendFlavor = MsgSendSuperFunctionDecl;
2275 if (MsgSendStretFlavor)
2276 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2277 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2278
Ted Kremenek42730c52008-01-07 19:49:32 +00002279 ObjCInterfaceDecl *SuperDecl =
Steve Naroff38a9e3f2008-10-27 17:20:55 +00002280 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroff3b1caac2007-12-07 03:50:46 +00002281
2282 llvm::SmallVector<Expr*, 4> InitExprs;
2283
2284 // set the receiver to self, the first argument to all methods.
Steve Naroff450d2fc2009-04-29 16:37:50 +00002285 InitExprs.push_back(
2286 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlsson7ef181c2009-07-31 00:48:10 +00002287 CastExpr::CK_Unknown,
Steve Naroff450d2fc2009-04-29 16:37:50 +00002288 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
2289 Context->getObjCIdType(),
2290 SourceLocation()),
2291 Context->getObjCIdType(),
2292 SourceLocation(), SourceLocation())); // set the 'receiver'.
2293
Steve Naroff3b1caac2007-12-07 03:50:46 +00002294 llvm::SmallVector<Expr*, 8> ClsExprs;
2295 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattneraa491192009-02-18 06:40:38 +00002296 ClsExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek4f530a92009-02-06 19:55:15 +00002297 SuperDecl->getIdentifier()->getName(),
2298 SuperDecl->getIdentifier()->getLength(),
Chris Lattnerc3144742009-02-18 05:49:11 +00002299 false, argType, SourceLocation()));
Steve Naroff3b1caac2007-12-07 03:50:46 +00002300 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2301 &ClsExprs[0],
2302 ClsExprs.size());
2303 // To turn off a warning, type-cast to 'id'
Douglas Gregor21a04f32008-10-27 19:41:14 +00002304 InitExprs.push_back( // set 'super class', using objc_getClass().
Ted Kremenek0c97e042009-02-07 01:47:29 +00002305 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlsson7ef181c2009-07-31 00:48:10 +00002306 CastExpr::CK_Unknown,
Douglas Gregor21a04f32008-10-27 19:41:14 +00002307 Cls, Context->getObjCIdType(),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002308 SourceLocation(), SourceLocation()));
Steve Naroff3b1caac2007-12-07 03:50:46 +00002309 // struct objc_super
2310 QualType superType = getSuperStructType();
Steve Naroffdee066b2008-03-11 18:14:26 +00002311 Expr *SuperRep;
Steve Naroffbec4bf52008-03-11 17:37:02 +00002312
Steve Naroffdee066b2008-03-11 18:14:26 +00002313 if (LangOpts.Microsoft) {
2314 SynthSuperContructorFunctionDecl();
2315 // Simulate a contructor call...
Ted Kremenek0c97e042009-02-07 01:47:29 +00002316 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroffdee066b2008-03-11 18:14:26 +00002317 superType, SourceLocation());
Ted Kremenek362abcd2009-02-09 20:51:47 +00002318 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2319 InitExprs.size(),
2320 superType, SourceLocation());
Steve Naroff12673622008-12-23 20:11:22 +00002321 // The code for super is a little tricky to prevent collision with
2322 // the structure definition in the header. The rewriter has it's own
2323 // internal definition (__rw_objc_super) that is uses. This is why
2324 // we need the cast below. For example:
2325 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2326 //
Ted Kremenek0c97e042009-02-07 01:47:29 +00002327 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Steve Naroff12673622008-12-23 20:11:22 +00002328 Context->getPointerType(SuperRep->getType()),
2329 SourceLocation());
Ted Kremenek0c97e042009-02-07 01:47:29 +00002330 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
Anders Carlsson7ef181c2009-07-31 00:48:10 +00002331 CastExpr::CK_Unknown, SuperRep,
2332 Context->getPointerType(superType),
Steve Naroff12673622008-12-23 20:11:22 +00002333 SourceLocation(), SourceLocation());
Steve Naroffdee066b2008-03-11 18:14:26 +00002334 } else {
2335 // (struct objc_super) { <exprs from above> }
Ted Kremenek0c97e042009-02-07 01:47:29 +00002336 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
Steve Naroffdee066b2008-03-11 18:14:26 +00002337 &InitExprs[0], InitExprs.size(),
Douglas Gregorf603b472009-01-28 21:54:33 +00002338 SourceLocation());
Ted Kremenek0c97e042009-02-07 01:47:29 +00002339 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE,
Chris Lattner71ca8c82008-10-26 23:43:26 +00002340 false);
Steve Naroff12673622008-12-23 20:11:22 +00002341 // struct objc_super *
Ted Kremenek0c97e042009-02-07 01:47:29 +00002342 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Steve Naroff12673622008-12-23 20:11:22 +00002343 Context->getPointerType(SuperRep->getType()),
2344 SourceLocation());
Steve Naroffdee066b2008-03-11 18:14:26 +00002345 }
Steve Naroff12673622008-12-23 20:11:22 +00002346 MsgExprs.push_back(SuperRep);
Steve Naroff3b1caac2007-12-07 03:50:46 +00002347 } else {
2348 llvm::SmallVector<Expr*, 8> ClsExprs;
2349 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattneraa491192009-02-18 06:40:38 +00002350 ClsExprs.push_back(StringLiteral::Create(*Context,
2351 clsName->getName(),
2352 clsName->getLength(),
2353 false, argType,
2354 SourceLocation()));
Steve Naroff3b1caac2007-12-07 03:50:46 +00002355 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2356 &ClsExprs[0],
2357 ClsExprs.size());
2358 MsgExprs.push_back(Cls);
2359 }
Steve Naroff885e2122007-11-14 23:54:14 +00002360 } else { // instance message.
2361 Expr *recExpr = Exp->getReceiver();
Steve Naroff764c1ae2007-11-15 10:28:18 +00002362
Ted Kremenek42730c52008-01-07 19:49:32 +00002363 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff764c1ae2007-11-15 10:28:18 +00002364 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002365 if (MsgSendStretFlavor)
2366 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +00002367 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2368
2369 llvm::SmallVector<Expr*, 4> InitExprs;
2370
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00002371 InitExprs.push_back(
Ted Kremenek0c97e042009-02-07 01:47:29 +00002372 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlsson7ef181c2009-07-31 00:48:10 +00002373 CastExpr::CK_Unknown,
Ted Kremenek0c97e042009-02-07 01:47:29 +00002374 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroff23528612008-07-16 22:35:27 +00002375 Context->getObjCIdType(),
Douglas Gregor21a04f32008-10-27 19:41:14 +00002376 SourceLocation()),
2377 Context->getObjCIdType(),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002378 SourceLocation(), SourceLocation())); // set the 'receiver'.
Steve Naroff764c1ae2007-11-15 10:28:18 +00002379
2380 llvm::SmallVector<Expr*, 8> ClsExprs;
2381 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattneraa491192009-02-18 06:40:38 +00002382 ClsExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek4f530a92009-02-06 19:55:15 +00002383 SuperDecl->getIdentifier()->getName(),
2384 SuperDecl->getIdentifier()->getLength(),
Chris Lattnerc3144742009-02-18 05:49:11 +00002385 false, argType, SourceLocation()));
Steve Naroff764c1ae2007-11-15 10:28:18 +00002386 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00002387 &ClsExprs[0],
2388 ClsExprs.size());
Fariborz Jahanianfabf3bf2007-12-05 17:29:46 +00002389 // To turn off a warning, type-cast to 'id'
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00002390 InitExprs.push_back(
Douglas Gregor21a04f32008-10-27 19:41:14 +00002391 // set 'super class', using objc_getClass().
Ted Kremenek0c97e042009-02-07 01:47:29 +00002392 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlsson7ef181c2009-07-31 00:48:10 +00002393 CastExpr::CK_Unknown,
Steve Naroff7f1412d2008-11-03 23:29:32 +00002394 Cls, Context->getObjCIdType(), SourceLocation(), SourceLocation()));
Steve Naroff764c1ae2007-11-15 10:28:18 +00002395 // struct objc_super
2396 QualType superType = getSuperStructType();
Steve Naroffbec4bf52008-03-11 17:37:02 +00002397 Expr *SuperRep;
2398
2399 if (LangOpts.Microsoft) {
2400 SynthSuperContructorFunctionDecl();
2401 // Simulate a contructor call...
Ted Kremenek0c97e042009-02-07 01:47:29 +00002402 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroffbec4bf52008-03-11 17:37:02 +00002403 superType, SourceLocation());
Ted Kremenek362abcd2009-02-09 20:51:47 +00002404 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2405 InitExprs.size(),
2406 superType, SourceLocation());
Steve Naroff12673622008-12-23 20:11:22 +00002407 // The code for super is a little tricky to prevent collision with
2408 // the structure definition in the header. The rewriter has it's own
2409 // internal definition (__rw_objc_super) that is uses. This is why
2410 // we need the cast below. For example:
2411 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2412 //
Ted Kremenek0c97e042009-02-07 01:47:29 +00002413 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Steve Naroff12673622008-12-23 20:11:22 +00002414 Context->getPointerType(SuperRep->getType()),
2415 SourceLocation());
Ted Kremenek0c97e042009-02-07 01:47:29 +00002416 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
Anders Carlsson7ef181c2009-07-31 00:48:10 +00002417 CastExpr::CK_Unknown,
Steve Naroff12673622008-12-23 20:11:22 +00002418 SuperRep, Context->getPointerType(superType),
2419 SourceLocation(), SourceLocation());
Steve Naroffbec4bf52008-03-11 17:37:02 +00002420 } else {
2421 // (struct objc_super) { <exprs from above> }
Ted Kremenek0c97e042009-02-07 01:47:29 +00002422 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
Steve Naroffbec4bf52008-03-11 17:37:02 +00002423 &InitExprs[0], InitExprs.size(),
Douglas Gregorf603b472009-01-28 21:54:33 +00002424 SourceLocation());
Ted Kremenek0c97e042009-02-07 01:47:29 +00002425 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
Steve Naroffbec4bf52008-03-11 17:37:02 +00002426 }
Steve Naroff12673622008-12-23 20:11:22 +00002427 MsgExprs.push_back(SuperRep);
Steve Naroff764c1ae2007-11-15 10:28:18 +00002428 } else {
Fariborz Jahanianbe4283c2007-12-07 21:21:21 +00002429 // Remove all type-casts because it may contain objc-style types; e.g.
2430 // Foo<Proto> *.
Douglas Gregor035d0882008-10-28 15:36:24 +00002431 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanianbe4283c2007-12-07 21:21:21 +00002432 recExpr = CE->getSubExpr();
Anders Carlsson7ef181c2009-07-31 00:48:10 +00002433 recExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
2434 CastExpr::CK_Unknown, recExpr,
Douglas Gregor21a04f32008-10-27 19:41:14 +00002435 Context->getObjCIdType(),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002436 SourceLocation(), SourceLocation());
Steve Naroff764c1ae2007-11-15 10:28:18 +00002437 MsgExprs.push_back(recExpr);
2438 }
Steve Naroff885e2122007-11-14 23:54:14 +00002439 }
Steve Naroff0add5d22007-11-03 11:27:19 +00002440 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff71226032007-10-24 22:48:43 +00002441 llvm::SmallVector<Expr*, 8> SelExprs;
2442 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattneraa491192009-02-18 06:40:38 +00002443 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek4f530a92009-02-06 19:55:15 +00002444 Exp->getSelector().getAsString().c_str(),
Chris Lattner3a8f2942008-11-24 03:33:13 +00002445 Exp->getSelector().getAsString().size(),
Chris Lattnerc3144742009-02-18 05:49:11 +00002446 false, argType, SourceLocation()));
Steve Naroff71226032007-10-24 22:48:43 +00002447 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2448 &SelExprs[0], SelExprs.size());
2449 MsgExprs.push_back(SelExp);
2450
2451 // Now push any user supplied arguments.
2452 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff885e2122007-11-14 23:54:14 +00002453 Expr *userExpr = Exp->getArg(i);
Steve Naroff6b759ce2007-11-15 02:58:25 +00002454 // Make all implicit casts explicit...ICE comes in handy:-)
2455 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2456 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregor21a04f32008-10-27 19:41:14 +00002457 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremenek42730c52008-01-07 19:49:32 +00002458 ? Context->getObjCIdType()
Douglas Gregor21a04f32008-10-27 19:41:14 +00002459 : ICE->getType();
Anders Carlsson7ef181c2009-07-31 00:48:10 +00002460 userExpr = new (Context) CStyleCastExpr(type, CastExpr::CK_Unknown,
2461 userExpr, type, SourceLocation(),
2462 SourceLocation());
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002463 }
2464 // Make id<P...> cast into an 'id' cast.
Douglas Gregor035d0882008-10-28 15:36:24 +00002465 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002466 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor035d0882008-10-28 15:36:24 +00002467 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002468 userExpr = CE->getSubExpr();
Ted Kremenek0c97e042009-02-07 01:47:29 +00002469 userExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlsson7ef181c2009-07-31 00:48:10 +00002470 CastExpr::CK_Unknown,
Douglas Gregor21a04f32008-10-27 19:41:14 +00002471 userExpr, Context->getObjCIdType(),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002472 SourceLocation(), SourceLocation());
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002473 }
Steve Naroff6b759ce2007-11-15 02:58:25 +00002474 }
Steve Naroff885e2122007-11-14 23:54:14 +00002475 MsgExprs.push_back(userExpr);
Steve Naroff450d2fc2009-04-29 16:37:50 +00002476 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2477 // out the argument in the original expression (since we aren't deleting
2478 // the ObjCMessageExpr). See RewritePropertySetter() usage for more info.
2479 //Exp->setArg(i, 0);
Steve Naroff71226032007-10-24 22:48:43 +00002480 }
Steve Naroff0744c472007-11-04 22:37:50 +00002481 // Generate the funky cast.
2482 CastExpr *cast;
2483 llvm::SmallVector<QualType, 8> ArgTypes;
2484 QualType returnType;
2485
2486 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff0c04bb62007-11-15 10:43:57 +00002487 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2488 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2489 else
Ted Kremenek42730c52008-01-07 19:49:32 +00002490 ArgTypes.push_back(Context->getObjCIdType());
2491 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner5c6b2c62009-02-20 18:43:26 +00002492 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroff0744c472007-11-04 22:37:50 +00002493 // Push any user argument types.
Chris Lattner5c6b2c62009-02-20 18:43:26 +00002494 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2495 E = OMD->param_end(); PI != E; ++PI) {
2496 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Ted Kremenek42730c52008-01-07 19:49:32 +00002497 ? Context->getObjCIdType()
Chris Lattner5c6b2c62009-02-20 18:43:26 +00002498 : (*PI)->getType();
Steve Naroff66c842f2008-10-29 14:49:46 +00002499 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffd896f4b2008-12-11 21:05:33 +00002500 if (isTopLevelBlockPointerType(t)) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002501 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroff66c842f2008-10-29 14:49:46 +00002502 t = Context->getPointerType(BPT->getPointeeType());
2503 }
Steve Naroff4242b972007-11-05 14:36:37 +00002504 ArgTypes.push_back(t);
2505 }
Chris Lattner5c6b2c62009-02-20 18:43:26 +00002506 returnType = OMD->getResultType()->isObjCQualifiedIdType()
2507 ? Context->getObjCIdType() : OMD->getResultType();
Steve Naroff0744c472007-11-04 22:37:50 +00002508 } else {
Ted Kremenek42730c52008-01-07 19:49:32 +00002509 returnType = Context->getObjCIdType();
Steve Naroff0744c472007-11-04 22:37:50 +00002510 }
2511 // Get the type, we will need to reference it in a couple spots.
Steve Naroff764c1ae2007-11-15 10:28:18 +00002512 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroff0744c472007-11-04 22:37:50 +00002513
2514 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek0c97e042009-02-07 01:47:29 +00002515 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002516 SourceLocation());
Steve Naroff0744c472007-11-04 22:37:50 +00002517
2518 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2519 // If we don't do this cast, we get the following bizarre warning/note:
2520 // xx.m:13: warning: function called through a non-compatible type
2521 // xx.m:13: note: if this code is reached, the program will abort
Anders Carlsson7ef181c2009-07-31 00:48:10 +00002522 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy),
2523 CastExpr::CK_Unknown, DRE,
Douglas Gregor21a04f32008-10-27 19:41:14 +00002524 Context->getPointerType(Context->VoidTy),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002525 SourceLocation(), SourceLocation());
Steve Naroff29fe7462007-11-15 12:35:21 +00002526
Steve Naroff0744c472007-11-04 22:37:50 +00002527 // Now do the "normal" pointer to function cast.
2528 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00002529 &ArgTypes[0], ArgTypes.size(),
Steve Naroff3b8b4e32008-03-18 02:02:04 +00002530 // If we don't have a method decl, force a variadic cast.
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002531 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Naroff0744c472007-11-04 22:37:50 +00002532 castType = Context->getPointerType(castType);
Anders Carlsson7ef181c2009-07-31 00:48:10 +00002533 cast = new (Context) CStyleCastExpr(castType, CastExpr::CK_Unknown, cast,
2534 castType, SourceLocation(),
2535 SourceLocation());
Steve Naroff0744c472007-11-04 22:37:50 +00002536
2537 // Don't forget the parens to enforce the proper binding.
Ted Kremenek0c97e042009-02-07 01:47:29 +00002538 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Steve Naroff0744c472007-11-04 22:37:50 +00002539
2540 const FunctionType *FT = msgSendType->getAsFunctionType();
Ted Kremenek362abcd2009-02-09 20:51:47 +00002541 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2542 MsgExprs.size(),
2543 FT->getResultType(), SourceLocation());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002544 Stmt *ReplacingStmt = CE;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002545 if (MsgSendStretFlavor) {
2546 // We have the method which returns a struct/union. Must also generate
2547 // call to objc_msgSend_stret and hang both varieties on a conditional
2548 // expression which dictate which one to envoke depending on size of
2549 // method's return type.
2550
2551 // Create a reference to the objc_msgSend_stret() declaration.
Ted Kremenek0c97e042009-02-07 01:47:29 +00002552 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002553 SourceLocation());
2554 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Anders Carlsson7ef181c2009-07-31 00:48:10 +00002555 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy),
2556 CastExpr::CK_Unknown, STDRE,
Douglas Gregor21a04f32008-10-27 19:41:14 +00002557 Context->getPointerType(Context->VoidTy),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002558 SourceLocation(), SourceLocation());
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002559 // Now do the "normal" pointer to function cast.
2560 castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00002561 &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002562 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002563 castType = Context->getPointerType(castType);
Anders Carlsson7ef181c2009-07-31 00:48:10 +00002564 cast = new (Context) CStyleCastExpr(castType, CastExpr::CK_Unknown,
2565 cast, castType, SourceLocation(), SourceLocation());
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002566
2567 // Don't forget the parens to enforce the proper binding.
Ted Kremenek0c97e042009-02-07 01:47:29 +00002568 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002569
2570 FT = msgSendType->getAsFunctionType();
Ted Kremenek362abcd2009-02-09 20:51:47 +00002571 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2572 MsgExprs.size(),
2573 FT->getResultType(), SourceLocation());
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002574
2575 // Build sizeof(returnType)
Douglas Gregor396f1142009-03-13 21:01:28 +00002576 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
2577 returnType,
Sebastian Redl0cb7c872008-11-11 17:56:53 +00002578 Context->getSizeType(),
2579 SourceLocation(), SourceLocation());
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002580 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2581 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2582 // For X86 it is more complicated and some kind of target specific routine
2583 // is needed to decide what to do.
Chris Lattner8cd0e932008-03-05 18:54:05 +00002584 unsigned IntSize =
2585 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Ted Kremenek0c97e042009-02-07 01:47:29 +00002586 IntegerLiteral *limit = new (Context) IntegerLiteral(llvm::APInt(IntSize, 8),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002587 Context->IntTy,
2588 SourceLocation());
Ted Kremenek0c97e042009-02-07 01:47:29 +00002589 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002590 BinaryOperator::LE,
2591 Context->IntTy,
2592 SourceLocation());
2593 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2594 ConditionalOperator *CondExpr =
Ted Kremenek0c97e042009-02-07 01:47:29 +00002595 new (Context) ConditionalOperator(lessThanExpr, CE, STCE, returnType);
2596 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002597 }
Steve Naroff450d2fc2009-04-29 16:37:50 +00002598 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002599 return ReplacingStmt;
2600}
2601
Steve Naroff44e81222008-04-14 22:03:09 +00002602Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002603 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroffe8efe892008-10-27 20:54:44 +00002604
Steve Naroff71226032007-10-24 22:48:43 +00002605 // Now do the actual rewrite.
Chris Lattnerb1548372008-01-31 19:37:57 +00002606 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff71226032007-10-24 22:48:43 +00002607
Steve Naroff102c3f22008-12-04 23:50:32 +00002608 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002609 return ReplacingStmt;
Steve Naroffe9780582007-10-23 23:50:29 +00002610}
2611
Steve Naroff450d2fc2009-04-29 16:37:50 +00002612// typedef struct objc_object Protocol;
2613QualType RewriteObjC::getProtocolType() {
2614 if (!ProtocolTypeDecl) {
2615 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
2616 SourceLocation(),
2617 &Context->Idents.get("Protocol"),
2618 Context->getObjCIdType());
2619 }
2620 return Context->getTypeDeclType(ProtocolTypeDecl);
2621}
2622
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002623/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroff450d2fc2009-04-29 16:37:50 +00002624/// a synthesized/forward data reference (to the protocol's metadata).
2625/// The forward references (and metadata) are generated in
2626/// RewriteObjC::HandleTranslationUnit().
Steve Naroff44e81222008-04-14 22:03:09 +00002627Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroff450d2fc2009-04-29 16:37:50 +00002628 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
2629 IdentifierInfo *ID = &Context->Idents.get(Name);
2630 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +00002631 ID, QualType()/*UNUSED*/, 0, VarDecl::Extern);
Steve Naroff450d2fc2009-04-29 16:37:50 +00002632 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), SourceLocation());
2633 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
2634 Context->getPointerType(DRE->getType()),
2635 SourceLocation());
Anders Carlsson7ef181c2009-07-31 00:48:10 +00002636 CastExpr *castExpr = new (Context) CStyleCastExpr(DerefExpr->getType(),
2637 CastExpr::CK_Unknown,
2638 DerefExpr, DerefExpr->getType(),
Steve Naroff450d2fc2009-04-29 16:37:50 +00002639 SourceLocation(), SourceLocation());
2640 ReplaceStmt(Exp, castExpr);
2641 ProtocolExprDecls.insert(Exp->getProtocol());
2642 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
2643 return castExpr;
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002644
2645}
2646
Steve Naroffef82b742008-05-31 14:15:04 +00002647bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
2648 const char *endBuf) {
2649 while (startBuf < endBuf) {
2650 if (*startBuf == '#') {
2651 // Skip whitespace.
2652 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2653 ;
2654 if (!strncmp(startBuf, "if", strlen("if")) ||
2655 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2656 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2657 !strncmp(startBuf, "define", strlen("define")) ||
2658 !strncmp(startBuf, "undef", strlen("undef")) ||
2659 !strncmp(startBuf, "else", strlen("else")) ||
2660 !strncmp(startBuf, "elif", strlen("elif")) ||
2661 !strncmp(startBuf, "endif", strlen("endif")) ||
2662 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2663 !strncmp(startBuf, "include", strlen("include")) ||
2664 !strncmp(startBuf, "import", strlen("import")) ||
2665 !strncmp(startBuf, "include_next", strlen("include_next")))
2666 return true;
2667 }
2668 startBuf++;
2669 }
2670 return false;
2671}
2672
Ted Kremenek42730c52008-01-07 19:49:32 +00002673/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002674/// an objective-c class with ivars.
Steve Naroff44e81222008-04-14 22:03:09 +00002675void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002676 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002677 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Chris Lattnerd120b9e2008-11-24 03:54:41 +00002678 assert(CDecl->getNameAsCString() &&
Douglas Gregor24afd4a2008-11-17 14:58:09 +00002679 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00002680 // Do not synthesize more than once.
Ted Kremenek42730c52008-01-07 19:49:32 +00002681 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00002682 return;
Ted Kremenek42730c52008-01-07 19:49:32 +00002683 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerec4979b2008-03-16 21:08:55 +00002684 int NumIvars = CDecl->ivar_size();
Steve Naroff2c7afc92007-11-14 19:25:57 +00002685 SourceLocation LocStart = CDecl->getLocStart();
2686 SourceLocation LocEnd = CDecl->getLocEnd();
2687
2688 const char *startBuf = SM->getCharacterData(LocStart);
2689 const char *endBuf = SM->getCharacterData(LocEnd);
Steve Naroffef82b742008-05-31 14:15:04 +00002690
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002691 // If no ivars and no root or if its root, directly or indirectly,
2692 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerec4979b2008-03-16 21:08:55 +00002693 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2694 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattnere1be6022009-04-14 23:22:57 +00002695 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Chris Lattnerb8a1b042008-01-31 19:51:04 +00002696 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002697 return;
2698 }
2699
2700 // FIXME: This has potential of causing problem. If
Ted Kremenek42730c52008-01-07 19:49:32 +00002701 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002702 Result += "\nstruct ";
Chris Lattner271d4c22008-11-24 05:29:24 +00002703 Result += CDecl->getNameAsString();
Steve Naroffde0da102008-03-10 23:16:54 +00002704 if (LangOpts.Microsoft)
2705 Result += "_IMPL";
Steve Naroff60dfb6b2008-03-12 00:25:36 +00002706
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002707 if (NumIvars > 0) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00002708 const char *cursor = strchr(startBuf, '{');
2709 assert((cursor && endBuf)
Ted Kremenek42730c52008-01-07 19:49:32 +00002710 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffef82b742008-05-31 14:15:04 +00002711 // If the buffer contains preprocessor directives, we do more fine-grained
2712 // rewrites. This is intended to fix code that looks like (which occurs in
2713 // NSURL.h, for example):
2714 //
2715 // #ifdef XYZ
2716 // @interface Foo : NSObject
2717 // #else
2718 // @interface FooBar : NSObject
2719 // #endif
2720 // {
2721 // int i;
2722 // }
2723 // @end
2724 //
2725 // This clause is segregated to avoid breaking the common case.
2726 if (BufferContainsPPDirectives(startBuf, cursor)) {
2727 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
2728 CDecl->getClassLoc();
2729 const char *endHeader = SM->getCharacterData(L);
Chris Lattnere1be6022009-04-14 23:22:57 +00002730 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffef82b742008-05-31 14:15:04 +00002731
Chris Lattner179fd522009-02-20 18:18:36 +00002732 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffef82b742008-05-31 14:15:04 +00002733 // advance to the end of the referenced protocols.
2734 while (endHeader < cursor && *endHeader != '>') endHeader++;
2735 endHeader++;
2736 }
2737 // rewrite the original header
2738 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2739 } else {
2740 // rewrite the original header *without* disturbing the '{'
2741 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
2742 }
Ted Kremenek42730c52008-01-07 19:49:32 +00002743 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00002744 Result = "\n struct ";
Chris Lattner271d4c22008-11-24 05:29:24 +00002745 Result += RCDecl->getNameAsString();
Steve Naroffcbf88fe2008-03-12 21:09:20 +00002746 Result += "_IMPL ";
Chris Lattner271d4c22008-11-24 05:29:24 +00002747 Result += RCDecl->getNameAsString();
Steve Naroff4850dfe2008-03-12 21:22:52 +00002748 Result += "_IVARS;\n";
Steve Naroff2c7afc92007-11-14 19:25:57 +00002749
2750 // insert the super class structure definition.
Chris Lattner6216f292008-01-31 19:42:41 +00002751 SourceLocation OnePastCurly =
2752 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2753 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Naroff2c7afc92007-11-14 19:25:57 +00002754 }
2755 cursor++; // past '{'
2756
2757 // Now comment out any visibility specifiers.
2758 while (cursor < endBuf) {
2759 if (*cursor == '@') {
2760 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf04ead52007-11-14 22:57:51 +00002761 // Skip whitespace.
2762 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2763 /*scan*/;
2764
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002765 // FIXME: presence of @public, etc. inside comment results in
2766 // this transformation as well, which is still correct c-code.
Steve Naroff2c7afc92007-11-14 19:25:57 +00002767 if (!strncmp(cursor, "public", strlen("public")) ||
2768 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffa93924a2008-04-04 22:34:24 +00002769 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002770 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattner6216f292008-01-31 19:42:41 +00002771 InsertText(atLoc, "// ", 3);
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002772 }
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002773 // FIXME: If there are cases where '<' is used in ivar declaration part
2774 // of user code, then scan the ivar list and use needToScanForQualifiers
2775 // for type checking.
2776 else if (*cursor == '<') {
2777 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner6216f292008-01-31 19:42:41 +00002778 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002779 cursor = strchr(cursor, '>');
2780 cursor++;
2781 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner6216f292008-01-31 19:42:41 +00002782 InsertText(atLoc, " */", 3);
Steve Naroff6449c6c2008-10-30 12:09:33 +00002783 } else if (*cursor == '^') { // rewrite block specifier.
2784 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2785 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002786 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00002787 cursor++;
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002788 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00002789 // Don't forget to add a ';'!!
Chris Lattner6216f292008-01-31 19:42:41 +00002790 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Naroff2c7afc92007-11-14 19:25:57 +00002791 } else { // we don't have any instance variables - insert super struct.
Chris Lattnere1be6022009-04-14 23:22:57 +00002792 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Naroff2c7afc92007-11-14 19:25:57 +00002793 Result += " {\n struct ";
Chris Lattner271d4c22008-11-24 05:29:24 +00002794 Result += RCDecl->getNameAsString();
Steve Naroffcbf88fe2008-03-12 21:09:20 +00002795 Result += "_IMPL ";
Chris Lattner271d4c22008-11-24 05:29:24 +00002796 Result += RCDecl->getNameAsString();
Steve Naroff4850dfe2008-03-12 21:22:52 +00002797 Result += "_IVARS;\n};\n";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00002798 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002799 }
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002800 // Mark this struct as having been generated.
Ted Kremenek42730c52008-01-07 19:49:32 +00002801 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Naroff04eaa192008-05-06 18:26:51 +00002802 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002803}
2804
Ted Kremenek42730c52008-01-07 19:49:32 +00002805// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002806/// class methods.
Douglas Gregorcd19b572009-04-23 01:02:12 +00002807template<typename MethodIterator>
2808void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
2809 MethodIterator MethodEnd,
Fariborz Jahaniana3986372007-10-25 00:14:44 +00002810 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002811 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00002812 const char *ClassName,
2813 std::string &Result) {
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002814 if (MethodBegin == MethodEnd) return;
2815
Fariborz Jahanian04455192007-10-22 21:41:37 +00002816 static bool objc_impl_method = false;
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002817 if (!objc_impl_method) {
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002818 /* struct _objc_method {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002819 SEL _cmd;
2820 char *method_types;
2821 void *_imp;
2822 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002823 */
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00002824 Result += "\nstruct _objc_method {\n";
2825 Result += "\tSEL _cmd;\n";
2826 Result += "\tchar *method_types;\n";
2827 Result += "\tvoid *_imp;\n";
2828 Result += "};\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002829
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002830 objc_impl_method = true;
Fariborz Jahanian96b55da2007-10-19 00:36:46 +00002831 }
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002832
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002833 // Build _objc_method_list for class's methods if needed
Steve Naroffc723eec2008-03-11 00:12:29 +00002834
2835 /* struct {
2836 struct _objc_method_list *next_method;
2837 int method_count;
2838 struct _objc_method method_list[];
2839 }
2840 */
Douglas Gregorcd19b572009-04-23 01:02:12 +00002841 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroffc723eec2008-03-11 00:12:29 +00002842 Result += "\nstatic struct {\n";
2843 Result += "\tstruct _objc_method_list *next_method;\n";
2844 Result += "\tint method_count;\n";
2845 Result += "\tstruct _objc_method method_list[";
Douglas Gregorcd19b572009-04-23 01:02:12 +00002846 Result += utostr(NumMethods);
Steve Naroffc723eec2008-03-11 00:12:29 +00002847 Result += "];\n} _OBJC_";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002848 Result += prefix;
2849 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2850 Result += "_METHODS_";
2851 Result += ClassName;
Steve Naroff5ce4a242008-03-12 17:18:30 +00002852 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002853 Result += IsInstanceMethod ? "inst" : "cls";
2854 Result += "_meth\")))= ";
Douglas Gregorcd19b572009-04-23 01:02:12 +00002855 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002856
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002857 Result += "\t,{{(SEL)\"";
Chris Lattner3a8f2942008-11-24 03:33:13 +00002858 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002859 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002860 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002861 Result += "\", \"";
2862 Result += MethodTypeString;
Steve Naroffc723eec2008-03-11 00:12:29 +00002863 Result += "\", (void *)";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002864 Result += MethodInternalNames[*MethodBegin];
2865 Result += "}\n";
2866 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2867 Result += "\t ,{(SEL)\"";
Chris Lattner3a8f2942008-11-24 03:33:13 +00002868 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002869 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002870 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002871 Result += "\", \"";
2872 Result += MethodTypeString;
Steve Naroffc723eec2008-03-11 00:12:29 +00002873 Result += "\", (void *)";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002874 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +00002875 Result += "}\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002876 }
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002877 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002878}
2879
Steve Naroff450d2fc2009-04-29 16:37:50 +00002880/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner0be08822008-07-21 21:32:27 +00002881void RewriteObjC::
Steve Naroff450d2fc2009-04-29 16:37:50 +00002882RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, const char *prefix,
2883 const char *ClassName, std::string &Result) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002884 static bool objc_protocol_methods = false;
Steve Naroff450d2fc2009-04-29 16:37:50 +00002885
2886 // Output struct protocol_methods holder of method selector and type.
2887 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
2888 /* struct protocol_methods {
2889 SEL _cmd;
2890 char *method_types;
2891 }
2892 */
2893 Result += "\nstruct _protocol_methods {\n";
2894 Result += "\tstruct objc_selector *_cmd;\n";
2895 Result += "\tchar *method_types;\n";
2896 Result += "};\n";
2897
2898 objc_protocol_methods = true;
2899 }
2900 // Do not synthesize the protocol more than once.
2901 if (ObjCSynthesizedProtocols.count(PDecl))
2902 return;
2903
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002904 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2905 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
2906 PDecl->instmeth_end());
Steve Naroff450d2fc2009-04-29 16:37:50 +00002907 /* struct _objc_protocol_method_list {
2908 int protocol_method_count;
2909 struct protocol_methods protocols[];
2910 }
Steve Naroff27429432008-03-12 01:06:30 +00002911 */
Steve Naroff450d2fc2009-04-29 16:37:50 +00002912 Result += "\nstatic struct {\n";
2913 Result += "\tint protocol_method_count;\n";
2914 Result += "\tstruct _protocol_methods protocol_methods[";
2915 Result += utostr(NumMethods);
2916 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
2917 Result += PDecl->getNameAsString();
2918 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
2919 "{\n\t" + utostr(NumMethods) + "\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002920
Steve Naroff450d2fc2009-04-29 16:37:50 +00002921 // Output instance methods declared in this protocol.
2922 for (ObjCProtocolDecl::instmeth_iterator
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002923 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroff450d2fc2009-04-29 16:37:50 +00002924 I != E; ++I) {
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002925 if (I == PDecl->instmeth_begin())
Steve Naroff450d2fc2009-04-29 16:37:50 +00002926 Result += "\t ,{{(struct objc_selector *)\"";
2927 else
2928 Result += "\t ,{(struct objc_selector *)\"";
2929 Result += (*I)->getSelector().getAsString().c_str();
2930 std::string MethodTypeString;
2931 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2932 Result += "\", \"";
2933 Result += MethodTypeString;
2934 Result += "\"}\n";
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002935 }
Steve Naroff450d2fc2009-04-29 16:37:50 +00002936 Result += "\t }\n};\n";
2937 }
2938
2939 // Output class methods declared in this protocol.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002940 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
2941 PDecl->classmeth_end());
Steve Naroff450d2fc2009-04-29 16:37:50 +00002942 if (NumMethods > 0) {
2943 /* struct _objc_protocol_method_list {
2944 int protocol_method_count;
2945 struct protocol_methods protocols[];
2946 }
2947 */
2948 Result += "\nstatic struct {\n";
2949 Result += "\tint protocol_method_count;\n";
2950 Result += "\tstruct _protocol_methods protocol_methods[";
2951 Result += utostr(NumMethods);
2952 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
2953 Result += PDecl->getNameAsString();
2954 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2955 "{\n\t";
2956 Result += utostr(NumMethods);
2957 Result += "\n";
2958
2959 // Output instance methods declared in this protocol.
2960 for (ObjCProtocolDecl::classmeth_iterator
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002961 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroff450d2fc2009-04-29 16:37:50 +00002962 I != E; ++I) {
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002963 if (I == PDecl->classmeth_begin())
Steve Naroff450d2fc2009-04-29 16:37:50 +00002964 Result += "\t ,{{(struct objc_selector *)\"";
2965 else
2966 Result += "\t ,{(struct objc_selector *)\"";
2967 Result += (*I)->getSelector().getAsString().c_str();
2968 std::string MethodTypeString;
2969 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2970 Result += "\", \"";
2971 Result += MethodTypeString;
2972 Result += "\"}\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002973 }
Steve Naroff450d2fc2009-04-29 16:37:50 +00002974 Result += "\t }\n};\n";
2975 }
2976
2977 // Output:
2978 /* struct _objc_protocol {
2979 // Objective-C 1.0 extensions
2980 struct _objc_protocol_extension *isa;
2981 char *protocol_name;
2982 struct _objc_protocol **protocol_list;
2983 struct _objc_protocol_method_list *instance_methods;
2984 struct _objc_protocol_method_list *class_methods;
2985 };
2986 */
2987 static bool objc_protocol = false;
2988 if (!objc_protocol) {
2989 Result += "\nstruct _objc_protocol {\n";
2990 Result += "\tstruct _objc_protocol_extension *isa;\n";
2991 Result += "\tchar *protocol_name;\n";
2992 Result += "\tstruct _objc_protocol **protocol_list;\n";
2993 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2994 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002995 Result += "};\n";
2996
Steve Naroff450d2fc2009-04-29 16:37:50 +00002997 objc_protocol = true;
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002998 }
Steve Naroff450d2fc2009-04-29 16:37:50 +00002999
3000 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3001 Result += PDecl->getNameAsString();
3002 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3003 "{\n\t0, \"";
3004 Result += PDecl->getNameAsString();
3005 Result += "\", 0, ";
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00003006 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroff450d2fc2009-04-29 16:37:50 +00003007 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3008 Result += PDecl->getNameAsString();
3009 Result += ", ";
3010 }
3011 else
3012 Result += "0, ";
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00003013 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroff450d2fc2009-04-29 16:37:50 +00003014 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3015 Result += PDecl->getNameAsString();
3016 Result += "\n";
3017 }
3018 else
3019 Result += "0\n";
3020 Result += "};\n";
3021
3022 // Mark this protocol as having been generated.
3023 if (!ObjCSynthesizedProtocols.insert(PDecl))
3024 assert(false && "protocol already synthesized");
3025
3026}
3027
3028void RewriteObjC::
3029RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
3030 const char *prefix, const char *ClassName,
3031 std::string &Result) {
3032 if (Protocols.empty()) return;
3033
3034 for (unsigned i = 0; i != Protocols.size(); i++)
3035 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3036
Chris Lattnera19b5ec2008-07-21 21:33:21 +00003037 // Output the top lovel protocol meta-data for the class.
3038 /* struct _objc_protocol_list {
3039 struct _objc_protocol_list *next;
3040 int protocol_count;
3041 struct _objc_protocol *class_protocols[];
3042 }
3043 */
3044 Result += "\nstatic struct {\n";
3045 Result += "\tstruct _objc_protocol_list *next;\n";
3046 Result += "\tint protocol_count;\n";
3047 Result += "\tstruct _objc_protocol *class_protocols[";
3048 Result += utostr(Protocols.size());
3049 Result += "];\n} _OBJC_";
3050 Result += prefix;
3051 Result += "_PROTOCOLS_";
3052 Result += ClassName;
3053 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3054 "{\n\t0, ";
3055 Result += utostr(Protocols.size());
3056 Result += "\n";
3057
3058 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003059 Result += Protocols[0]->getNameAsString();
Chris Lattnera19b5ec2008-07-21 21:33:21 +00003060 Result += " \n";
3061
3062 for (unsigned i = 1; i != Protocols.size(); i++) {
3063 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003064 Result += Protocols[i]->getNameAsString();
Chris Lattnera19b5ec2008-07-21 21:33:21 +00003065 Result += "\n";
3066 }
3067 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003068}
3069
Steve Naroff450d2fc2009-04-29 16:37:50 +00003070
Ted Kremenek42730c52008-01-07 19:49:32 +00003071/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003072/// implementation.
Steve Naroff44e81222008-04-14 22:03:09 +00003073void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003074 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00003075 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003076 // Find category declaration for this implementation.
Ted Kremenek42730c52008-01-07 19:49:32 +00003077 ObjCCategoryDecl *CDecl;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003078 for (CDecl = ClassDecl->getCategoryList(); CDecl;
3079 CDecl = CDecl->getNextClassCategory())
3080 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3081 break;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003082
Chris Lattner271d4c22008-11-24 05:29:24 +00003083 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnera661a4d2007-12-23 01:40:15 +00003084 FullCategoryName += '_';
Chris Lattner271d4c22008-11-24 05:29:24 +00003085 FullCategoryName += IDecl->getNameAsString();
Steve Naroff450d2fc2009-04-29 16:37:50 +00003086
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003087 // Build _objc_method_list for class's instance methods if needed
Douglas Gregorcd19b572009-04-23 01:02:12 +00003088 llvm::SmallVector<ObjCMethodDecl *, 32>
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00003089 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregorcd19b572009-04-23 01:02:12 +00003090
3091 // If any of our property implementations have associated getters or
3092 // setters, produce metadata for them as well.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00003093 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3094 PropEnd = IDecl->propimpl_end();
Douglas Gregorcd19b572009-04-23 01:02:12 +00003095 Prop != PropEnd; ++Prop) {
3096 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3097 continue;
3098 if (!(*Prop)->getPropertyIvarDecl())
3099 continue;
3100 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3101 if (!PD)
3102 continue;
3103 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3104 InstanceMethods.push_back(Getter);
3105 if (PD->isReadOnly())
3106 continue;
3107 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3108 InstanceMethods.push_back(Setter);
3109 }
3110 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnera661a4d2007-12-23 01:40:15 +00003111 true, "CATEGORY_", FullCategoryName.c_str(),
3112 Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003113
3114 // Build _objc_method_list for class's class methods if needed
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00003115 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnera661a4d2007-12-23 01:40:15 +00003116 false, "CATEGORY_", FullCategoryName.c_str(),
3117 Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003118
3119 // Protocols referenced in class declaration?
Fariborz Jahaniand256e062007-11-13 22:09:49 +00003120 // Null CDecl is case of a category implementation with no category interface
3121 if (CDecl)
Steve Naroff450d2fc2009-04-29 16:37:50 +00003122 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
3123 FullCategoryName.c_str(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003124 /* struct _objc_category {
3125 char *category_name;
3126 char *class_name;
3127 struct _objc_method_list *instance_methods;
3128 struct _objc_method_list *class_methods;
3129 struct _objc_protocol_list *protocols;
3130 // Objective-C 1.0 extensions
3131 uint32_t size; // sizeof (struct _objc_category)
3132 struct _objc_property_list *instance_properties; // category's own
3133 // @property decl.
3134 };
3135 */
3136
3137 static bool objc_category = false;
3138 if (!objc_category) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003139 Result += "\nstruct _objc_category {\n";
3140 Result += "\tchar *category_name;\n";
3141 Result += "\tchar *class_name;\n";
3142 Result += "\tstruct _objc_method_list *instance_methods;\n";
3143 Result += "\tstruct _objc_method_list *class_methods;\n";
3144 Result += "\tstruct _objc_protocol_list *protocols;\n";
3145 Result += "\tunsigned int size;\n";
3146 Result += "\tstruct _objc_property_list *instance_properties;\n";
3147 Result += "};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003148 objc_category = true;
Fariborz Jahanian04455192007-10-22 21:41:37 +00003149 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003150 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3151 Result += FullCategoryName;
Steve Naroff5ce4a242008-03-12 17:18:30 +00003152 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003153 Result += IDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003154 Result += "\"\n\t, \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003155 Result += ClassDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003156 Result += "\"\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003157
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00003158 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003159 Result += "\t, (struct _objc_method_list *)"
3160 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3161 Result += FullCategoryName;
3162 Result += "\n";
3163 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003164 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003165 Result += "\t, 0\n";
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00003166 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003167 Result += "\t, (struct _objc_method_list *)"
3168 "&_OBJC_CATEGORY_CLASS_METHODS_";
3169 Result += FullCategoryName;
3170 Result += "\n";
3171 }
3172 else
3173 Result += "\t, 0\n";
3174
Chris Lattner179fd522009-02-20 18:18:36 +00003175 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003176 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
3177 Result += FullCategoryName;
3178 Result += "\n";
3179 }
3180 else
3181 Result += "\t, 0\n";
3182 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003183}
3184
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00003185/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3186/// ivar offset.
Steve Naroff44e81222008-04-14 22:03:09 +00003187void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
Ted Kremenek42730c52008-01-07 19:49:32 +00003188 ObjCIvarDecl *ivar,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00003189 std::string &Result) {
Steve Naroffd3354222008-07-16 18:22:22 +00003190 if (ivar->isBitField()) {
3191 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3192 // place all bitfields at offset 0.
3193 Result += "0";
3194 } else {
3195 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003196 Result += IDecl->getNameAsString();
Steve Naroffd3354222008-07-16 18:22:22 +00003197 if (LangOpts.Microsoft)
3198 Result += "_IMPL";
3199 Result += ", ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003200 Result += ivar->getNameAsString();
Steve Naroffd3354222008-07-16 18:22:22 +00003201 Result += ")";
3202 }
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00003203}
3204
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003205//===----------------------------------------------------------------------===//
3206// Meta Data Emission
3207//===----------------------------------------------------------------------===//
3208
Steve Naroff44e81222008-04-14 22:03:09 +00003209void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003210 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00003211 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003212
Fariborz Jahanian7e216522007-11-26 20:59:57 +00003213 // Explictly declared @interface's are already synthesized.
Steve Naroff7333b492009-04-20 20:09:33 +00003214 if (CDecl->isImplicitInterfaceDecl()) {
Fariborz Jahanian7e216522007-11-26 20:59:57 +00003215 // FIXME: Implementation of a class with no @interface (legacy) doese not
3216 // produce correct synthesis as yet.
Ted Kremenek42730c52008-01-07 19:49:32 +00003217 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian7e216522007-11-26 20:59:57 +00003218 }
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00003219
Chris Lattnerc7b06752007-12-12 07:56:42 +00003220 // Build _objc_ivar_list metadata for classes ivars if needed
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00003221 unsigned NumIvars = !IDecl->ivar_empty()
3222 ? IDecl->ivar_size()
Chris Lattnerec4979b2008-03-16 21:08:55 +00003223 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003224 if (NumIvars > 0) {
3225 static bool objc_ivar = false;
3226 if (!objc_ivar) {
3227 /* struct _objc_ivar {
3228 char *ivar_name;
3229 char *ivar_type;
3230 int ivar_offset;
3231 };
3232 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003233 Result += "\nstruct _objc_ivar {\n";
3234 Result += "\tchar *ivar_name;\n";
3235 Result += "\tchar *ivar_type;\n";
3236 Result += "\tint ivar_offset;\n";
3237 Result += "};\n";
3238
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003239 objc_ivar = true;
3240 }
3241
Steve Naroffc723eec2008-03-11 00:12:29 +00003242 /* struct {
3243 int ivar_count;
3244 struct _objc_ivar ivar_list[nIvars];
3245 };
3246 */
3247 Result += "\nstatic struct {\n";
3248 Result += "\tint ivar_count;\n";
3249 Result += "\tstruct _objc_ivar ivar_list[";
3250 Result += utostr(NumIvars);
3251 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003252 Result += IDecl->getNameAsString();
Steve Naroff5ce4a242008-03-12 17:18:30 +00003253 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003254 "{\n\t";
3255 Result += utostr(NumIvars);
3256 Result += "\n";
Chris Lattnerc7b06752007-12-12 07:56:42 +00003257
Ted Kremenek42730c52008-01-07 19:49:32 +00003258 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor087dbf32009-04-23 03:23:08 +00003259 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00003260 if (!IDecl->ivar_empty()) {
Douglas Gregor087dbf32009-04-23 03:23:08 +00003261 for (ObjCImplementationDecl::ivar_iterator
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00003262 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor087dbf32009-04-23 03:23:08 +00003263 IV != IVEnd; ++IV)
3264 IVars.push_back(*IV);
3265 IVI = IVars.begin();
3266 IVE = IVars.end();
Chris Lattnerc7b06752007-12-12 07:56:42 +00003267 } else {
3268 IVI = CDecl->ivar_begin();
3269 IVE = CDecl->ivar_end();
3270 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003271 Result += "\t,{{\"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003272 Result += (*IVI)->getNameAsString();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00003273 Result += "\", \"";
Steve Naroff450d2fc2009-04-29 16:37:50 +00003274 std::string TmpString, StrEncoding;
3275 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3276 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00003277 Result += StrEncoding;
3278 Result += "\", ";
Chris Lattnerc7b06752007-12-12 07:56:42 +00003279 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00003280 Result += "}\n";
Chris Lattnerc7b06752007-12-12 07:56:42 +00003281 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003282 Result += "\t ,{\"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003283 Result += (*IVI)->getNameAsString();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00003284 Result += "\", \"";
Steve Naroff450d2fc2009-04-29 16:37:50 +00003285 std::string TmpString, StrEncoding;
3286 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3287 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00003288 Result += StrEncoding;
3289 Result += "\", ";
Chris Lattnerc7b06752007-12-12 07:56:42 +00003290 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00003291 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003292 }
3293
3294 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003295 }
3296
3297 // Build _objc_method_list for class's instance methods if needed
Douglas Gregorcd19b572009-04-23 01:02:12 +00003298 llvm::SmallVector<ObjCMethodDecl *, 32>
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00003299 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregorcd19b572009-04-23 01:02:12 +00003300
3301 // If any of our property implementations have associated getters or
3302 // setters, produce metadata for them as well.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00003303 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3304 PropEnd = IDecl->propimpl_end();
Douglas Gregorcd19b572009-04-23 01:02:12 +00003305 Prop != PropEnd; ++Prop) {
3306 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3307 continue;
3308 if (!(*Prop)->getPropertyIvarDecl())
3309 continue;
3310 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3311 if (!PD)
3312 continue;
3313 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3314 InstanceMethods.push_back(Getter);
3315 if (PD->isReadOnly())
3316 continue;
3317 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3318 InstanceMethods.push_back(Setter);
3319 }
3320 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnerd120b9e2008-11-24 03:54:41 +00003321 true, "", IDecl->getNameAsCString(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003322
3323 // Build _objc_method_list for class's class methods if needed
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00003324 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerd120b9e2008-11-24 03:54:41 +00003325 false, "", IDecl->getNameAsCString(), Result);
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003326
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003327 // Protocols referenced in class declaration?
Steve Naroff450d2fc2009-04-29 16:37:50 +00003328 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
3329 "CLASS", CDecl->getNameAsCString(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003330
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003331 // Declaration of class/meta-class metadata
3332 /* struct _objc_class {
3333 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003334 const char *super_class_name;
3335 char *name;
3336 long version;
3337 long info;
3338 long instance_size;
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003339 struct _objc_ivar_list *ivars;
3340 struct _objc_method_list *methods;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003341 struct objc_cache *cache;
3342 struct objc_protocol_list *protocols;
3343 const char *ivar_layout;
3344 struct _objc_class_ext *ext;
3345 };
3346 */
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003347 static bool objc_class = false;
3348 if (!objc_class) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003349 Result += "\nstruct _objc_class {\n";
3350 Result += "\tstruct _objc_class *isa;\n";
3351 Result += "\tconst char *super_class_name;\n";
3352 Result += "\tchar *name;\n";
3353 Result += "\tlong version;\n";
3354 Result += "\tlong info;\n";
3355 Result += "\tlong instance_size;\n";
3356 Result += "\tstruct _objc_ivar_list *ivars;\n";
3357 Result += "\tstruct _objc_method_list *methods;\n";
3358 Result += "\tstruct objc_cache *cache;\n";
3359 Result += "\tstruct _objc_protocol_list *protocols;\n";
3360 Result += "\tconst char *ivar_layout;\n";
3361 Result += "\tstruct _objc_class_ext *ext;\n";
3362 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003363 objc_class = true;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003364 }
3365
3366 // Meta-class metadata generation.
Ted Kremenek42730c52008-01-07 19:49:32 +00003367 ObjCInterfaceDecl *RootClass = 0;
3368 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003369 while (SuperClass) {
3370 RootClass = SuperClass;
3371 SuperClass = SuperClass->getSuperClass();
3372 }
3373 SuperClass = CDecl->getSuperClass();
3374
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003375 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003376 Result += CDecl->getNameAsString();
Steve Naroff5ce4a242008-03-12 17:18:30 +00003377 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003378 "{\n\t(struct _objc_class *)\"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003379 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003380 Result += "\"";
3381
3382 if (SuperClass) {
3383 Result += ", \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003384 Result += SuperClass->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003385 Result += "\", \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003386 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003387 Result += "\"";
3388 }
3389 else {
3390 Result += ", 0, \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003391 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003392 Result += "\"";
3393 }
Ted Kremenek42730c52008-01-07 19:49:32 +00003394 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003395 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003396 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00003397 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroffdee066b2008-03-11 18:14:26 +00003398 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003399 Result += IDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003400 Result += "\n";
3401 }
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003402 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003403 Result += ", 0\n";
Chris Lattner179fd522009-02-20 18:18:36 +00003404 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff27429432008-03-12 01:06:30 +00003405 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003406 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003407 Result += ",0,0\n";
3408 }
Fariborz Jahanian0cb4d922007-10-24 20:54:23 +00003409 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003410 Result += "\t,0,0,0,0\n";
3411 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003412
3413 // class metadata generation.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003414 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003415 Result += CDecl->getNameAsString();
Steve Naroff5ce4a242008-03-12 17:18:30 +00003416 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003417 "{\n\t&_OBJC_METACLASS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003418 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003419 if (SuperClass) {
3420 Result += ", \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003421 Result += SuperClass->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003422 Result += "\", \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003423 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003424 Result += "\"";
3425 }
3426 else {
3427 Result += ", 0, \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003428 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003429 Result += "\"";
3430 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003431 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00003432 Result += ", 0,1";
Ted Kremenek42730c52008-01-07 19:49:32 +00003433 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00003434 Result += ",0";
3435 else {
3436 // class has size. Must synthesize its size.
Fariborz Jahanian9447e462007-11-05 17:47:33 +00003437 Result += ",sizeof(struct ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003438 Result += CDecl->getNameAsString();
Steve Naroffc302e5b2008-03-10 23:33:22 +00003439 if (LangOpts.Microsoft)
3440 Result += "_IMPL";
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00003441 Result += ")";
3442 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003443 if (NumIvars > 0) {
Steve Naroffbec4bf52008-03-11 17:37:02 +00003444 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003445 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003446 Result += "\n\t";
3447 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003448 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003449 Result += ",0";
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00003450 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroffc723eec2008-03-11 00:12:29 +00003451 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003452 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003453 Result += ", 0\n\t";
3454 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003455 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003456 Result += ",0,0";
Chris Lattner179fd522009-02-20 18:18:36 +00003457 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff27429432008-03-12 01:06:30 +00003458 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003459 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003460 Result += ", 0,0\n";
3461 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003462 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003463 Result += ",0,0,0\n";
3464 Result += "};\n";
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003465}
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00003466
Fariborz Jahanian8c664912007-11-13 19:21:13 +00003467/// RewriteImplementations - This routine rewrites all method implementations
3468/// and emits meta-data.
3469
Steve Naroff21658f62008-11-13 20:07:04 +00003470void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003471 int ClsDefCount = ClassImplementation.size();
3472 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian8c664912007-11-13 19:21:13 +00003473
Fariborz Jahanian8c664912007-11-13 19:21:13 +00003474 // Rewrite implemented methods
3475 for (int i = 0; i < ClsDefCount; i++)
3476 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00003477
Fariborz Jahanian0136e372007-11-13 20:04:28 +00003478 for (int i = 0; i < CatDefCount; i++)
3479 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Naroff21658f62008-11-13 20:07:04 +00003480}
Fariborz Jahanian0136e372007-11-13 20:04:28 +00003481
Steve Naroff21658f62008-11-13 20:07:04 +00003482void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3483 int ClsDefCount = ClassImplementation.size();
3484 int CatDefCount = CategoryImplementation.size();
3485
Steve Naroff5bf10222008-05-07 21:23:49 +00003486 // This is needed for determining instance variable offsets.
Steve Naroff314c1a62008-08-05 18:47:23 +00003487 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003488 // For each implemented class, write out all its meta data.
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00003489 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek42730c52008-01-07 19:49:32 +00003490 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003491
3492 // For each implemented category, write out all its meta data.
3493 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek42730c52008-01-07 19:49:32 +00003494 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroff450d2fc2009-04-29 16:37:50 +00003495
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003496 // Write objc_symtab metadata
3497 /*
3498 struct _objc_symtab
3499 {
3500 long sel_ref_cnt;
3501 SEL *refs;
3502 short cls_def_cnt;
3503 short cat_def_cnt;
3504 void *defs[cls_def_cnt + cat_def_cnt];
3505 };
3506 */
3507
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003508 Result += "\nstruct _objc_symtab {\n";
3509 Result += "\tlong sel_ref_cnt;\n";
3510 Result += "\tSEL *refs;\n";
3511 Result += "\tshort cls_def_cnt;\n";
3512 Result += "\tshort cat_def_cnt;\n";
3513 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3514 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003515
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003516 Result += "static struct _objc_symtab "
Steve Naroff5ce4a242008-03-12 17:18:30 +00003517 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003518 Result += "\t0, 0, " + utostr(ClsDefCount)
3519 + ", " + utostr(CatDefCount) + "\n";
3520 for (int i = 0; i < ClsDefCount; i++) {
3521 Result += "\t,&_OBJC_CLASS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003522 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003523 Result += "\n";
3524 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003525
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003526 for (int i = 0; i < CatDefCount; i++) {
3527 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003528 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003529 Result += "_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003530 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003531 Result += "\n";
3532 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003533
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003534 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003535
3536 // Write objc_module metadata
3537
3538 /*
3539 struct _objc_module {
3540 long version;
3541 long size;
3542 const char *name;
3543 struct _objc_symtab *symtab;
3544 }
3545 */
3546
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003547 Result += "\nstruct _objc_module {\n";
3548 Result += "\tlong version;\n";
3549 Result += "\tlong size;\n";
3550 Result += "\tconst char *name;\n";
3551 Result += "\tstruct _objc_symtab *symtab;\n";
3552 Result += "};\n\n";
3553 Result += "static struct _objc_module "
Steve Naroff5ce4a242008-03-12 17:18:30 +00003554 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00003555 Result += "\t" + utostr(OBJC_ABI_VERSION) +
3556 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003557 Result += "};\n\n";
Steve Naroff7fd0aff2008-03-10 20:43:59 +00003558
3559 if (LangOpts.Microsoft) {
Steve Naroff450d2fc2009-04-29 16:37:50 +00003560 if (ProtocolExprDecls.size()) {
3561 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
3562 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
3563 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
3564 E = ProtocolExprDecls.end(); I != E; ++I) {
3565 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
3566 Result += (*I)->getNameAsString();
3567 Result += " = &_OBJC_PROTOCOL_";
3568 Result += (*I)->getNameAsString();
3569 Result += ";\n";
3570 }
3571 Result += "#pragma data_seg(pop)\n\n";
3572 }
Steve Naroff7fd0aff2008-03-10 20:43:59 +00003573 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroffbdd2dba2008-05-07 00:06:16 +00003574 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff7fd0aff2008-03-10 20:43:59 +00003575 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3576 Result += "&_OBJC_MODULES;\n";
3577 Result += "#pragma data_seg(pop)\n\n";
3578 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003579}
Chris Lattner6fe8b272007-10-16 22:36:42 +00003580
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003581std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3582 const char *funcName,
3583 std::string Tag) {
3584 const FunctionType *AFT = CE->getFunctionType();
3585 QualType RT = AFT->getResultType();
3586 std::string StructRef = "struct " + Tag;
3587 std::string S = "static " + RT.getAsString() + " __" +
3588 funcName + "_" + "block_func_" + utostr(i);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00003589
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003590 BlockDecl *BD = CE->getBlockDecl();
3591
Douglas Gregor4fa58902009-02-26 23:50:07 +00003592 if (isa<FunctionNoProtoType>(AFT)) {
Steve Naroff16478cf2009-02-02 17:19:26 +00003593 // No user-supplied arguments. Still need to pass in a pointer to the
3594 // block (to reference imported block decl refs).
3595 S += "(" + StructRef + " *__cself)";
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003596 } else if (BD->param_empty()) {
3597 S += "(" + StructRef + " *__cself)";
3598 } else {
Douglas Gregor4fa58902009-02-26 23:50:07 +00003599 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003600 assert(FT && "SynthesizeBlockFunc: No function proto");
3601 S += '(';
3602 // first add the implicit argument.
3603 S += StructRef + " *__cself, ";
3604 std::string ParamStr;
3605 for (BlockDecl::param_iterator AI = BD->param_begin(),
3606 E = BD->param_end(); AI != E; ++AI) {
3607 if (AI != BD->param_begin()) S += ", ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003608 ParamStr = (*AI)->getNameAsString();
Douglas Gregor3bf3bbc2009-05-29 20:38:28 +00003609 (*AI)->getType().getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003610 S += ParamStr;
3611 }
3612 if (FT->isVariadic()) {
3613 if (!BD->param_empty()) S += ", ";
3614 S += "...";
3615 }
3616 S += ')';
3617 }
3618 S += " {\n";
3619
3620 // Create local declarations to avoid rewriting all closure decl ref exprs.
3621 // First, emit a declaration for all "by ref" decls.
3622 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3623 E = BlockByRefDecls.end(); I != E; ++I) {
3624 S += " ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003625 std::string Name = (*I)->getNameAsString();
Douglas Gregor3bf3bbc2009-05-29 20:38:28 +00003626 Context->getPointerType((*I)->getType()).getAsStringInternal(Name,
3627 Context->PrintingPolicy);
Chris Lattner271d4c22008-11-24 05:29:24 +00003628 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003629 }
3630 // Next, emit a declaration for all "by copy" declarations.
3631 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3632 E = BlockByCopyDecls.end(); I != E; ++I) {
3633 S += " ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003634 std::string Name = (*I)->getNameAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003635 // Handle nested closure invocation. For example:
3636 //
3637 // void (^myImportedClosure)(void);
3638 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3639 //
3640 // void (^anotherClosure)(void);
3641 // anotherClosure = ^(void) {
3642 // myImportedClosure(); // import and invoke the closure
3643 // };
3644 //
Steve Naroffd896f4b2008-12-11 21:05:33 +00003645 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003646 S += "struct __block_impl *";
3647 else
Douglas Gregor3bf3bbc2009-05-29 20:38:28 +00003648 (*I)->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Chris Lattner271d4c22008-11-24 05:29:24 +00003649 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003650 }
3651 std::string RewrittenStr = RewrittenBlockExprs[CE];
3652 const char *cstr = RewrittenStr.c_str();
3653 while (*cstr++ != '{') ;
3654 S += cstr;
3655 S += "\n";
3656 return S;
3657}
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00003658
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003659std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3660 const char *funcName,
3661 std::string Tag) {
3662 std::string StructRef = "struct " + Tag;
3663 std::string S = "static void __";
3664
3665 S += funcName;
3666 S += "_block_copy_" + utostr(i);
3667 S += "(" + StructRef;
3668 S += "*dst, " + StructRef;
3669 S += "*src) {";
3670 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3671 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff44fe1e32008-12-16 15:50:30 +00003672 S += "_Block_object_assign((void*)&dst->";
Chris Lattner271d4c22008-11-24 05:29:24 +00003673 S += (*I)->getNameAsString();
Steve Naroff1d56d9e2008-12-11 20:51:38 +00003674 S += ", (void*)src->";
Chris Lattner271d4c22008-11-24 05:29:24 +00003675 S += (*I)->getNameAsString();
Steve Naroff44fe1e32008-12-16 15:50:30 +00003676 S += ", 3/*BLOCK_FIELD_IS_OBJECT*/);}";
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003677 }
3678 S += "\nstatic void __";
3679 S += funcName;
3680 S += "_block_dispose_" + utostr(i);
3681 S += "(" + StructRef;
3682 S += "*src) {";
3683 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3684 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff44fe1e32008-12-16 15:50:30 +00003685 S += "_Block_object_dispose((void*)src->";
Chris Lattner271d4c22008-11-24 05:29:24 +00003686 S += (*I)->getNameAsString();
Steve Naroff44fe1e32008-12-16 15:50:30 +00003687 S += ", 3/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003688 }
3689 S += "}\n";
3690 return S;
3691}
3692
3693std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3694 bool hasCopyDisposeHelpers) {
Steve Naroff6449c6c2008-10-30 12:09:33 +00003695 std::string S = "\nstruct " + Tag;
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003696 std::string Constructor = " " + Tag;
3697
3698 S += " {\n struct __block_impl impl;\n";
3699
3700 if (hasCopyDisposeHelpers)
3701 S += " void *copy;\n void *dispose;\n";
3702
3703 Constructor += "(void *fp";
3704
3705 if (hasCopyDisposeHelpers)
3706 Constructor += ", void *copyHelp, void *disposeHelp";
3707
3708 if (BlockDeclRefs.size()) {
3709 // Output all "by copy" declarations.
3710 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3711 E = BlockByCopyDecls.end(); I != E; ++I) {
3712 S += " ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003713 std::string FieldName = (*I)->getNameAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003714 std::string ArgName = "_" + FieldName;
3715 // Handle nested closure invocation. For example:
3716 //
3717 // void (^myImportedBlock)(void);
3718 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3719 //
3720 // void (^anotherBlock)(void);
3721 // anotherBlock = ^(void) {
3722 // myImportedBlock(); // import and invoke the closure
3723 // };
3724 //
Steve Naroffd896f4b2008-12-11 21:05:33 +00003725 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003726 S += "struct __block_impl *";
3727 Constructor += ", void *" + ArgName;
3728 } else {
Douglas Gregor3bf3bbc2009-05-29 20:38:28 +00003729 (*I)->getType().getAsStringInternal(FieldName, Context->PrintingPolicy);
3730 (*I)->getType().getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003731 Constructor += ", " + ArgName;
3732 }
3733 S += FieldName + ";\n";
3734 }
3735 // Output all "by ref" declarations.
3736 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3737 E = BlockByRefDecls.end(); I != E; ++I) {
3738 S += " ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003739 std::string FieldName = (*I)->getNameAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003740 std::string ArgName = "_" + FieldName;
3741 // Handle nested closure invocation. For example:
3742 //
3743 // void (^myImportedBlock)(void);
3744 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3745 //
3746 // void (^anotherBlock)(void);
3747 // anotherBlock = ^(void) {
3748 // myImportedBlock(); // import and invoke the closure
3749 // };
3750 //
Steve Naroffd896f4b2008-12-11 21:05:33 +00003751 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003752 S += "struct __block_impl *";
3753 Constructor += ", void *" + ArgName;
3754 } else {
Douglas Gregor3bf3bbc2009-05-29 20:38:28 +00003755 Context->getPointerType((*I)->getType()).getAsStringInternal(FieldName,
3756 Context->PrintingPolicy);
3757 Context->getPointerType((*I)->getType()).getAsStringInternal(ArgName,
3758 Context->PrintingPolicy);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003759 Constructor += ", " + ArgName;
3760 }
3761 S += FieldName + "; // by ref\n";
3762 }
3763 // Finish writing the constructor.
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003764 Constructor += ", int flags=0) {\n";
Steve Naroff450d2fc2009-04-29 16:37:50 +00003765 if (GlobalVarDecl)
3766 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3767 else
3768 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3769 Constructor += " impl.Size = sizeof(";
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003770 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3771
3772 if (hasCopyDisposeHelpers)
3773 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3774
3775 // Initialize all "by copy" arguments.
3776 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3777 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattner271d4c22008-11-24 05:29:24 +00003778 std::string Name = (*I)->getNameAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003779 Constructor += " ";
Steve Naroffd896f4b2008-12-11 21:05:33 +00003780 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003781 Constructor += Name + " = (struct __block_impl *)_";
3782 else
3783 Constructor += Name + " = _";
3784 Constructor += Name + ";\n";
3785 }
3786 // Initialize all "by ref" arguments.
3787 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3788 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattner271d4c22008-11-24 05:29:24 +00003789 std::string Name = (*I)->getNameAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003790 Constructor += " ";
Steve Naroffd896f4b2008-12-11 21:05:33 +00003791 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003792 Constructor += Name + " = (struct __block_impl *)_";
3793 else
3794 Constructor += Name + " = _";
3795 Constructor += Name + ";\n";
3796 }
3797 } else {
3798 // Finish writing the constructor.
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003799 Constructor += ", int flags=0) {\n";
Steve Naroff450d2fc2009-04-29 16:37:50 +00003800 if (GlobalVarDecl)
3801 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3802 else
3803 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3804 Constructor += " impl.Size = sizeof(";
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003805 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3806 if (hasCopyDisposeHelpers)
3807 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3808 }
3809 Constructor += " ";
3810 Constructor += "}\n";
3811 S += Constructor;
3812 S += "};\n";
3813 return S;
3814}
3815
3816void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3817 const char *FunName) {
3818 // Insert closures that were part of the function.
3819 for (unsigned i = 0; i < Blocks.size(); i++) {
3820
3821 CollectBlockDeclRefInfo(Blocks[i]);
3822
3823 std::string Tag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
3824
3825 std::string CI = SynthesizeBlockImpl(Blocks[i], Tag,
3826 ImportedBlockDecls.size() > 0);
3827
3828 InsertText(FunLocStart, CI.c_str(), CI.size());
3829
3830 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, Tag);
3831
3832 InsertText(FunLocStart, CF.c_str(), CF.size());
3833
3834 if (ImportedBlockDecls.size()) {
3835 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, Tag);
3836 InsertText(FunLocStart, HF.c_str(), HF.size());
3837 }
3838
3839 BlockDeclRefs.clear();
3840 BlockByRefDecls.clear();
3841 BlockByCopyDecls.clear();
3842 BlockCallExprs.clear();
3843 ImportedBlockDecls.clear();
3844 }
3845 Blocks.clear();
3846 RewrittenBlockExprs.clear();
3847}
3848
3849void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3850 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattnerd120b9e2008-11-24 03:54:41 +00003851 const char *FuncName = FD->getNameAsCString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003852
3853 SynthesizeBlockLiterals(FunLocStart, FuncName);
3854}
3855
3856void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroff6449c6c2008-10-30 12:09:33 +00003857 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3858 //SourceLocation FunLocStart = MD->getLocStart();
3859 // FIXME: This hack works around a bug in Rewrite.InsertText().
3860 SourceLocation FunLocStart = MD->getLocStart().getFileLocWithOffset(-1);
Chris Lattner3a8f2942008-11-24 03:33:13 +00003861 std::string FuncName = MD->getSelector().getAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003862 // Convert colons to underscores.
3863 std::string::size_type loc = 0;
3864 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3865 FuncName.replace(loc, 1, "_");
3866
3867 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
3868}
3869
3870void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
3871 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3872 CI != E; ++CI)
3873 if (*CI) {
3874 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3875 GetBlockDeclRefExprs(CBE->getBody());
3876 else
3877 GetBlockDeclRefExprs(*CI);
3878 }
3879 // Handle specific things.
3880 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
3881 // FIXME: Handle enums.
3882 if (!isa<FunctionDecl>(CDRE->getDecl()))
3883 BlockDeclRefs.push_back(CDRE);
3884 return;
3885}
3886
3887void RewriteObjC::GetBlockCallExprs(Stmt *S) {
3888 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3889 CI != E; ++CI)
3890 if (*CI) {
3891 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3892 GetBlockCallExprs(CBE->getBody());
3893 else
3894 GetBlockCallExprs(*CI);
3895 }
3896
3897 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
3898 if (CE->getCallee()->getType()->isBlockPointerType()) {
3899 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
3900 }
3901 }
3902 return;
3903}
3904
Steve Naroff85eb17b2008-10-30 10:07:53 +00003905Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp) {
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003906 // Navigate to relevant type information.
3907 const char *closureName = 0;
3908 const BlockPointerType *CPT = 0;
3909
3910 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp->getCallee())) {
Chris Lattnerd120b9e2008-11-24 03:54:41 +00003911 closureName = DRE->getDecl()->getNameAsCString();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003912 CPT = DRE->getType()->getAs<BlockPointerType>();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003913 } else if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(Exp->getCallee())) {
Chris Lattnerd120b9e2008-11-24 03:54:41 +00003914 closureName = CDRE->getDecl()->getNameAsCString();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003915 CPT = CDRE->getType()->getAs<BlockPointerType>();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003916 } else if (MemberExpr *MExpr = dyn_cast<MemberExpr>(Exp->getCallee())) {
Chris Lattnerd120b9e2008-11-24 03:54:41 +00003917 closureName = MExpr->getMemberDecl()->getNameAsCString();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003918 CPT = MExpr->getType()->getAs<BlockPointerType>();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003919 } else {
3920 assert(1 && "RewriteBlockClass: Bad type");
3921 }
3922 assert(CPT && "RewriteBlockClass: Bad type");
3923 const FunctionType *FT = CPT->getPointeeType()->getAsFunctionType();
3924 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor4fa58902009-02-26 23:50:07 +00003925 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003926 // FTP will be null for closures that don't take arguments.
3927
Steve Naroff85eb17b2008-10-30 10:07:53 +00003928 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
3929 SourceLocation(),
3930 &Context->Idents.get("__block_impl"));
3931 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003932
Steve Naroff85eb17b2008-10-30 10:07:53 +00003933 // Generate a funky cast.
3934 llvm::SmallVector<QualType, 8> ArgTypes;
3935
3936 // Push the block argument type.
3937 ArgTypes.push_back(PtrBlock);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003938 if (FTP) {
Douglas Gregor4fa58902009-02-26 23:50:07 +00003939 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff85eb17b2008-10-30 10:07:53 +00003940 E = FTP->arg_type_end(); I && (I != E); ++I) {
3941 QualType t = *I;
3942 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffd896f4b2008-12-11 21:05:33 +00003943 if (isTopLevelBlockPointerType(t)) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003944 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroff85eb17b2008-10-30 10:07:53 +00003945 t = Context->getPointerType(BPT->getPointeeType());
3946 }
3947 ArgTypes.push_back(t);
3948 }
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003949 }
Steve Naroff85eb17b2008-10-30 10:07:53 +00003950 // Now do the pointer to function cast.
3951 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
3952 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
3953
3954 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003955
Anders Carlsson7ef181c2009-07-31 00:48:10 +00003956 CastExpr *BlkCast = new (Context) CStyleCastExpr(PtrBlock,
3957 CastExpr::CK_Unknown,
3958 Exp->getCallee(),
Ted Kremenek0c97e042009-02-07 01:47:29 +00003959 PtrBlock, SourceLocation(),
3960 SourceLocation());
Steve Naroff85eb17b2008-10-30 10:07:53 +00003961 // Don't forget the parens to enforce the proper binding.
Ted Kremenek0c97e042009-02-07 01:47:29 +00003962 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3963 BlkCast);
Steve Naroff85eb17b2008-10-30 10:07:53 +00003964 //PE->dump();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003965
Douglas Gregor8acb7272008-12-11 16:49:14 +00003966 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +00003967 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00003968 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek0c97e042009-02-07 01:47:29 +00003969 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
3970 FD->getType());
Steve Naroff85eb17b2008-10-30 10:07:53 +00003971
Anders Carlsson7ef181c2009-07-31 00:48:10 +00003972 CastExpr *FunkCast = new (Context) CStyleCastExpr(PtrToFuncCastType,
3973 CastExpr::CK_Unknown, ME,
Ted Kremenek0c97e042009-02-07 01:47:29 +00003974 PtrToFuncCastType,
3975 SourceLocation(),
3976 SourceLocation());
3977 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Steve Naroff85eb17b2008-10-30 10:07:53 +00003978
3979 llvm::SmallVector<Expr*, 8> BlkExprs;
3980 // Add the implicit argument.
3981 BlkExprs.push_back(BlkCast);
3982 // Add the user arguments.
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003983 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3984 E = Exp->arg_end(); I != E; ++I) {
Steve Naroff85eb17b2008-10-30 10:07:53 +00003985 BlkExprs.push_back(*I);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003986 }
Ted Kremenek362abcd2009-02-09 20:51:47 +00003987 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
3988 BlkExprs.size(),
Ted Kremenek0c97e042009-02-07 01:47:29 +00003989 Exp->getType(), SourceLocation());
Steve Naroff85eb17b2008-10-30 10:07:53 +00003990 return CE;
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003991}
3992
3993void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Steve Naroff85eb17b2008-10-30 10:07:53 +00003994 Stmt *BlockCall = SynthesizeBlockCall(Exp);
3995 ReplaceStmt(Exp, BlockCall);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003996}
3997
Steve Naroff450d2fc2009-04-29 16:37:50 +00003998// We need to return the rewritten expression to handle cases where the
3999// BlockDeclRefExpr is embedded in another expression being rewritten.
4000// For example:
4001//
4002// int main() {
4003// __block Foo *f;
4004// __block int i;
4005//
4006// void (^myblock)() = ^() {
4007// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4008// i = 77;
4009// };
4010//}
4011Stmt *RewriteObjC::RewriteBlockDeclRefExpr(BlockDeclRefExpr *BDRE) {
Steve Naroff38a9e3f2008-10-27 17:20:55 +00004012 // FIXME: Add more elaborate code generation required by the ABI.
Ted Kremenek0c97e042009-02-07 01:47:29 +00004013 Expr *DerefExpr = new (Context) UnaryOperator(BDRE, UnaryOperator::Deref,
Steve Naroff16478cf2009-02-02 17:19:26 +00004014 Context->getPointerType(BDRE->getType()),
4015 SourceLocation());
4016 // Need parens to enforce precedence.
Ted Kremenek0c97e042009-02-07 01:47:29 +00004017 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), DerefExpr);
Steve Naroff16478cf2009-02-02 17:19:26 +00004018 ReplaceStmt(BDRE, PE);
Steve Naroff450d2fc2009-04-29 16:37:50 +00004019 return PE;
Steve Naroff38a9e3f2008-10-27 17:20:55 +00004020}
4021
Steve Naroff7f1412d2008-11-03 23:29:32 +00004022void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4023 SourceLocation LocStart = CE->getLParenLoc();
4024 SourceLocation LocEnd = CE->getRParenLoc();
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004025
4026 // Need to avoid trying to rewrite synthesized casts.
4027 if (LocStart.isInvalid())
4028 return;
Steve Naroff1c53c022008-11-03 11:20:24 +00004029 // Need to avoid trying to rewrite casts contained in macros.
4030 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4031 return;
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004032
Steve Naroff38a9e3f2008-10-27 17:20:55 +00004033 const char *startBuf = SM->getCharacterData(LocStart);
4034 const char *endBuf = SM->getCharacterData(LocEnd);
4035
4036 // advance the location to startArgList.
4037 const char *argPtr = startBuf;
4038
4039 while (*argPtr++ && (argPtr < endBuf)) {
4040 switch (*argPtr) {
4041 case '^':
4042 // Replace the '^' with '*'.
4043 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
4044 ReplaceText(LocStart, 1, "*", 1);
4045 break;
4046 }
4047 }
4048 return;
4049}
4050
4051void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4052 SourceLocation DeclLoc = FD->getLocation();
4053 unsigned parenCount = 0;
4054
4055 // We have 1 or more arguments that have closure pointers.
4056 const char *startBuf = SM->getCharacterData(DeclLoc);
4057 const char *startArgList = strchr(startBuf, '(');
4058
4059 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4060
4061 parenCount++;
4062 // advance the location to startArgList.
4063 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4064 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4065
4066 const char *argPtr = startArgList;
4067
4068 while (*argPtr++ && parenCount) {
4069 switch (*argPtr) {
4070 case '^':
4071 // Replace the '^' with '*'.
4072 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
4073 ReplaceText(DeclLoc, 1, "*", 1);
4074 break;
4075 case '(':
4076 parenCount++;
4077 break;
4078 case ')':
4079 parenCount--;
4080 break;
4081 }
4082 }
4083 return;
4084}
4085
4086bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor4fa58902009-02-26 23:50:07 +00004087 const FunctionProtoType *FTP;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004088 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00004089 if (PT) {
Douglas Gregor4fa58902009-02-26 23:50:07 +00004090 FTP = PT->getPointeeType()->getAsFunctionProtoType();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00004091 } else {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004092 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00004093 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
Douglas Gregor4fa58902009-02-26 23:50:07 +00004094 FTP = BPT->getPointeeType()->getAsFunctionProtoType();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00004095 }
4096 if (FTP) {
Douglas Gregor4fa58902009-02-26 23:50:07 +00004097 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff38a9e3f2008-10-27 17:20:55 +00004098 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroffd896f4b2008-12-11 21:05:33 +00004099 if (isTopLevelBlockPointerType(*I))
Steve Naroff38a9e3f2008-10-27 17:20:55 +00004100 return true;
4101 }
4102 return false;
4103}
4104
Ted Kremenek0c97e042009-02-07 01:47:29 +00004105void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4106 const char *&RParen) {
Steve Naroff38a9e3f2008-10-27 17:20:55 +00004107 const char *argPtr = strchr(Name, '(');
4108 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4109
4110 LParen = argPtr; // output the start.
4111 argPtr++; // skip past the left paren.
4112 unsigned parenCount = 1;
4113
4114 while (*argPtr && parenCount) {
4115 switch (*argPtr) {
4116 case '(': parenCount++; break;
4117 case ')': parenCount--; break;
4118 default: break;
4119 }
4120 if (parenCount) argPtr++;
4121 }
4122 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4123 RParen = argPtr; // output the end
4124}
4125
4126void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4127 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4128 RewriteBlockPointerFunctionArgs(FD);
4129 return;
4130 }
4131 // Handle Variables and Typedefs.
4132 SourceLocation DeclLoc = ND->getLocation();
4133 QualType DeclT;
4134 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4135 DeclT = VD->getType();
4136 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4137 DeclT = TDD->getUnderlyingType();
4138 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4139 DeclT = FD->getType();
4140 else
4141 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
4142
4143 const char *startBuf = SM->getCharacterData(DeclLoc);
4144 const char *endBuf = startBuf;
4145 // scan backward (from the decl location) for the end of the previous decl.
4146 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4147 startBuf--;
4148
4149 // *startBuf != '^' if we are dealing with a pointer to function that
4150 // may take block argument types (which will be handled below).
4151 if (*startBuf == '^') {
4152 // Replace the '^' with '*', computing a negative offset.
4153 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
4154 ReplaceText(DeclLoc, 1, "*", 1);
4155 }
4156 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4157 // Replace the '^' with '*' for arguments.
4158 DeclLoc = ND->getLocation();
4159 startBuf = SM->getCharacterData(DeclLoc);
4160 const char *argListBegin, *argListEnd;
4161 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4162 while (argListBegin < argListEnd) {
4163 if (*argListBegin == '^') {
4164 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
4165 ReplaceText(CaretLoc, 1, "*", 1);
4166 }
4167 argListBegin++;
4168 }
4169 }
4170 return;
4171}
4172
4173void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
4174 // Add initializers for any closure decl refs.
4175 GetBlockDeclRefExprs(Exp->getBody());
4176 if (BlockDeclRefs.size()) {
4177 // Unique all "by copy" declarations.
4178 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4179 if (!BlockDeclRefs[i]->isByRef())
4180 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
4181 // Unique all "by ref" declarations.
4182 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4183 if (BlockDeclRefs[i]->isByRef()) {
4184 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
4185 }
4186 // Find any imported blocks...they will need special attention.
4187 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Steve Naroff1d56d9e2008-12-11 20:51:38 +00004188 if (BlockDeclRefs[i]->getType()->isBlockPointerType()) {
Steve Naroffe59c8b12008-11-13 17:40:07 +00004189 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00004190 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4191 }
4192 }
4193}
4194
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004195FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
4196 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor4fa58902009-02-26 23:50:07 +00004197 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004198 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +00004199 ID, FType, 0, FunctionDecl::Extern, false,
Douglas Gregor1f88aa72009-02-25 16:33:18 +00004200 false);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004201}
4202
Steve Naroff80c54752008-10-29 18:15:37 +00004203Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004204 Blocks.push_back(Exp);
4205
4206 CollectBlockDeclRefInfo(Exp);
4207 std::string FuncName;
4208
4209 if (CurFunctionDef)
Chris Lattner3a8f2942008-11-24 03:33:13 +00004210 FuncName = CurFunctionDef->getNameAsString();
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004211 else if (CurMethodDef) {
Chris Lattner3a8f2942008-11-24 03:33:13 +00004212 FuncName = CurMethodDef->getSelector().getAsString();
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004213 // Convert colons to underscores.
4214 std::string::size_type loc = 0;
4215 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4216 FuncName.replace(loc, 1, "_");
Steve Naroff80c54752008-10-29 18:15:37 +00004217 } else if (GlobalVarDecl)
Chris Lattner271d4c22008-11-24 05:29:24 +00004218 FuncName = std::string(GlobalVarDecl->getNameAsString());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004219
4220 std::string BlockNumber = utostr(Blocks.size()-1);
4221
4222 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4223 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
4224
4225 // Get a pointer to the function type so we can cast appropriately.
4226 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
4227
4228 FunctionDecl *FD;
4229 Expr *NewRep;
4230
4231 // Simulate a contructor call...
4232 FD = SynthBlockInitFunctionDecl(Tag.c_str());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004233 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004234
4235 llvm::SmallVector<Expr*, 4> InitExprs;
4236
Steve Naroffd0419d62008-10-29 21:23:59 +00004237 // Initialize the block function.
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004238 FD = SynthBlockInitFunctionDecl(Func.c_str());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004239 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
4240 SourceLocation());
Anders Carlsson7ef181c2009-07-31 00:48:10 +00004241 CastExpr *castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy,
4242 CastExpr::CK_Unknown, Arg,
Ted Kremenek0c97e042009-02-07 01:47:29 +00004243 Context->VoidPtrTy, SourceLocation(),
4244 SourceLocation());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004245 InitExprs.push_back(castExpr);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004246
4247 if (ImportedBlockDecls.size()) {
4248 std::string Buf = "__" + FuncName + "_block_copy_" + BlockNumber;
Steve Naroffd0419d62008-10-29 21:23:59 +00004249 FD = SynthBlockInitFunctionDecl(Buf.c_str());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004250 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Anders Carlsson7ef181c2009-07-31 00:48:10 +00004251 castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy,
4252 CastExpr::CK_Unknown, Arg,
Ted Kremenek0c97e042009-02-07 01:47:29 +00004253 Context->VoidPtrTy, SourceLocation(),
4254 SourceLocation());
Steve Naroffd0419d62008-10-29 21:23:59 +00004255 InitExprs.push_back(castExpr);
4256
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004257 Buf = "__" + FuncName + "_block_dispose_" + BlockNumber;
Steve Naroffd0419d62008-10-29 21:23:59 +00004258 FD = SynthBlockInitFunctionDecl(Buf.c_str());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004259 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Anders Carlsson7ef181c2009-07-31 00:48:10 +00004260 castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy,
4261 CastExpr::CK_Unknown, Arg,
Ted Kremenek0c97e042009-02-07 01:47:29 +00004262 Context->VoidPtrTy, SourceLocation(),
4263 SourceLocation());
Steve Naroffd0419d62008-10-29 21:23:59 +00004264 InitExprs.push_back(castExpr);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004265 }
4266 // Add initializers for any closure decl refs.
4267 if (BlockDeclRefs.size()) {
Steve Naroffd0419d62008-10-29 21:23:59 +00004268 Expr *Exp;
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004269 // Output all "by copy" declarations.
4270 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4271 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004272 if (isObjCType((*I)->getType())) {
Steve Naroffd0419d62008-10-29 21:23:59 +00004273 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattnerd120b9e2008-11-24 03:54:41 +00004274 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004275 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroffd896f4b2008-12-11 21:05:33 +00004276 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Chris Lattnerd120b9e2008-11-24 03:54:41 +00004277 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004278 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Anders Carlsson7ef181c2009-07-31 00:48:10 +00004279 Exp = new (Context) CStyleCastExpr(Context->VoidPtrTy,
4280 CastExpr::CK_Unknown, Arg,
4281 Context->VoidPtrTy,
4282 SourceLocation(),
Ted Kremenek0c97e042009-02-07 01:47:29 +00004283 SourceLocation());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004284 } else {
Chris Lattnerd120b9e2008-11-24 03:54:41 +00004285 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004286 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004287 }
Steve Naroffd0419d62008-10-29 21:23:59 +00004288 InitExprs.push_back(Exp);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004289 }
4290 // Output all "by ref" declarations.
4291 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4292 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerd120b9e2008-11-24 03:54:41 +00004293 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004294 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4295 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf,
Steve Naroffd0419d62008-10-29 21:23:59 +00004296 Context->getPointerType(Exp->getType()),
4297 SourceLocation());
Steve Naroff362c7562008-11-14 21:36:12 +00004298 InitExprs.push_back(Exp);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004299 }
4300 }
Ted Kremenek362abcd2009-02-09 20:51:47 +00004301 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4302 FType, SourceLocation());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004303 NewRep = new (Context) UnaryOperator(NewRep, UnaryOperator::AddrOf,
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004304 Context->getPointerType(NewRep->getType()),
4305 SourceLocation());
Anders Carlsson7ef181c2009-07-31 00:48:10 +00004306 NewRep = new (Context) CStyleCastExpr(FType, CastExpr::CK_Unknown, NewRep,
4307 FType, SourceLocation(),
Ted Kremenek0c97e042009-02-07 01:47:29 +00004308 SourceLocation());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004309 BlockDeclRefs.clear();
4310 BlockByRefDecls.clear();
4311 BlockByCopyDecls.clear();
4312 ImportedBlockDecls.clear();
4313 return NewRep;
4314}
4315
4316//===----------------------------------------------------------------------===//
4317// Function Body / Expression rewriting
4318//===----------------------------------------------------------------------===//
4319
Steve Naroff0e948412008-12-04 16:24:46 +00004320// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
4321// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
4322// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
4323// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
4324// Since the rewriter isn't capable of rewriting rewritten code, it's important
4325// we get this right.
4326void RewriteObjC::CollectPropertySetters(Stmt *S) {
4327 // Perform a bottom up traversal of all children.
4328 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4329 CI != E; ++CI)
4330 if (*CI)
4331 CollectPropertySetters(*CI);
4332
4333 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
4334 if (BinOp->isAssignmentOp()) {
4335 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
4336 PropSetters[PRE] = BinOp;
4337 }
4338 }
4339}
4340
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004341Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
4342 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4343 isa<DoStmt>(S) || isa<ForStmt>(S))
4344 Stmts.push_back(S);
4345 else if (isa<ObjCForCollectionStmt>(S)) {
4346 Stmts.push_back(S);
4347 ObjCBcLabelNo.push_back(++BcLabelCount);
4348 }
4349
4350 SourceRange OrigStmtRange = S->getSourceRange();
4351
4352 // Perform a bottom up rewrite of all children.
4353 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4354 CI != E; ++CI)
4355 if (*CI) {
4356 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
4357 if (newStmt)
4358 *CI = newStmt;
4359 }
4360
4361 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4362 // Rewrite the block body in place.
4363 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
4364
4365 // Now we snarf the rewritten text and stash it away for later use.
Steve Naroff80c54752008-10-29 18:15:37 +00004366 std::string Str = Rewrite.getRewritenText(BE->getSourceRange());
4367 RewrittenBlockExprs[BE] = Str;
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004368
4369 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
4370 //blockTranscribed->dump();
Steve Naroff80c54752008-10-29 18:15:37 +00004371 ReplaceStmt(S, blockTranscribed);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004372 return blockTranscribed;
4373 }
4374 // Handle specific things.
4375 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4376 return RewriteAtEncode(AtEncode);
4377
4378 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
4379 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
4380
Steve Naroff0e948412008-12-04 16:24:46 +00004381 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
4382 BinaryOperator *BinOp = PropSetters[PropRefExpr];
4383 if (BinOp) {
4384 // Because the rewriter doesn't allow us to rewrite rewritten code,
4385 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroffedb4bc92008-12-09 12:56:34 +00004386 DisableReplaceStmt = true;
4387 // Save the source range. Even if we disable the replacement, the
4388 // rewritten node will have been inserted into the tree. If the synthesized
4389 // node is at the 'end', the rewriter will fail. Consider this:
4390 // self.errorHandler = handler ? handler :
4391 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
4392 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroff0e948412008-12-04 16:24:46 +00004393 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroffedb4bc92008-12-09 12:56:34 +00004394 DisableReplaceStmt = false;
Steve Naroff102c3f22008-12-04 23:50:32 +00004395 //
4396 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
4397 // we changed the RHS of BinOp, the rewriter would fail (since it needs
4398 // to see the original expression). Consider this example:
4399 //
4400 // Foo *obj1, *obj2;
4401 //
4402 // obj1.i = [obj2 rrrr];
4403 //
4404 // 'BinOp' for the previous expression looks like:
4405 //
4406 // (BinaryOperator 0x231ccf0 'int' '='
4407 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
4408 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
4409 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
4410 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
4411 //
4412 // 'newStmt' represents the rewritten message expression. For example:
4413 //
4414 // (CallExpr 0x231d300 'id':'struct objc_object *'
4415 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
4416 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
4417 // (CStyleCastExpr 0x231d220 'void *'
4418 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
4419 //
4420 // Note that 'newStmt' is passed to RewritePropertySetter so that it
4421 // can be used as the setter argument. ReplaceStmt() will still 'see'
4422 // the original RHS (since we haven't altered BinOp).
4423 //
4424 // This implies the Rewrite* routines can no longer delete the original
4425 // node. As a result, we now leak the original AST nodes.
4426 //
Steve Naroffedb4bc92008-12-09 12:56:34 +00004427 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroff0e948412008-12-04 16:24:46 +00004428 } else {
4429 return RewritePropertyGetter(PropRefExpr);
Steve Narofff6ce8a12008-12-03 00:56:33 +00004430 }
4431 }
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004432 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4433 return RewriteAtSelector(AtSelector);
4434
4435 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4436 return RewriteObjCStringLiteral(AtString);
4437
4438 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroff0e948412008-12-04 16:24:46 +00004439#if 0
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004440 // Before we rewrite it, put the original message expression in a comment.
4441 SourceLocation startLoc = MessExpr->getLocStart();
4442 SourceLocation endLoc = MessExpr->getLocEnd();
4443
4444 const char *startBuf = SM->getCharacterData(startLoc);
4445 const char *endBuf = SM->getCharacterData(endLoc);
4446
4447 std::string messString;
4448 messString += "// ";
4449 messString.append(startBuf, endBuf-startBuf+1);
4450 messString += "\n";
4451
4452 // FIXME: Missing definition of
4453 // InsertText(clang::SourceLocation, char const*, unsigned int).
4454 // InsertText(startLoc, messString.c_str(), messString.size());
4455 // Tried this, but it didn't work either...
4456 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroff0e948412008-12-04 16:24:46 +00004457#endif
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004458 return RewriteMessageExpr(MessExpr);
4459 }
4460
4461 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4462 return RewriteObjCTryStmt(StmtTry);
4463
4464 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4465 return RewriteObjCSynchronizedStmt(StmtTry);
4466
4467 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4468 return RewriteObjCThrowStmt(StmtThrow);
4469
4470 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4471 return RewriteObjCProtocolExpr(ProtocolExp);
4472
4473 if (ObjCForCollectionStmt *StmtForCollection =
4474 dyn_cast<ObjCForCollectionStmt>(S))
4475 return RewriteObjCForCollectionStmt(StmtForCollection,
4476 OrigStmtRange.getEnd());
4477 if (BreakStmt *StmtBreakStmt =
4478 dyn_cast<BreakStmt>(S))
4479 return RewriteBreakStmt(StmtBreakStmt);
4480 if (ContinueStmt *StmtContinueStmt =
4481 dyn_cast<ContinueStmt>(S))
4482 return RewriteContinueStmt(StmtContinueStmt);
4483
4484 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
4485 // and cast exprs.
4486 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4487 // FIXME: What we're doing here is modifying the type-specifier that
4488 // precedes the first Decl. In the future the DeclGroup should have
4489 // a separate type-specifier that we can rewrite.
4490 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
4491
4492 // Blocks rewrite rules.
4493 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4494 DI != DE; ++DI) {
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00004495 Decl *SD = *DI;
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004496 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroffd896f4b2008-12-11 21:05:33 +00004497 if (isTopLevelBlockPointerType(ND->getType()))
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004498 RewriteBlockPointerDecl(ND);
4499 else if (ND->getType()->isFunctionPointerType())
4500 CheckFunctionPointerDecl(ND->getType(), ND);
4501 }
4502 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroffd896f4b2008-12-11 21:05:33 +00004503 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004504 RewriteBlockPointerDecl(TD);
4505 else if (TD->getUnderlyingType()->isFunctionPointerType())
4506 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4507 }
4508 }
4509 }
4510
4511 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4512 RewriteObjCQualifiedInterfaceTypes(CE);
4513
4514 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4515 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4516 assert(!Stmts.empty() && "Statement stack is empty");
4517 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4518 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
4519 && "Statement stack mismatch");
4520 Stmts.pop_back();
4521 }
4522 // Handle blocks rewriting.
4523 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4524 if (BDRE->isByRef())
Steve Naroff450d2fc2009-04-29 16:37:50 +00004525 return RewriteBlockDeclRefExpr(BDRE);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004526 }
4527 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroff85eb17b2008-10-30 10:07:53 +00004528 if (CE->getCallee()->getType()->isBlockPointerType()) {
4529 Stmt *BlockCall = SynthesizeBlockCall(CE);
4530 ReplaceStmt(S, BlockCall);
4531 return BlockCall;
4532 }
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004533 }
Steve Naroff7f1412d2008-11-03 23:29:32 +00004534 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004535 RewriteCastExpr(CE);
4536 }
4537#if 0
4538 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Ted Kremenek0c97e042009-02-07 01:47:29 +00004539 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004540 // Get the new text.
4541 std::string SStr;
4542 llvm::raw_string_ostream Buf(SStr);
Eli Friedman011a7362009-05-30 05:19:26 +00004543 Replacement->printPretty(Buf, *Context);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004544 const std::string &Str = Buf.str();
4545
4546 printf("CAST = %s\n", &Str[0]);
4547 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4548 delete S;
4549 return Replacement;
4550 }
4551#endif
4552 // Return this stmt unmodified.
4553 return S;
4554}
4555
4556/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4557/// main file of the input.
4558void RewriteObjC::HandleDeclInMainFile(Decl *D) {
4559 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffee8d4972008-12-17 00:20:22 +00004560 if (FD->isOverloadedOperator())
4561 return;
4562
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004563 // Since function prototypes don't have ParmDecl's, we check the function
4564 // prototype. This enables us to rewrite function declarations and
4565 // definitions using the same code.
Douglas Gregor4fa58902009-02-26 23:50:07 +00004566 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004567
Sebastian Redlbc9ef252009-04-26 20:35:05 +00004568 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argiris Kirtzidisccb9efe2009-06-30 02:35:26 +00004569 if (CompoundStmt *Body = FD->getCompoundBody()) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004570 CurFunctionDef = FD;
Steve Naroff0e948412008-12-04 16:24:46 +00004571 CollectPropertySetters(Body);
Steve Narofffbed6802008-12-08 16:43:47 +00004572 CurrentBody = Body;
Ted Kremenek30916072009-03-12 18:33:24 +00004573 Body =
4574 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4575 FD->setBody(Body);
Steve Narofffbed6802008-12-08 16:43:47 +00004576 CurrentBody = 0;
4577 if (PropParentMap) {
4578 delete PropParentMap;
4579 PropParentMap = 0;
4580 }
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004581 // This synthesizes and inserts the block "impl" struct, invoke function,
4582 // and any copy/dispose helper functions.
4583 InsertBlockLiteralsWithinFunction(FD);
4584 CurFunctionDef = 0;
4585 }
4586 return;
4587 }
4588 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argiris Kirtzidisccb9efe2009-06-30 02:35:26 +00004589 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004590 CurMethodDef = MD;
Steve Naroff0e948412008-12-04 16:24:46 +00004591 CollectPropertySetters(Body);
Steve Narofffbed6802008-12-08 16:43:47 +00004592 CurrentBody = Body;
Ted Kremenek30916072009-03-12 18:33:24 +00004593 Body =
4594 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4595 MD->setBody(Body);
Steve Narofffbed6802008-12-08 16:43:47 +00004596 CurrentBody = 0;
4597 if (PropParentMap) {
4598 delete PropParentMap;
4599 PropParentMap = 0;
4600 }
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004601 InsertBlockLiteralsWithinMethod(MD);
4602 CurMethodDef = 0;
4603 }
4604 }
4605 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
4606 ClassImplementation.push_back(CI);
4607 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
4608 CategoryImplementation.push_back(CI);
4609 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
4610 RewriteForwardClassDecl(CD);
4611 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4612 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroffd896f4b2008-12-11 21:05:33 +00004613 if (isTopLevelBlockPointerType(VD->getType()))
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004614 RewriteBlockPointerDecl(VD);
Steve Naroff80c54752008-10-29 18:15:37 +00004615 else if (VD->getType()->isFunctionPointerType()) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004616 CheckFunctionPointerDecl(VD->getType(), VD);
4617 if (VD->getInit()) {
Steve Naroff7f1412d2008-11-03 23:29:32 +00004618 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004619 RewriteCastExpr(CE);
4620 }
4621 }
4622 }
Steve Naroff80c54752008-10-29 18:15:37 +00004623 if (VD->getInit()) {
4624 GlobalVarDecl = VD;
Steve Naroff0e948412008-12-04 16:24:46 +00004625 CollectPropertySetters(VD->getInit());
Steve Narofffbed6802008-12-08 16:43:47 +00004626 CurrentBody = VD->getInit();
Steve Naroff80c54752008-10-29 18:15:37 +00004627 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Narofffbed6802008-12-08 16:43:47 +00004628 CurrentBody = 0;
4629 if (PropParentMap) {
4630 delete PropParentMap;
4631 PropParentMap = 0;
4632 }
Douglas Gregor24afd4a2008-11-17 14:58:09 +00004633 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattnerd120b9e2008-11-24 03:54:41 +00004634 VD->getNameAsCString());
Steve Naroff80c54752008-10-29 18:15:37 +00004635 GlobalVarDecl = 0;
4636
4637 // This is needed for blocks.
Steve Naroff7f1412d2008-11-03 23:29:32 +00004638 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff80c54752008-10-29 18:15:37 +00004639 RewriteCastExpr(CE);
4640 }
4641 }
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004642 return;
4643 }
4644 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroffd896f4b2008-12-11 21:05:33 +00004645 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004646 RewriteBlockPointerDecl(TD);
4647 else if (TD->getUnderlyingType()->isFunctionPointerType())
4648 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4649 return;
4650 }
4651 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
4652 if (RD->isDefinition()) {
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00004653 for (RecordDecl::field_iterator i = RD->field_begin(),
4654 e = RD->field_end(); i != e; ++i) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004655 FieldDecl *FD = *i;
Steve Naroffd896f4b2008-12-11 21:05:33 +00004656 if (isTopLevelBlockPointerType(FD->getType()))
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004657 RewriteBlockPointerDecl(FD);
4658 }
4659 }
4660 return;
4661 }
4662 // Nothing yet.
4663}
4664
Chris Lattner2a594d02009-03-28 04:11:33 +00004665void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004666 // Get the top-level buffer that this corresponds to.
4667
4668 // Rewrite tabs if we care.
4669 //RewriteTabs();
4670
4671 if (Diags.hasErrorOccurred())
4672 return;
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004673
4674 RewriteInclude();
4675
Steve Naroff450d2fc2009-04-29 16:37:50 +00004676 // Here's a great place to add any extra declarations that may be needed.
4677 // Write out meta data for each @protocol(<expr>).
4678 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
4679 E = ProtocolExprDecls.end(); I != E; ++I)
4680 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
4681
Chris Lattnerf4f776a2009-01-17 06:22:33 +00004682 InsertText(SM->getLocForStartOfFile(MainFileID),
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004683 Preamble.c_str(), Preamble.size(), false);
Steve Naroff901d8fd2008-11-14 14:10:01 +00004684 if (ClassImplementation.size() || CategoryImplementation.size())
4685 RewriteImplementations();
Steve Naroff450d2fc2009-04-29 16:37:50 +00004686
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004687 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
4688 // we are done.
4689 if (const RewriteBuffer *RewriteBuf =
4690 Rewrite.getRewriteBufferFor(MainFileID)) {
4691 //printf("Changed:\n");
4692 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4693 } else {
4694 fprintf(stderr, "No changes\n");
4695 }
Steve Naroff21658f62008-11-13 20:07:04 +00004696
Steve Naroff450d2fc2009-04-29 16:37:50 +00004697 if (ClassImplementation.size() || CategoryImplementation.size() ||
4698 ProtocolExprDecls.size()) {
Steve Naroff901d8fd2008-11-14 14:10:01 +00004699 // Rewrite Objective-c meta data*
4700 std::string ResultStr;
4701 SynthesizeMetaDataIntoBuffer(ResultStr);
4702 // Emit metadata.
4703 *OutFile << ResultStr;
4704 }
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004705 OutFile->flush();
4706}
4707