blob: f382704014f7eeecc4f59883624d834a2b997489 [file] [log] [blame]
Steve Naroffb29b4272008-04-14 22:03:09 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
Chris Lattner77cd2a02007-10-11 00:43:27 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner77cd2a02007-10-11 00:43:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
Eli Friedman39d7c4d2009-05-18 22:50:54 +000014#include "clang/Frontend/ASTConsumers.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Steve Naroff8599e7a2008-12-08 16:43:47 +000018#include "clang/AST/ParentMap.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000019#include "clang/Basic/SourceManager.h"
Steve Naroffebf2b562007-10-23 23:50:29 +000020#include "clang/Basic/IdentifierTable.h"
Chris Lattner07506182007-11-30 22:53:43 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattner26de4652007-12-02 01:13:47 +000022#include "clang/Lex/Lexer.h"
Chris Lattner158ecb92007-10-25 17:07:24 +000023#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000024#include "llvm/ADT/SmallPtrSet.h"
Ted Kremeneka95d3752008-09-13 05:16:45 +000025#include "llvm/ADT/OwningPtr.h"
Chris Lattner26de4652007-12-02 01:13:47 +000026#include "llvm/Support/MemoryBuffer.h"
Dan Gohman63e2dcc2008-05-21 20:19:16 +000027#include "llvm/Support/Streams.h"
Ted Kremeneka95d3752008-09-13 05:16:45 +000028#include "llvm/Support/raw_ostream.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000029using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000030using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000031
Chris Lattner77cd2a02007-10-11 00:43:27 +000032namespace {
Steve Naroffb29b4272008-04-14 22:03:09 +000033 class RewriteObjC : public ASTConsumer {
Chris Lattner2c64b7b2007-10-16 21:07:07 +000034 Rewriter Rewrite;
Chris Lattnere365c502007-11-30 22:25:36 +000035 Diagnostic &Diags;
Steve Naroff4f943c22008-03-10 20:43:59 +000036 const LangOptions &LangOpts;
Steve Narofff69cc5d2008-01-30 19:17:43 +000037 unsigned RewriteFailedDiag;
Steve Naroff8c565152008-12-05 17:03:39 +000038 unsigned TryFinallyContainsReturnDiag;
39
Chris Lattner01c57482007-10-17 22:35:30 +000040 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000041 SourceManager *SM;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000042 TranslationUnitDecl *TUDecl;
Chris Lattner2b2453a2009-01-17 06:22:33 +000043 FileID MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000044 const char *MainFileStart, *MainFileEnd;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000045 SourceLocation LastIncLoc;
Steve Naroffba92b2e2008-03-27 22:29:16 +000046
Ted Kremeneka526c5c2008-01-07 19:49:32 +000047 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
48 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
49 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Narofffbfe8252008-05-06 18:26:51 +000050 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000051 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
52 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000053 llvm::SmallVector<Stmt *, 32> Stmts;
54 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroff621edce2009-04-29 16:37:50 +000055 // Remember all the @protocol(<expr>) expressions.
56 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Steve Naroffebf2b562007-10-23 23:50:29 +000057
Steve Naroffd82a9ab2008-03-15 00:55:56 +000058 unsigned NumObjCStringLiterals;
59
Steve Naroffebf2b562007-10-23 23:50:29 +000060 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000061 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000062 FunctionDecl *MsgSendStretFunctionDecl;
63 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000064 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000065 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000066 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000067 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000068 FunctionDecl *CFStringFunctionDecl;
Steve Naroffc0a123c2008-03-11 17:37:02 +000069 FunctionDecl *SuperContructorFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000070
Steve Naroffbeaf2992007-11-03 11:27:19 +000071 // ObjC string constant support.
Steve Naroff248a7532008-04-15 22:42:06 +000072 VarDecl *ConstantStringClassReference;
Steve Naroffbeaf2992007-11-03 11:27:19 +000073 RecordDecl *NSStringRecord;
Steve Naroffab972d32007-11-04 22:37:50 +000074
Fariborz Jahanianb586cce2008-01-16 00:09:11 +000075 // ObjC foreach break/continue generation support.
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000076 int BcLabelCount;
77
Steve Naroff874e2322007-11-15 10:28:18 +000078 // Needed for super.
Steve Naroff54055232008-10-27 17:20:55 +000079 ObjCMethodDecl *CurMethodDef;
Steve Naroff874e2322007-11-15 10:28:18 +000080 RecordDecl *SuperStructDecl;
Steve Naroffd82a9ab2008-03-15 00:55:56 +000081 RecordDecl *ConstantStringDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000082
Steve Naroff621edce2009-04-29 16:37:50 +000083 TypeDecl *ProtocolTypeDecl;
84 QualType getProtocolType();
85
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +000086 // Needed for header files being rewritten
87 bool IsHeader;
88
Steve Naroffa7b402d2008-03-28 22:26:09 +000089 std::string InFileName;
Eli Friedman66d6f042009-05-18 22:20:00 +000090 llvm::raw_ostream* OutFile;
Eli Friedmanc6d656e2009-05-18 22:39:16 +000091
92 bool SilenceRewriteMacroWarning;
93
Steve Naroffba92b2e2008-03-27 22:29:16 +000094 std::string Preamble;
Steve Naroff54055232008-10-27 17:20:55 +000095
96 // Block expressions.
97 llvm::SmallVector<BlockExpr *, 32> Blocks;
98 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
99 llvm::DenseMap<BlockDeclRefExpr *, CallExpr *> BlockCallExprs;
Steve Naroffba92b2e2008-03-27 22:29:16 +0000100
Steve Naroff54055232008-10-27 17:20:55 +0000101 // Block related declarations.
102 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDecls;
103 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDecls;
104 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
105
106 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
107
Steve Naroffc77a6362008-12-04 16:24:46 +0000108 // This maps a property to it's assignment statement.
109 llvm::DenseMap<ObjCPropertyRefExpr *, BinaryOperator *> PropSetters;
Steve Naroff8599e7a2008-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 Naroff4c3580e2008-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 Naroff15f081d2008-12-03 00:56:33 +0000118
Steve Naroff54055232008-10-27 17:20:55 +0000119 FunctionDecl *CurFunctionDef;
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000120 VarDecl *GlobalVarDecl;
121
Steve Naroffb619d952008-12-09 12:56:34 +0000122 bool DisableReplaceStmt;
123
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000124 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +0000125 public:
Ted Kremeneke3a61982008-05-31 20:11:04 +0000126 virtual void Initialize(ASTContext &context);
127
Chris Lattnerf04da132007-10-24 17:06:59 +0000128 // Top Level Driver code.
Chris Lattner682bf922009-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 Lattner2c64b7b2007-10-16 21:07:07 +0000134 void HandleDeclInMainFile(Decl *D);
Eli Friedman66d6f042009-05-18 22:20:00 +0000135 RewriteObjC(std::string inFile, llvm::raw_ostream *OS,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000136 Diagnostic &D, const LangOptions &LOpts,
137 bool silenceMacroWarn);
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000138
139 ~RewriteObjC() {}
140
Chris Lattnerdacbc5d2009-03-28 04:11:33 +0000141 virtual void HandleTranslationUnit(ASTContext &C);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000142
143 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff4c3580e2008-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 Lattnerdcbc5b02008-01-31 19:37:57 +0000148
Steve Naroffb619d952008-12-09 12:56:34 +0000149 if (DisableReplaceStmt)
150 return; // Used when rewriting the assignment of a property setter.
151
Steve Naroff4c3580e2008-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 Lattner0a14eee2008-11-18 07:04:44 +0000159 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
160 << Old->getSourceRange();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000161 }
Steve Naroffb619d952008-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);
Eli Friedman3a9eb442009-05-30 05:19:26 +0000174 New->printPretty(S, *Context);
Steve Naroffb619d952008-12-09 12:56:34 +0000175 const std::string &Str = S.str();
176
177 // If replacement succeeded or warning disabled return with no warning.
178 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, &Str[0], Str.size())) {
179 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 Naroffba92b2e2008-03-27 22:29:16 +0000188 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
189 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000190 // If insertion succeeded or warning disabled return with no warning.
Steve Naroffba92b2e2008-03-27 22:29:16 +0000191 if (!Rewrite.InsertText(Loc, StrData, StrLen, InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000192 SilenceRewriteMacroWarning)
193 return;
194
195 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
196 }
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000197
Chris Lattneraadaf782008-01-31 19:51:04 +0000198 void RemoveText(SourceLocation Loc, unsigned StrLen) {
199 // If removal succeeded or warning disabled return with no warning.
200 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
201 return;
202
203 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
204 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000205
Chris Lattneraadaf782008-01-31 19:51:04 +0000206 void ReplaceText(SourceLocation Start, unsigned OrigLength,
207 const char *NewStr, unsigned NewLength) {
208 // If removal succeeded or warning disabled return with no warning.
209 if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength) ||
210 SilenceRewriteMacroWarning)
211 return;
212
213 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
214 }
215
Chris Lattnerf04da132007-10-24 17:06:59 +0000216 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000217 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000218 void RewriteInclude();
Chris Lattnerf04da132007-10-24 17:06:59 +0000219 void RewriteTabs();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000220 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffa0876e82008-12-02 17:36:43 +0000221 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
222 ObjCImplementationDecl *IMD,
223 ObjCCategoryImplDecl *CID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000224 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000225 void RewriteImplementationDecl(Decl *Dcl);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000226 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
227 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
228 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
229 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
230 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff6327e0d2009-01-11 01:06:09 +0000231 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff09b266e2007-10-30 23:14:51 +0000232 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000233 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroff4f95b752008-07-29 18:15:38 +0000234 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffd5255f52007-11-01 13:24:47 +0000235 bool needToScanForQualifiers(QualType T);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000236 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000237 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000238 QualType getConstantStringStructType();
Steve Naroffbaf58c32008-05-31 14:15:04 +0000239 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Chris Lattner311ff022007-10-16 22:36:42 +0000240
Chris Lattnerf04da132007-10-24 17:06:59 +0000241 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000242 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroffc77a6362008-12-04 16:24:46 +0000243 void CollectPropertySetters(Stmt *S);
244
Steve Naroff8599e7a2008-12-08 16:43:47 +0000245 Stmt *CurrentBody;
246 ParentMap *PropParentMap; // created lazily.
247
Chris Lattnere64b7772007-10-24 16:57:36 +0000248 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000249 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart);
Steve Naroffc77a6362008-12-04 16:24:46 +0000250 Stmt *RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr);
Steve Naroffb619d952008-12-09 12:56:34 +0000251 Stmt *RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
252 SourceRange SrcRange);
Steve Naroffb42f8412007-11-05 14:50:49 +0000253 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000254 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000255 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000256 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroff8c565152008-12-05 17:03:39 +0000257 void WarnAboutReturnGotoContinueOrBreakStmts(Stmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000258 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000259 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000260 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
261 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
262 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000263 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
264 SourceLocation OrigEnd);
Steve Naroff934f2762007-10-24 22:48:43 +0000265 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
266 Expr **args, unsigned nargs);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000267 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000268 Stmt *RewriteBreakStmt(BreakStmt *S);
269 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000270 void SynthCountByEnumWithState(std::string &buf);
271
Steve Naroff09b266e2007-10-30 23:14:51 +0000272 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000273 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000274 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000275 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000276 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000277 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000278 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000279 void SynthSelGetUidFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000280 void SynthSuperContructorFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000281
Chris Lattnerf04da132007-10-24 17:06:59 +0000282 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000283 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000284 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000285
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000286 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000287 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000288
Douglas Gregor653f1b12009-04-23 01:02:12 +0000289 template<typename MethodIterator>
290 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
291 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000292 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000293 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000294 const char *ClassName,
295 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000296
Steve Naroff621edce2009-04-29 16:37:50 +0000297 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
298 const char *prefix,
299 const char *ClassName,
300 std::string &Result);
301 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
302 const char *prefix,
303 const char *ClassName,
304 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000305 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000306 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000307 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
308 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000309 std::string &Result);
Steve Narofface66252008-11-13 20:07:04 +0000310 void RewriteImplementations();
311 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Steve Naroff54055232008-10-27 17:20:55 +0000312
313 // Block rewriting.
Douglas Gregor72564e72009-02-26 23:50:07 +0000314 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff54055232008-10-27 17:20:55 +0000315 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
316
317 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
318 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
319
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000320 // Block specific rewrite rules.
Steve Naroff54055232008-10-27 17:20:55 +0000321 void RewriteBlockCall(CallExpr *Exp);
322 void RewriteBlockPointerDecl(NamedDecl *VD);
Steve Naroff621edce2009-04-29 16:37:50 +0000323 Stmt *RewriteBlockDeclRefExpr(BlockDeclRefExpr *VD);
Steve Naroff54055232008-10-27 17:20:55 +0000324 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
325
326 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
327 const char *funcName, std::string Tag);
328 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
329 const char *funcName, std::string Tag);
330 std::string SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
331 bool hasCopyDisposeHelpers);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +0000332 Stmt *SynthesizeBlockCall(CallExpr *Exp);
Steve Naroff54055232008-10-27 17:20:55 +0000333 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
334 const char *FunName);
335
336 void CollectBlockDeclRefInfo(BlockExpr *Exp);
337 void GetBlockCallExprs(Stmt *S);
338 void GetBlockDeclRefExprs(Stmt *S);
339
340 // We avoid calling Type::isBlockPointerType(), since it operates on the
341 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000342 bool isTopLevelBlockPointerType(QualType T) {
343 return isa<BlockPointerType>(T);
344 }
Steve Naroff54055232008-10-27 17:20:55 +0000345
346 // FIXME: This predicate seems like it would be useful to add to ASTContext.
347 bool isObjCType(QualType T) {
348 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
349 return false;
350
351 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
352
353 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
354 OCT == Context->getCanonicalType(Context->getObjCClassType()))
355 return true;
356
357 if (const PointerType *PT = OCT->getAsPointerType()) {
358 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
359 isa<ObjCQualifiedIdType>(PT->getPointeeType()))
360 return true;
361 }
362 return false;
363 }
364 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Ted Kremenek8189cde2009-02-07 01:47:29 +0000365 void GetExtentOfArgList(const char *Name, const char *&LParen,
366 const char *&RParen);
Steve Naroffb2f9e512008-11-03 23:29:32 +0000367 void RewriteCastExpr(CStyleCastExpr *CE);
Steve Narofffa15fd92008-10-28 20:29:00 +0000368
369 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000370 Stmt *SynthBlockInitExpr(BlockExpr *Exp);
Steve Naroff621edce2009-04-29 16:37:50 +0000371
372 void QuoteDoublequotes(std::string &From, std::string &To) {
373 for(unsigned i = 0; i < From.length(); i++) {
374 if (From[i] == '"')
375 To += "\\\"";
376 else
377 To += From[i];
378 }
379 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000380 };
381}
382
Douglas Gregor72564e72009-02-26 23:50:07 +0000383void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
Steve Naroff54055232008-10-27 17:20:55 +0000384 NamedDecl *D) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000385 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
386 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +0000387 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000388 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff54055232008-10-27 17:20:55 +0000389 // All the args are checked/rewritten. Don't call twice!
390 RewriteBlockPointerDecl(D);
391 break;
392 }
393 }
394}
395
396void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
397 const PointerType *PT = funcType->getAsPointerType();
398 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor72564e72009-02-26 23:50:07 +0000399 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff54055232008-10-27 17:20:55 +0000400}
401
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000402static bool IsHeaderFile(const std::string &Filename) {
403 std::string::size_type DotPos = Filename.rfind('.');
404
405 if (DotPos == std::string::npos) {
406 // no file extension
407 return false;
408 }
409
410 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
411 // C header: .h
412 // C++ header: .hh or .H;
413 return Ext == "h" || Ext == "hh" || Ext == "H";
414}
415
Eli Friedman66d6f042009-05-18 22:20:00 +0000416RewriteObjC::RewriteObjC(std::string inFile, llvm::raw_ostream* OS,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000417 Diagnostic &D, const LangOptions &LOpts,
418 bool silenceMacroWarn)
419 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
420 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Naroffa7b402d2008-03-28 22:26:09 +0000421 IsHeader = IsHeaderFile(inFile);
Steve Naroffa7b402d2008-03-28 22:26:09 +0000422 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
423 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff8c565152008-12-05 17:03:39 +0000424 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000425 "rewriter doesn't support user-specified control flow semantics "
426 "for @try/@finally (code may not execute properly)");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000427}
428
Eli Friedmanbce831b2009-05-18 22:29:17 +0000429ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
430 llvm::raw_ostream* OS,
431 Diagnostic &Diags,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000432 const LangOptions &LOpts,
433 bool SilenceRewriteMacroWarning) {
434 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere365c502007-11-30 22:25:36 +0000435}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000436
Steve Naroffb29b4272008-04-14 22:03:09 +0000437void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000438 Context = &context;
439 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000440 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000441 MsgSendFunctionDecl = 0;
442 MsgSendSuperFunctionDecl = 0;
443 MsgSendStretFunctionDecl = 0;
444 MsgSendSuperStretFunctionDecl = 0;
445 MsgSendFpretFunctionDecl = 0;
446 GetClassFunctionDecl = 0;
447 GetMetaClassFunctionDecl = 0;
448 SelGetUidFunctionDecl = 0;
449 CFStringFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000450 ConstantStringClassReference = 0;
451 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000452 CurMethodDef = 0;
453 CurFunctionDef = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000454 GlobalVarDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000455 SuperStructDecl = 0;
Steve Naroff621edce2009-04-29 16:37:50 +0000456 ProtocolTypeDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000457 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000458 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000459 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000460 NumObjCStringLiterals = 0;
Steve Naroff68272b82008-12-08 20:01:41 +0000461 PropParentMap = 0;
462 CurrentBody = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000463 DisableReplaceStmt = false;
464
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000465 // Get the ID and start/end of the main file.
466 MainFileID = SM->getMainFileID();
467 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
468 MainFileStart = MainBuf->getBufferStart();
469 MainFileEnd = MainBuf->getBufferEnd();
Steve Naroffba92b2e2008-03-27 22:29:16 +0000470
Chris Lattner2c78b872009-04-14 23:22:57 +0000471 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000472
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000473 // declaring objc_selector outside the parameter list removes a silly
474 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000475 if (IsHeader)
Steve Naroff62c26322009-02-03 20:39:18 +0000476 Preamble = "#pragma once\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000477 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff46a98a72008-12-23 20:11:22 +0000478 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000479 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000480 if (LangOpts.Microsoft) {
481 // Add a constructor for creating temporary objects.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000482 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
483 ": ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000484 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000485 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000486 Preamble += "};\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000487 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
488 Preamble += "typedef struct objc_object Protocol;\n";
489 Preamble += "#define _REWRITER_typedef_Protocol\n";
490 Preamble += "#endif\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000491 if (LangOpts.Microsoft) {
492 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
493 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
494 } else
495 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
496 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000497 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000498 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000499 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000500 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000501 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000502 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000503 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000504 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000505 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000506 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000507 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000508 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000509 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000510 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
511 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
512 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
513 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
514 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000515 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000516 // @synchronized hooks.
Steve Naroff4ebd7162008-12-08 17:30:33 +0000517 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
518 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
519 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000520 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
521 Preamble += "struct __objcFastEnumerationState {\n\t";
522 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000523 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000524 Preamble += "unsigned long *mutationsPtr;\n\t";
525 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000526 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000527 Preamble += "#define __FASTENUMERATIONSTATE\n";
528 Preamble += "#endif\n";
529 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
530 Preamble += "struct __NSConstantStringImpl {\n";
531 Preamble += " int *isa;\n";
532 Preamble += " int flags;\n";
533 Preamble += " char *str;\n";
534 Preamble += " long length;\n";
535 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000536 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
537 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
538 Preamble += "#else\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000539 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000540 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000541 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
542 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000543 // Blocks preamble.
544 Preamble += "#ifndef BLOCK_IMPL\n";
545 Preamble += "#define BLOCK_IMPL\n";
546 Preamble += "struct __block_impl {\n";
547 Preamble += " void *isa;\n";
548 Preamble += " int Flags;\n";
549 Preamble += " int Size;\n";
550 Preamble += " void *FuncPtr;\n";
551 Preamble += "};\n";
Steve Naroff5bc60d02008-12-16 15:50:30 +0000552 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
553 Preamble += "__OBJC_RW_STATICIMPORT void _Block_object_assign(void *, const void *, const int);\n";
554 Preamble += "__OBJC_RW_STATICIMPORT void _Block_object_dispose(const void *, const int);\n";
555 Preamble += "__OBJC_RW_STATICIMPORT void *_NSConcreteGlobalBlock[32];\n";
556 Preamble += "__OBJC_RW_STATICIMPORT void *_NSConcreteStackBlock[32];\n";
Steve Naroff54055232008-10-27 17:20:55 +0000557 Preamble += "#endif\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000558 if (LangOpts.Microsoft) {
Steve Naroff4ebd7162008-12-08 17:30:33 +0000559 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
560 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000561 Preamble += "#define __attribute__(X)\n";
562 }
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000563}
564
565
Chris Lattnerf04da132007-10-24 17:06:59 +0000566//===----------------------------------------------------------------------===//
567// Top Level Driver Code
568//===----------------------------------------------------------------------===//
569
Chris Lattner682bf922009-03-29 16:50:03 +0000570void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000571 // Two cases: either the decl could be in the main file, or it could be in a
572 // #included file. If the former, rewrite it now. If the later, check to see
573 // if we rewrote the #include/#import.
574 SourceLocation Loc = D->getLocation();
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000575 Loc = SM->getInstantiationLoc(Loc);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000576
577 // If this is for a builtin, ignore it.
578 if (Loc.isInvalid()) return;
579
Steve Naroffebf2b562007-10-23 23:50:29 +0000580 // Look for built-in declarations that we need to refer during the rewrite.
581 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000582 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000583 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000584 // declared in <Foundation/NSString.h>
Chris Lattner8ec03f52008-11-24 03:54:41 +0000585 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000586 ConstantStringClassReference = FVD;
587 return;
588 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000589 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000590 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000591 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000592 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000593 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000594 RewriteProtocolDecl(PD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000595 } else if (ObjCForwardProtocolDecl *FP =
596 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000597 RewriteForwardProtocolDecl(FP);
Douglas Gregord0434102009-01-09 00:49:46 +0000598 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
599 // Recurse into linkage specifications
Douglas Gregor6ab35242009-04-09 21:40:53 +0000600 for (DeclContext::decl_iterator DI = LSD->decls_begin(*Context),
601 DIEnd = LSD->decls_end(*Context);
Douglas Gregord0434102009-01-09 00:49:46 +0000602 DI != DIEnd; ++DI)
Chris Lattner682bf922009-03-29 16:50:03 +0000603 HandleTopLevelSingleDecl(*DI);
Steve Naroffebf2b562007-10-23 23:50:29 +0000604 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000605 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000606 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000607 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000608}
609
Chris Lattnerf04da132007-10-24 17:06:59 +0000610//===----------------------------------------------------------------------===//
611// Syntactic (non-AST) Rewriting Code
612//===----------------------------------------------------------------------===//
613
Steve Naroffb29b4272008-04-14 22:03:09 +0000614void RewriteObjC::RewriteInclude() {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000615 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000616 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
617 const char *MainBufStart = MainBuf.first;
618 const char *MainBufEnd = MainBuf.second;
619 size_t ImportLen = strlen("import");
620 size_t IncludeLen = strlen("include");
621
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000622 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000623 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
624 if (*BufPtr == '#') {
625 if (++BufPtr == MainBufEnd)
626 return;
627 while (*BufPtr == ' ' || *BufPtr == '\t')
628 if (++BufPtr == MainBufEnd)
629 return;
630 if (!strncmp(BufPtr, "import", ImportLen)) {
631 // replace import with include
632 SourceLocation ImportLoc =
633 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattneraadaf782008-01-31 19:51:04 +0000634 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000635 BufPtr += ImportLen;
636 }
637 }
638 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000639}
640
Steve Naroffb29b4272008-04-14 22:03:09 +0000641void RewriteObjC::RewriteTabs() {
Chris Lattnerf04da132007-10-24 17:06:59 +0000642 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
643 const char *MainBufStart = MainBuf.first;
644 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000645
Chris Lattnerf04da132007-10-24 17:06:59 +0000646 // Loop over the whole file, looking for tabs.
647 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
648 if (*BufPtr != '\t')
649 continue;
650
651 // Okay, we found a tab. This tab will turn into at least one character,
652 // but it depends on which 'virtual column' it is in. Compute that now.
653 unsigned VCol = 0;
654 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
655 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
656 ++VCol;
657
658 // Okay, now that we know the virtual column, we know how many spaces to
659 // insert. We assume 8-character tab-stops.
660 unsigned Spaces = 8-(VCol & 7);
661
662 // Get the location of the tab.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000663 SourceLocation TabLoc = SM->getLocForStartOfFile(MainFileID);
664 TabLoc = TabLoc.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattnerf04da132007-10-24 17:06:59 +0000665
666 // Rewrite the single tab character into a sequence of spaces.
Chris Lattneraadaf782008-01-31 19:51:04 +0000667 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerf04da132007-10-24 17:06:59 +0000668 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000669}
670
Steve Naroffeb0646c2008-12-02 15:48:25 +0000671static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
672 ObjCIvarDecl *OID) {
673 std::string S;
674 S = "((struct ";
675 S += ClassDecl->getIdentifier()->getName();
676 S += "_IMPL *)self)->";
677 S += OID->getNameAsCString();
678 return S;
679}
680
Steve Naroffa0876e82008-12-02 17:36:43 +0000681void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
682 ObjCImplementationDecl *IMD,
683 ObjCCategoryImplDecl *CID) {
Steve Naroffd40910b2008-12-01 20:33:01 +0000684 SourceLocation startLoc = PID->getLocStart();
685 InsertText(startLoc, "// ", 3);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000686 const char *startBuf = SM->getCharacterData(startLoc);
687 assert((*startBuf == '@') && "bogus @synthesize location");
688 const char *semiBuf = strchr(startBuf, ';');
689 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek8189cde2009-02-07 01:47:29 +0000690 SourceLocation onePastSemiLoc =
691 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000692
693 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
694 return; // FIXME: is this correct?
695
696 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000697 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000698 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000699 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000700
701 if (!OID)
702 return;
703
704 std::string Getr;
705 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
706 Getr += "{ ";
707 // Synthesize an explicit cast to gain access to the ivar.
Steve Naroff3539cdb2008-12-02 17:54:50 +0000708 // FIXME: deal with code generation implications for various property
709 // attributes (copy, retain, nonatomic).
710 // See objc-act.c:objc_synthesize_new_getter() for details.
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000711 Getr += "return " + getIvarAccessString(ClassDecl, OID);
712 Getr += "; }";
Steve Naroffeb0646c2008-12-02 15:48:25 +0000713 InsertText(onePastSemiLoc, Getr.c_str(), Getr.size());
Steve Naroffeb0646c2008-12-02 15:48:25 +0000714 if (PD->isReadOnly())
715 return;
716
717 // Generate the 'setter' function.
718 std::string Setr;
719 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000720 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000721 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff3539cdb2008-12-02 17:54:50 +0000722 // FIXME: deal with code generation implications for various property
723 // attributes (copy, retain, nonatomic).
Steve Naroff15f081d2008-12-03 00:56:33 +0000724 // See objc-act.c:objc_synthesize_new_setter() for details.
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000725 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
Steve Narofff4312dc2008-12-11 19:29:16 +0000726 Setr += PD->getNameAsCString();
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000727 Setr += "; }";
Steve Naroffeb0646c2008-12-02 15:48:25 +0000728 InsertText(onePastSemiLoc, Setr.c_str(), Setr.size());
Steve Naroffd40910b2008-12-01 20:33:01 +0000729}
Chris Lattner8a12c272007-10-11 18:38:32 +0000730
Steve Naroffb29b4272008-04-14 22:03:09 +0000731void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000732 // Get the start location and compute the semi location.
733 SourceLocation startLoc = ClassDecl->getLocation();
734 const char *startBuf = SM->getCharacterData(startLoc);
735 const char *semiPtr = strchr(startBuf, ';');
736
737 // Translate to typedef's that forward reference structs with the same name
738 // as the class. As a convenience, we include the original declaration
739 // as a comment.
740 std::string typedefString;
741 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000742 typedefString.append(startBuf, semiPtr-startBuf+1);
743 typedefString += "\n";
Chris Lattner67956052009-02-20 18:04:31 +0000744 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
745 I != E; ++I) {
746 ObjCInterfaceDecl *ForwardDecl = *I;
Steve Naroff32174822007-11-09 12:50:28 +0000747 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000748 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000749 typedefString += "\n";
750 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000751 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000752 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000753 typedefString += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000754 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000755 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000756 }
757
758 // Replace the @class with typedefs corresponding to the classes.
Chris Lattneraadaf782008-01-31 19:51:04 +0000759 ReplaceText(startLoc, semiPtr-startBuf+1,
760 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000761}
762
Steve Naroffb29b4272008-04-14 22:03:09 +0000763void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000764 SourceLocation LocStart = Method->getLocStart();
765 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000766
Chris Lattner30fc9332009-02-04 01:06:56 +0000767 if (SM->getInstantiationLineNumber(LocEnd) >
768 SM->getInstantiationLineNumber(LocStart)) {
Steve Naroff94ac21e2008-10-21 13:37:27 +0000769 InsertText(LocStart, "#if 0\n", 6);
770 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000771 } else {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000772 InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000773 }
774}
775
Steve Naroff6327e0d2009-01-11 01:06:09 +0000776void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop)
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000777{
Steve Naroff6327e0d2009-01-11 01:06:09 +0000778 SourceLocation Loc = prop->getLocation();
779
780 ReplaceText(Loc, 0, "// ", 3);
781
782 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000783}
784
Steve Naroffb29b4272008-04-14 22:03:09 +0000785void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000786 SourceLocation LocStart = CatDecl->getLocStart();
787
788 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000789 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000790
Douglas Gregor6ab35242009-04-09 21:40:53 +0000791 for (ObjCCategoryDecl::instmeth_iterator
792 I = CatDecl->instmeth_begin(*Context),
793 E = CatDecl->instmeth_end(*Context);
794 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000795 RewriteMethodDeclaration(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000796 for (ObjCCategoryDecl::classmeth_iterator
797 I = CatDecl->classmeth_begin(*Context),
798 E = CatDecl->classmeth_end(*Context);
799 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000800 RewriteMethodDeclaration(*I);
801
Steve Naroff423cb562007-10-30 13:30:57 +0000802 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000803 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000804}
805
Steve Naroffb29b4272008-04-14 22:03:09 +0000806void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000807 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000808
Steve Naroff752d6ef2007-10-30 16:42:30 +0000809 SourceLocation LocStart = PDecl->getLocStart();
810
811 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000812 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000813
Douglas Gregor6ab35242009-04-09 21:40:53 +0000814 for (ObjCProtocolDecl::instmeth_iterator
815 I = PDecl->instmeth_begin(*Context),
816 E = PDecl->instmeth_end(*Context);
817 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000818 RewriteMethodDeclaration(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000819 for (ObjCProtocolDecl::classmeth_iterator
820 I = PDecl->classmeth_begin(*Context),
821 E = PDecl->classmeth_end(*Context);
822 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000823 RewriteMethodDeclaration(*I);
824
Steve Naroff752d6ef2007-10-30 16:42:30 +0000825 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000826 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattneraadaf782008-01-31 19:51:04 +0000827 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000828
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000829 // Must comment out @optional/@required
830 const char *startBuf = SM->getCharacterData(LocStart);
831 const char *endBuf = SM->getCharacterData(LocEnd);
832 for (const char *p = startBuf; p < endBuf; p++) {
833 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
834 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000835 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000836 ReplaceText(OptionalLoc, strlen("@optional"),
837 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000838
839 }
840 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
841 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000842 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000843 ReplaceText(OptionalLoc, strlen("@required"),
844 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000845
846 }
847 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000848}
849
Steve Naroffb29b4272008-04-14 22:03:09 +0000850void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000851 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000852 if (LocStart.isInvalid())
853 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000854 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000855 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000856}
857
Steve Naroffb29b4272008-04-14 22:03:09 +0000858void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000859 std::string &ResultStr) {
Steve Naroffced80a82008-10-30 12:09:33 +0000860 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroff76e429d2008-07-16 14:40:40 +0000861 const FunctionType *FPRetType = 0;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000862 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000863 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000864 ResultStr += "id";
Steve Narofff4312dc2008-12-11 19:29:16 +0000865 else if (OMD->getResultType()->isFunctionPointerType() ||
866 OMD->getResultType()->isBlockPointerType()) {
Steve Naroff76e429d2008-07-16 14:40:40 +0000867 // needs special handling, since pointer-to-functions have special
868 // syntax (where a decaration models use).
869 QualType retType = OMD->getResultType();
Steve Narofff4312dc2008-12-11 19:29:16 +0000870 QualType PointeeTy;
871 if (const PointerType* PT = retType->getAsPointerType())
872 PointeeTy = PT->getPointeeType();
873 else if (const BlockPointerType *BPT = retType->getAsBlockPointerType())
874 PointeeTy = BPT->getPointeeType();
875 if ((FPRetType = PointeeTy->getAsFunctionType())) {
876 ResultStr += FPRetType->getResultType().getAsString();
877 ResultStr += "(*";
Steve Naroff76e429d2008-07-16 14:40:40 +0000878 }
879 } else
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000880 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000881 ResultStr += " ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000882
883 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000884 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000885
Douglas Gregorf8d49f62009-01-09 17:18:27 +0000886 if (OMD->isInstanceMethod())
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000887 NameStr += "_I_";
888 else
889 NameStr += "_C_";
890
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000891 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000892 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000893
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000894 if (ObjCCategoryImplDecl *CID =
Steve Naroff3e0a5402009-01-08 19:41:02 +0000895 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000896 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000897 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000898 }
Steve Naroff563b8282008-04-04 22:23:44 +0000899 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +0000900 {
901 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000902 int len = selString.size();
903 for (int i = 0; i < len; i++)
904 if (selString[i] == ':')
905 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000906 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000907 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000908 // Remember this name for metadata emission
909 MethodInternalNames[OMD] = NameStr;
910 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000911
912 // Rewrite arguments
913 ResultStr += "(";
914
915 // invisible arguments
Douglas Gregorf8d49f62009-01-09 17:18:27 +0000916 if (OMD->isInstanceMethod()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000917 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000918 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +0000919 if (!LangOpts.Microsoft) {
920 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
921 ResultStr += "struct ";
922 }
923 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000924 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000925 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000926 }
927 else
Steve Naroff621edce2009-04-29 16:37:50 +0000928 ResultStr += Context->getObjCClassType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000929
930 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000931 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000932 ResultStr += " _cmd";
933
934 // Method arguments.
Chris Lattner89951a82009-02-20 18:43:26 +0000935 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
936 E = OMD->param_end(); PI != E; ++PI) {
937 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000938 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +0000939 if (PDecl->getType()->isObjCQualifiedIdType()) {
940 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000941 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +0000942 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000943 std::string Name = PDecl->getNameAsString();
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000944 if (isTopLevelBlockPointerType(PDecl->getType())) {
Steve Naroffc8ad87b2008-10-30 14:45:29 +0000945 // Make sure we convert "t (^)(...)" to "t (*)(...)".
946 const BlockPointerType *BPT = PDecl->getType()->getAsBlockPointerType();
Douglas Gregord249e1d1f2009-05-29 20:38:28 +0000947 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name,
948 Context->PrintingPolicy);
Steve Naroffc8ad87b2008-10-30 14:45:29 +0000949 } else
Douglas Gregord249e1d1f2009-05-29 20:38:28 +0000950 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroff543409e2008-04-18 21:13:19 +0000951 ResultStr += Name;
952 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000953 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +0000954 if (OMD->isVariadic())
955 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000956 ResultStr += ") ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000957
Steve Naroff76e429d2008-07-16 14:40:40 +0000958 if (FPRetType) {
959 ResultStr += ")"; // close the precedence "scope" for "*".
960
961 // Now, emit the argument types (if any).
Douglas Gregor72564e72009-02-26 23:50:07 +0000962 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff76e429d2008-07-16 14:40:40 +0000963 ResultStr += "(";
964 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
965 if (i) ResultStr += ", ";
966 std::string ParamStr = FT->getArgType(i).getAsString();
967 ResultStr += ParamStr;
968 }
969 if (FT->isVariadic()) {
970 if (FT->getNumArgs()) ResultStr += ", ";
971 ResultStr += "...";
972 }
973 ResultStr += ")";
974 } else {
975 ResultStr += "()";
976 }
977 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000978}
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000979void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000980 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
981 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000982
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000983 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000984 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000985 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000986 InsertText(CID->getLocStart(), "// ", 3);
Steve Narofface66252008-11-13 20:07:04 +0000987
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000988 for (ObjCCategoryImplDecl::instmeth_iterator
Douglas Gregor653f1b12009-04-23 01:02:12 +0000989 I = IMD ? IMD->instmeth_begin(*Context) : CID->instmeth_begin(*Context),
990 E = IMD ? IMD->instmeth_end(*Context) : CID->instmeth_end(*Context);
991 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000992 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000993 ObjCMethodDecl *OMD = *I;
994 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000995 SourceLocation LocStart = OMD->getLocStart();
Sebastian Redld3a413d2009-04-26 20:35:05 +0000996 SourceLocation LocEnd = OMD->getCompoundBody(*Context)->getLocStart();
997
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000998 const char *startBuf = SM->getCharacterData(LocStart);
999 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +00001000 ReplaceText(LocStart, endBuf-startBuf,
1001 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001002 }
1003
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001004 for (ObjCCategoryImplDecl::classmeth_iterator
Douglas Gregor653f1b12009-04-23 01:02:12 +00001005 I = IMD ? IMD->classmeth_begin(*Context) : CID->classmeth_begin(*Context),
1006 E = IMD ? IMD->classmeth_end(*Context) : CID->classmeth_end(*Context);
1007 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001008 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001009 ObjCMethodDecl *OMD = *I;
1010 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001011 SourceLocation LocStart = OMD->getLocStart();
Sebastian Redld3a413d2009-04-26 20:35:05 +00001012 SourceLocation LocEnd = OMD->getCompoundBody(*Context)->getLocStart();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001013
1014 const char *startBuf = SM->getCharacterData(LocStart);
1015 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +00001016 ReplaceText(LocStart, endBuf-startBuf,
1017 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001018 }
Steve Naroffd40910b2008-12-01 20:33:01 +00001019 for (ObjCCategoryImplDecl::propimpl_iterator
Douglas Gregor653f1b12009-04-23 01:02:12 +00001020 I = IMD ? IMD->propimpl_begin(*Context) : CID->propimpl_begin(*Context),
1021 E = IMD ? IMD->propimpl_end(*Context) : CID->propimpl_end(*Context);
1022 I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +00001023 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001024 }
1025
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001026 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001027 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001028 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001029 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001030}
1031
Steve Naroffb29b4272008-04-14 22:03:09 +00001032void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001033 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001034 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001035 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001036 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001037 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001038 ResultStr += "\n";
1039 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001040 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001041 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001042 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001043 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001044 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001045 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001046 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001047 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001048 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Narofff908a872007-10-30 02:23:23 +00001049
Douglas Gregor6ab35242009-04-09 21:40:53 +00001050 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(*Context),
1051 E = ClassDecl->prop_end(*Context); I != E; ++I)
Steve Naroff6327e0d2009-01-11 01:06:09 +00001052 RewriteProperty(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001053 for (ObjCInterfaceDecl::instmeth_iterator
1054 I = ClassDecl->instmeth_begin(*Context),
1055 E = ClassDecl->instmeth_end(*Context);
1056 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001057 RewriteMethodDeclaration(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001058 for (ObjCInterfaceDecl::classmeth_iterator
1059 I = ClassDecl->classmeth_begin(*Context),
1060 E = ClassDecl->classmeth_end(*Context);
1061 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001062 RewriteMethodDeclaration(*I);
1063
Steve Naroff2feac5e2007-10-30 03:43:13 +00001064 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +00001065 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +00001066}
1067
Steve Naroffb619d952008-12-09 12:56:34 +00001068Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1069 SourceRange SrcRange) {
Steve Naroffc77a6362008-12-04 16:24:46 +00001070 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1071 // This allows us to reuse all the fun and games in SynthMessageExpr().
1072 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1073 ObjCMessageExpr *MsgExpr;
1074 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1075 llvm::SmallVector<Expr *, 1> ExprVec;
1076 ExprVec.push_back(newStmt);
1077
Steve Naroff8599e7a2008-12-08 16:43:47 +00001078 Stmt *Receiver = PropRefExpr->getBase();
1079 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1080 if (PRE && PropGetters[PRE]) {
1081 // This allows us to handle chain/nested property getters.
1082 Receiver = PropGetters[PRE];
1083 }
Ted Kremenek8189cde2009-02-07 01:47:29 +00001084 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
Steve Naroffc77a6362008-12-04 16:24:46 +00001085 PDecl->getSetterName(), PDecl->getType(),
1086 PDecl->getSetterMethodDecl(),
1087 SourceLocation(), SourceLocation(),
1088 &ExprVec[0], 1);
1089 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
1090
1091 // Now do the actual rewrite.
Steve Naroffb619d952008-12-09 12:56:34 +00001092 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffe58ee0c2008-12-10 14:53:27 +00001093 //delete BinOp;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001094 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1095 // to things that stay around.
1096 Context->Deallocate(MsgExpr);
Steve Naroffc77a6362008-12-04 16:24:46 +00001097 return ReplacingStmt;
Steve Naroff15f081d2008-12-03 00:56:33 +00001098}
1099
Steve Naroffc77a6362008-12-04 16:24:46 +00001100Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Naroff15f081d2008-12-03 00:56:33 +00001101 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1102 // This allows us to reuse all the fun and games in SynthMessageExpr().
1103 ObjCMessageExpr *MsgExpr;
1104 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1105
Steve Naroff8599e7a2008-12-08 16:43:47 +00001106 Stmt *Receiver = PropRefExpr->getBase();
1107
1108 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1109 if (PRE && PropGetters[PRE]) {
1110 // This allows us to handle chain/nested property getters.
1111 Receiver = PropGetters[PRE];
1112 }
Ted Kremenek8189cde2009-02-07 01:47:29 +00001113 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
Steve Naroff15f081d2008-12-03 00:56:33 +00001114 PDecl->getGetterName(), PDecl->getType(),
1115 PDecl->getGetterMethodDecl(),
1116 SourceLocation(), SourceLocation(),
1117 0, 0);
1118
Steve Naroff4c3580e2008-12-04 23:50:32 +00001119 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001120
1121 if (!PropParentMap)
1122 PropParentMap = new ParentMap(CurrentBody);
1123
1124 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1125 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1126 // We stash away the ReplacingStmt since actually doing the
1127 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1128 PropGetters[PropRefExpr] = ReplacingStmt;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001129 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1130 // to things that stay around.
1131 Context->Deallocate(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001132 return PropRefExpr; // return the original...
1133 } else {
1134 ReplaceStmt(PropRefExpr, ReplacingStmt);
Ted Kremenek8189cde2009-02-07 01:47:29 +00001135 // delete PropRefExpr; elsewhere...
1136 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1137 // to things that stay around.
1138 Context->Deallocate(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001139 return ReplacingStmt;
1140 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001141}
1142
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001143Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
1144 SourceLocation OrigStart) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001145 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff54055232008-10-27 17:20:55 +00001146 if (CurMethodDef) {
Steve Naroff05b8c782008-03-12 00:25:36 +00001147 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001148 ObjCInterfaceType *iFaceDecl =
1149 dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Narofff0757612008-05-08 17:52:16 +00001150 // lookup which class implements the instance variable.
1151 ObjCInterfaceDecl *clsDeclared = 0;
Douglas Gregor6ab35242009-04-09 21:40:53 +00001152 iFaceDecl->getDecl()->lookupInstanceVariable(*Context,
1153 D->getIdentifier(),
1154 clsDeclared);
Steve Narofff0757612008-05-08 17:52:16 +00001155 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1156
1157 // Synthesize an explicit cast to gain access to the ivar.
1158 std::string RecName = clsDeclared->getIdentifier()->getName();
1159 RecName += "_IMPL";
1160 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001161 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001162 SourceLocation(), II);
Steve Narofff0757612008-05-08 17:52:16 +00001163 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1164 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Ted Kremenek8189cde2009-02-07 01:47:29 +00001165 CastExpr *castExpr = new (Context) CStyleCastExpr(castT, IV->getBase(),
1166 castT,SourceLocation(),
1167 SourceLocation());
Steve Narofff0757612008-05-08 17:52:16 +00001168 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001169 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1170 IV->getBase()->getLocEnd(),
1171 castExpr);
Steve Narofff0757612008-05-08 17:52:16 +00001172 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +00001173 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001174 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1175 IV->getLocation(),
1176 D->getType());
Steve Narofff0757612008-05-08 17:52:16 +00001177 ReplaceStmt(IV, ME);
Steve Naroff4c3580e2008-12-04 23:50:32 +00001178 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Narofff0757612008-05-08 17:52:16 +00001179 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001180 }
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001181
1182 ReplaceStmt(IV->getBase(), PE);
1183 // Cannot delete IV->getBase(), since PE points to it.
1184 // Replace the old base with the cast. This is important when doing
1185 // embedded rewrites. For example, [newInv->_container addObject:0].
1186 IV->setBase(PE);
1187 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001188 }
Steve Naroff84472a82008-04-18 21:55:08 +00001189 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001190 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
1191
1192 // Explicit ivar refs need to have a cast inserted.
1193 // FIXME: consider sharing some of this code with the code above.
1194 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +00001195 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001196 // lookup which class implements the instance variable.
1197 ObjCInterfaceDecl *clsDeclared = 0;
Douglas Gregor6ab35242009-04-09 21:40:53 +00001198 iFaceDecl->getDecl()->lookupInstanceVariable(*Context,
1199 D->getIdentifier(),
1200 clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001201 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1202
1203 // Synthesize an explicit cast to gain access to the ivar.
1204 std::string RecName = clsDeclared->getIdentifier()->getName();
1205 RecName += "_IMPL";
1206 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001207 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001208 SourceLocation(), II);
Steve Naroff9f525972008-05-06 23:20:07 +00001209 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1210 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Ted Kremenek8189cde2009-02-07 01:47:29 +00001211 CastExpr *castExpr = new (Context) CStyleCastExpr(castT, IV->getBase(),
1212 castT, SourceLocation(),
1213 SourceLocation());
Steve Naroff9f525972008-05-06 23:20:07 +00001214 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001215 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner8d366162008-05-28 16:38:23 +00001216 IV->getBase()->getLocEnd(), castExpr);
Steve Naroff9f525972008-05-06 23:20:07 +00001217 ReplaceStmt(IV->getBase(), PE);
1218 // Cannot delete IV->getBase(), since PE points to it.
1219 // Replace the old base with the cast. This is important when doing
1220 // embedded rewrites. For example, [newInv->_container addObject:0].
1221 IV->setBase(PE);
1222 return IV;
1223 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001224 }
Steve Naroff84472a82008-04-18 21:55:08 +00001225 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +00001226}
1227
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001228/// SynthCountByEnumWithState - To print:
1229/// ((unsigned int (*)
1230/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1231/// (void *)objc_msgSend)((id)l_collection,
1232/// sel_registerName(
1233/// "countByEnumeratingWithState:objects:count:"),
1234/// &enumState,
1235/// (id *)items, (unsigned int)16)
1236///
Steve Naroffb29b4272008-04-14 22:03:09 +00001237void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001238 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1239 "id *, unsigned int))(void *)objc_msgSend)";
1240 buf += "\n\t\t";
1241 buf += "((id)l_collection,\n\t\t";
1242 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1243 buf += "\n\t\t";
1244 buf += "&enumState, "
1245 "(id *)items, (unsigned int)16)";
1246}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001247
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001248/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1249/// statement to exit to its outer synthesized loop.
1250///
Steve Naroffb29b4272008-04-14 22:03:09 +00001251Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001252 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1253 return S;
1254 // replace break with goto __break_label
1255 std::string buf;
1256
1257 SourceLocation startLoc = S->getLocStart();
1258 buf = "goto __break_label_";
1259 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001260 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001261
1262 return 0;
1263}
1264
1265/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1266/// statement to continue with its inner synthesized loop.
1267///
Steve Naroffb29b4272008-04-14 22:03:09 +00001268Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001269 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1270 return S;
1271 // replace continue with goto __continue_label
1272 std::string buf;
1273
1274 SourceLocation startLoc = S->getLocStart();
1275 buf = "goto __continue_label_";
1276 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001277 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001278
1279 return 0;
1280}
1281
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001282/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001283/// It rewrites:
1284/// for ( type elem in collection) { stmts; }
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001285
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001286/// Into:
1287/// {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001288/// type elem;
1289/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001290/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001291/// id l_collection = (id)collection;
1292/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1293/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001294/// if (limit) {
1295/// unsigned long startMutations = *enumState.mutationsPtr;
1296/// do {
1297/// unsigned long counter = 0;
1298/// do {
1299/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001300/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001301/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001302/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001303/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001304/// } while (counter < limit);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001305/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1306/// objects:items count:16]);
1307/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001308/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001309/// }
1310/// else
1311/// elem = nil;
1312/// }
1313///
Steve Naroffb29b4272008-04-14 22:03:09 +00001314Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001315 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001316 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1317 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1318 "ObjCForCollectionStmt Statement stack mismatch");
1319 assert(!ObjCBcLabelNo.empty() &&
1320 "ObjCForCollectionStmt - Label No stack empty");
1321
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001322 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001323 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001324 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001325 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001326 std::string buf;
1327 buf = "\n{\n\t";
1328 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1329 // type elem;
Chris Lattner7e24e822009-03-28 06:33:19 +00001330 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001331 QualType ElementType = cast<ValueDecl>(D)->getType();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001332 elementTypeAsString = ElementType.getAsString();
1333 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001334 buf += " ";
Chris Lattner8ec03f52008-11-24 03:54:41 +00001335 elementName = D->getNameAsCString();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001336 buf += elementName;
1337 buf += ";\n\t";
1338 }
Chris Lattner06767512008-04-08 05:52:18 +00001339 else {
1340 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner8ec03f52008-11-24 03:54:41 +00001341 elementName = DR->getDecl()->getNameAsCString();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001342 elementTypeAsString
1343 = cast<ValueDecl>(DR->getDecl())->getType().getAsString();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001344 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001345
1346 // struct __objcFastEnumerationState enumState = { 0 };
1347 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1348 // id items[16];
1349 buf += "id items[16];\n\t";
1350 // id l_collection = (id)
1351 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001352 // Find start location of 'collection' the hard way!
1353 const char *startCollectionBuf = startBuf;
1354 startCollectionBuf += 3; // skip 'for'
1355 startCollectionBuf = strchr(startCollectionBuf, '(');
1356 startCollectionBuf++; // skip '('
1357 // find 'in' and skip it.
1358 while (*startCollectionBuf != ' ' ||
1359 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1360 (*(startCollectionBuf+3) != ' ' &&
1361 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1362 startCollectionBuf++;
1363 startCollectionBuf += 3;
1364
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001365 // Replace: "for (type element in" with string constructed thus far.
Chris Lattneraadaf782008-01-31 19:51:04 +00001366 ReplaceText(startLoc, startCollectionBuf - startBuf,
1367 buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001368 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001369 SourceLocation rightParenLoc = S->getRParenLoc();
1370 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1371 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001372 buf = ";\n\t";
1373
1374 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1375 // objects:items count:16];
1376 // which is synthesized into:
1377 // unsigned int limit =
1378 // ((unsigned int (*)
1379 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1380 // (void *)objc_msgSend)((id)l_collection,
1381 // sel_registerName(
1382 // "countByEnumeratingWithState:objects:count:"),
1383 // (struct __objcFastEnumerationState *)&state,
1384 // (id *)items, (unsigned int)16);
1385 buf += "unsigned long limit =\n\t\t";
1386 SynthCountByEnumWithState(buf);
1387 buf += ";\n\t";
1388 /// if (limit) {
1389 /// unsigned long startMutations = *enumState.mutationsPtr;
1390 /// do {
1391 /// unsigned long counter = 0;
1392 /// do {
1393 /// if (startMutations != *enumState.mutationsPtr)
1394 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001395 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001396 buf += "if (limit) {\n\t";
1397 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1398 buf += "do {\n\t\t";
1399 buf += "unsigned long counter = 0;\n\t\t";
1400 buf += "do {\n\t\t\t";
1401 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1402 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1403 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001404 buf += " = (";
1405 buf += elementTypeAsString;
1406 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001407 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattneraadaf782008-01-31 19:51:04 +00001408 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001409
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001410 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001411 /// } while (counter < limit);
1412 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1413 /// objects:items count:16]);
1414 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001415 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001416 /// }
1417 /// else
1418 /// elem = nil;
1419 /// }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001420 ///
1421 buf = ";\n\t";
1422 buf += "__continue_label_";
1423 buf += utostr(ObjCBcLabelNo.back());
1424 buf += ": ;";
1425 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001426 buf += "} while (counter < limit);\n\t";
1427 buf += "} while (limit = ";
1428 SynthCountByEnumWithState(buf);
1429 buf += ");\n\t";
1430 buf += elementName;
Steve Naroff5605fdf2008-12-17 14:24:39 +00001431 buf += " = ((id)0);\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001432 buf += "__break_label_";
1433 buf += utostr(ObjCBcLabelNo.back());
1434 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001435 buf += "}\n\t";
1436 buf += "else\n\t\t";
1437 buf += elementName;
Steve Naroff5605fdf2008-12-17 14:24:39 +00001438 buf += " = ((id)0);\n";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001439 buf += "}\n";
Steve Naroff600e4e82008-07-21 18:26:02 +00001440
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001441 // Insert all these *after* the statement body.
Sebastian Redld3a413d2009-04-26 20:35:05 +00001442 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Naroff600e4e82008-07-21 18:26:02 +00001443 if (isa<CompoundStmt>(S->getBody())) {
1444 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1445 InsertText(endBodyLoc, buf.c_str(), buf.size());
1446 } else {
1447 /* Need to treat single statements specially. For example:
1448 *
1449 * for (A *a in b) if (stuff()) break;
1450 * for (A *a in b) xxxyy;
1451 *
1452 * The following code simply scans ahead to the semi to find the actual end.
1453 */
1454 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1455 const char *semiBuf = strchr(stmtBuf, ';');
1456 assert(semiBuf && "Can't find ';'");
1457 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1458 InsertText(endBodyLoc, buf.c_str(), buf.size());
1459 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001460 Stmts.pop_back();
1461 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001462 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001463}
1464
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001465/// RewriteObjCSynchronizedStmt -
1466/// This routine rewrites @synchronized(expr) stmt;
1467/// into:
1468/// objc_sync_enter(expr);
1469/// @try stmt @finally { objc_sync_exit(expr); }
1470///
Steve Naroffb29b4272008-04-14 22:03:09 +00001471Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001472 // Get the start location and compute the semi location.
1473 SourceLocation startLoc = S->getLocStart();
1474 const char *startBuf = SM->getCharacterData(startLoc);
1475
1476 assert((*startBuf == '@') && "bogus @synchronized location");
1477
1478 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001479 buf = "objc_sync_enter((id)";
1480 const char *lparenBuf = startBuf;
1481 while (*lparenBuf != '(') lparenBuf++;
1482 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Steve Naroffc7089f12008-08-19 13:04:19 +00001483 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1484 // the sync expression is typically a message expression that's already
1485 // been rewritten! (which implies the SourceLocation's are invalid).
1486 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001487 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001488 while (*endBuf != ')') endBuf--;
1489 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001490 buf = ");\n";
1491 // declare a new scope with two variables, _stack and _rethrow.
1492 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1493 buf += "int buf[18/*32-bit i386*/];\n";
1494 buf += "char *pointers[4];} _stack;\n";
1495 buf += "id volatile _rethrow = 0;\n";
1496 buf += "objc_exception_try_enter(&_stack);\n";
1497 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00001498 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001499 startLoc = S->getSynchBody()->getLocEnd();
1500 startBuf = SM->getCharacterData(startLoc);
1501
Steve Naroffc7089f12008-08-19 13:04:19 +00001502 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001503 SourceLocation lastCurlyLoc = startLoc;
1504 buf = "}\nelse {\n";
1505 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroff621edce2009-04-29 16:37:50 +00001506 buf += "}\n";
1507 buf += "{ /* implicit finally clause */\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001508 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb2a39452008-07-16 19:47:39 +00001509 buf += " objc_sync_exit(";
Ted Kremenek8189cde2009-02-07 01:47:29 +00001510 Expr *syncExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
1511 S->getSynchExpr(),
1512 Context->getObjCIdType(),
1513 SourceLocation(),
1514 SourceLocation());
Ted Kremeneka95d3752008-09-13 05:16:45 +00001515 std::string syncExprBufS;
1516 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Eli Friedman3a9eb442009-05-30 05:19:26 +00001517 syncExpr->printPretty(syncExprBuf, *Context);
Steve Naroffb2a39452008-07-16 19:47:39 +00001518 buf += syncExprBuf.str();
1519 buf += ");\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001520 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1521 buf += "}\n";
1522 buf += "}";
1523
Chris Lattneraadaf782008-01-31 19:51:04 +00001524 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001525 return 0;
1526}
1527
Steve Naroff8c565152008-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 Naroffb29b4272008-04-14 22:03:09 +00001543Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-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 Naroff21867b12007-11-07 18:43:40 +00001557 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001558
Chris Lattneraadaf782008-01-31 19:51:04 +00001559 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001560
1561 startLoc = S->getTryBody()->getLocEnd();
1562 startBuf = SM->getCharacterData(startLoc);
1563
1564 assert((*startBuf == '}') && "bogus @try block");
Steve Naroffc9ba1722008-07-16 15:31:30 +00001565
Steve Naroff75730982007-11-07 04:08:17 +00001566 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffc9ba1722008-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 Naroff8bd3dc62008-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 Naroffc9ba1722008-07-16 15:31:30 +00001583 }
Steve Naroff75730982007-11-07 04:08:17 +00001584 bool sawIdTypedCatch = false;
1585 Stmt *lastCatchBody = 0;
Steve Naroff75730982007-11-07 04:08:17 +00001586 while (catchList) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00001587 ParmVarDecl *catchDecl = catchList->getCatchParamDecl();
Steve Naroff75730982007-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 Naroffbe4b3332008-02-01 22:08:12 +00001600 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001601 // Now rewrite the body...
1602 lastCatchBody = catchList->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001603 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1604 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner06767512008-04-08 05:52:18 +00001605 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1606 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001607 assert((*bodyBuf == '{') && "bogus @catch body location");
1608
1609 buf += "1) { id _tmp = _caught;";
1610 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1611 buf.c_str(), buf.size());
Steve Naroff7ba138a2009-03-03 19:52:17 +00001612 } else if (catchDecl) {
1613 QualType t = catchDecl->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001614 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001615 buf += "1) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001616 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001617 sawIdTypedCatch = true;
1618 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001619 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroff75730982007-11-07 04:08:17 +00001620
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001621 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001622 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001623 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001624 buf += cls->getDecl()->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001625 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001626 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001627 }
1628 }
1629 // Now rewrite the body...
1630 lastCatchBody = catchList->getCatchBody();
1631 SourceLocation rParenLoc = catchList->getRParenLoc();
1632 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1633 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1634 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1635 assert((*rParenBuf == ')') && "bogus @catch paren location");
1636 assert((*bodyBuf == '{') && "bogus @catch body location");
1637
1638 buf = " = _caught;";
1639 // Here we replace ") {" with "= _caught;" (which initializes and
1640 // declares the @catch parameter).
Chris Lattneraadaf782008-01-31 19:51:04 +00001641 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff7ba138a2009-03-03 19:52:17 +00001642 } else {
Steve Naroff75730982007-11-07 04:08:17 +00001643 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001644 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001645 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001646 catchList = catchList->getNextCatchStmt();
1647 }
1648 // Complete the catch list...
1649 if (lastCatchBody) {
1650 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001651 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1652 "bogus @catch body location");
Steve Naroff75730982007-11-07 04:08:17 +00001653
Steve Naroff378f47a2008-09-11 15:29:03 +00001654 // Insert the last (implicit) else clause *before* the right curly brace.
1655 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1656 buf = "} /* last catch end */\n";
1657 buf += "else {\n";
1658 buf += " _rethrow = _caught;\n";
1659 buf += " objc_exception_try_exit(&_stack);\n";
1660 buf += "} } /* @catch end */\n";
1661 if (!S->getFinallyStmt())
1662 buf += "}\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001663 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001664
1665 // Set lastCurlyLoc
1666 lastCurlyLoc = lastCatchBody->getLocEnd();
1667 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001668 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001669 startLoc = finalStmt->getLocStart();
1670 startBuf = SM->getCharacterData(startLoc);
1671 assert((*startBuf == '@') && "bogus @finally start");
1672
1673 buf = "/* @finally */";
Chris Lattneraadaf782008-01-31 19:51:04 +00001674 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001675
1676 Stmt *body = finalStmt->getFinallyBody();
1677 SourceLocation startLoc = body->getLocStart();
1678 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001679 assert(*SM->getCharacterData(startLoc) == '{' &&
1680 "bogus @finally body location");
1681 assert(*SM->getCharacterData(endLoc) == '}' &&
1682 "bogus @finally body location");
Steve Naroff75730982007-11-07 04:08:17 +00001683
1684 startLoc = startLoc.getFileLocWithOffset(1);
1685 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001686 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001687 endLoc = endLoc.getFileLocWithOffset(-1);
1688 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001689 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001690
1691 // Set lastCurlyLoc
1692 lastCurlyLoc = body->getLocEnd();
Steve Naroff8c565152008-12-05 17:03:39 +00001693
1694 // Now check for any return/continue/go statements within the @try.
1695 WarnAboutReturnGotoContinueOrBreakStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00001696 } else { /* no finally clause - make sure we synthesize an implicit one */
1697 buf = "{ /* implicit finally clause */\n";
1698 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1699 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1700 buf += "}";
1701 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001702 }
1703 // Now emit the final closing curly brace...
1704 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1705 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001706 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001707 return 0;
1708}
1709
Steve Naroffb29b4272008-04-14 22:03:09 +00001710Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001711 return 0;
1712}
1713
Steve Naroffb29b4272008-04-14 22:03:09 +00001714Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001715 return 0;
1716}
1717
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001718// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff2bd03922007-11-07 15:32:26 +00001719// the throw expression is typically a message expression that's already
1720// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001721Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001722 // Get the start location and compute the semi location.
1723 SourceLocation startLoc = S->getLocStart();
1724 const char *startBuf = SM->getCharacterData(startLoc);
1725
1726 assert((*startBuf == '@') && "bogus @throw location");
1727
1728 std::string buf;
1729 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001730 if (S->getThrowExpr())
1731 buf = "objc_exception_throw(";
1732 else // add an implicit argument
1733 buf = "objc_exception_throw(_caught";
Steve Naroff4ba0acb2008-07-25 15:41:30 +00001734
1735 // handle "@ throw" correctly.
1736 const char *wBuf = strchr(startBuf, 'w');
1737 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1738 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
1739
Steve Naroff2bd03922007-11-07 15:32:26 +00001740 const char *semiBuf = strchr(startBuf, ';');
1741 assert((*semiBuf == ';') && "@throw: can't find ';'");
1742 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1743 buf = ");";
Chris Lattneraadaf782008-01-31 19:51:04 +00001744 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001745 return 0;
1746}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001747
Steve Naroffb29b4272008-04-14 22:03:09 +00001748Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001749 // Create a new string expression.
1750 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001751 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001752 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattner2085fd62009-02-18 06:40:38 +00001753 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
1754 StrEncoding.length(), false,StrType,
1755 SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001756 ReplaceStmt(Exp, Replacement);
Chris Lattnere365c502007-11-30 22:25:36 +00001757
Chris Lattner07506182007-11-30 22:53:43 +00001758 // Replace this subexpr in the parent.
Steve Naroff4c3580e2008-12-04 23:50:32 +00001759 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00001760 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001761}
1762
Steve Naroffb29b4272008-04-14 22:03:09 +00001763Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff1a937642008-12-22 22:16:07 +00001764 if (!SelGetUidFunctionDecl)
1765 SynthSelGetUidFunctionDecl();
Steve Naroffb42f8412007-11-05 14:50:49 +00001766 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1767 // Create a call to sel_registerName("selName").
1768 llvm::SmallVector<Expr*, 8> SelExprs;
1769 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner2085fd62009-02-18 06:40:38 +00001770 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00001771 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00001772 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00001773 false, argType, SourceLocation()));
Steve Naroffb42f8412007-11-05 14:50:49 +00001774 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1775 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001776 ReplaceStmt(Exp, SelExp);
Steve Naroff4c3580e2008-12-04 23:50:32 +00001777 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00001778 return SelExp;
1779}
1780
Steve Naroffb29b4272008-04-14 22:03:09 +00001781CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff934f2762007-10-24 22:48:43 +00001782 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001783 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001784 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +00001785
1786 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001787 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +00001788
1789 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001790 QualType pToFunc = Context->getPointerType(msgSendType);
Ted Kremenek8189cde2009-02-07 01:47:29 +00001791 ImplicitCastExpr *ICE = new (Context) ImplicitCastExpr(pToFunc, DRE,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001792 /*isLvalue=*/false);
Steve Naroffebf2b562007-10-23 23:50:29 +00001793
1794 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +00001795
Ted Kremenek668bf912009-02-09 20:51:47 +00001796 return new (Context) CallExpr(*Context, ICE, args, nargs, FT->getResultType(),
1797 SourceLocation());
Steve Naroff934f2762007-10-24 22:48:43 +00001798}
1799
Steve Naroffd5255f52007-11-01 13:24:47 +00001800static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1801 const char *&startRef, const char *&endRef) {
1802 while (startBuf < endBuf) {
1803 if (*startBuf == '<')
1804 startRef = startBuf; // mark the start.
1805 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001806 if (startRef && *startRef == '<') {
1807 endRef = startBuf; // mark the end.
1808 return true;
1809 }
1810 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001811 }
1812 startBuf++;
1813 }
1814 return false;
1815}
1816
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001817static void scanToNextArgument(const char *&argRef) {
1818 int angle = 0;
1819 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1820 if (*argRef == '<')
1821 angle++;
1822 else if (*argRef == '>')
1823 angle--;
1824 argRef++;
1825 }
1826 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1827}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001828
Steve Naroffb29b4272008-04-14 22:03:09 +00001829bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001830
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001831 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001832 return true;
1833
Steve Naroffd5255f52007-11-01 13:24:47 +00001834 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +00001835 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001836 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff9165ad32007-10-31 04:38:33 +00001837 return true; // we have "Class <Protocol> *".
1838 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001839 return false;
1840}
1841
Steve Naroff4f95b752008-07-29 18:15:38 +00001842void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1843 QualType Type = E->getType();
1844 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00001845 SourceLocation Loc, EndLoc;
1846
1847 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
1848 Loc = ECE->getLParenLoc();
1849 EndLoc = ECE->getRParenLoc();
1850 } else {
1851 Loc = E->getLocStart();
1852 EndLoc = E->getLocEnd();
1853 }
1854 // This will defend against trying to rewrite synthesized expressions.
1855 if (Loc.isInvalid() || EndLoc.isInvalid())
1856 return;
1857
Steve Naroff4f95b752008-07-29 18:15:38 +00001858 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00001859 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00001860 const char *startRef = 0, *endRef = 0;
1861 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1862 // Get the locations of the startRef, endRef.
1863 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1864 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1865 // Comment out the protocol references.
1866 InsertText(LessLoc, "/*", 2);
1867 InsertText(GreaterLoc, "*/", 2);
1868 }
1869 }
1870}
1871
Steve Naroffb29b4272008-04-14 22:03:09 +00001872void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001873 SourceLocation Loc;
1874 QualType Type;
Douglas Gregor72564e72009-02-26 23:50:07 +00001875 const FunctionProtoType *proto = 0;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001876 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1877 Loc = VD->getLocation();
1878 Type = VD->getType();
1879 }
1880 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1881 Loc = FD->getLocation();
1882 // Check for ObjC 'id' and class types that have been adorned with protocol
1883 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1884 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1885 assert(funcType && "missing function type");
Douglas Gregor72564e72009-02-26 23:50:07 +00001886 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001887 if (!proto)
1888 return;
1889 Type = proto->getResultType();
1890 }
1891 else
1892 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001893
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001894 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001895 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001896
1897 const char *endBuf = SM->getCharacterData(Loc);
1898 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00001899 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001900 startBuf--; // scan backward (from the decl location) for return type.
1901 const char *startRef = 0, *endRef = 0;
1902 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1903 // Get the locations of the startRef, endRef.
1904 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1905 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1906 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001907 InsertText(LessLoc, "/*", 2);
1908 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001909 }
1910 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001911 if (!proto)
1912 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001913 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001914 const char *startBuf = SM->getCharacterData(Loc);
1915 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001916 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1917 if (needToScanForQualifiers(proto->getArgType(i))) {
1918 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001919
Steve Naroffd5255f52007-11-01 13:24:47 +00001920 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001921 // scan forward (from the decl location) for argument types.
1922 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001923 const char *startRef = 0, *endRef = 0;
1924 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1925 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001926 SourceLocation LessLoc =
1927 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1928 SourceLocation GreaterLoc =
1929 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001930 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001931 InsertText(LessLoc, "/*", 2);
1932 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001933 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001934 startBuf = ++endBuf;
1935 }
1936 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00001937 // If the function name is derived from a macro expansion, then the
1938 // argument buffer will not follow the name. Need to speak with Chris.
1939 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001940 startBuf++; // scan forward (from the decl location) for argument types.
1941 startBuf++;
1942 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001943 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001944}
1945
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001946// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00001947void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001948 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1949 llvm::SmallVector<QualType, 16> ArgTys;
1950 ArgTys.push_back(Context->getPointerType(
1951 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001952 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001953 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001954 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001955 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001956 SourceLocation(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001957 SelGetUidIdent, getFuncType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001958 FunctionDecl::Extern, false);
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001959}
1960
Steve Naroffb29b4272008-04-14 22:03:09 +00001961void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001962 // declared in <objc/objc.h>
Douglas Gregor51efe562009-01-09 01:47:02 +00001963 if (FD->getIdentifier() &&
1964 strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001965 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001966 return;
1967 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001968 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001969}
1970
Steve Naroffc0a123c2008-03-11 17:37:02 +00001971// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00001972void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00001973 if (SuperContructorFunctionDecl)
1974 return;
Steve Naroff46a98a72008-12-23 20:11:22 +00001975 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroffc0a123c2008-03-11 17:37:02 +00001976 llvm::SmallVector<QualType, 16> ArgTys;
1977 QualType argT = Context->getObjCIdType();
1978 assert(!argT.isNull() && "Can't find 'id' type");
1979 ArgTys.push_back(argT);
1980 ArgTys.push_back(argT);
1981 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1982 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001983 false, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001984 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001985 SourceLocation(),
Steve Naroffc0a123c2008-03-11 17:37:02 +00001986 msgSendIdent, msgSendType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001987 FunctionDecl::Extern, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00001988}
1989
Steve Naroff09b266e2007-10-30 23:14:51 +00001990// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001991void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00001992 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1993 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001994 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001995 assert(!argT.isNull() && "Can't find 'id' type");
1996 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001997 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001998 assert(!argT.isNull() && "Can't find 'SEL' type");
1999 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002000 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002001 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002002 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002003 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002004 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002005 msgSendIdent, msgSendType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002006 FunctionDecl::Extern, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002007}
2008
Steve Naroff874e2322007-11-15 10:28:18 +00002009// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002010void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00002011 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2012 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002013 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002014 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002015 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002016 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2017 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2018 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002019 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002020 assert(!argT.isNull() && "Can't find 'SEL' type");
2021 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002022 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00002023 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002024 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002025 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002026 SourceLocation(),
Steve Naroff874e2322007-11-15 10:28:18 +00002027 msgSendIdent, msgSendType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002028 FunctionDecl::Extern, false);
Steve Naroff874e2322007-11-15 10:28:18 +00002029}
2030
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002031// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002032void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002033 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2034 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002035 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002036 assert(!argT.isNull() && "Can't find 'id' type");
2037 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002038 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002039 assert(!argT.isNull() && "Can't find 'SEL' type");
2040 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002041 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002042 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002043 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002044 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002045 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002046 msgSendIdent, msgSendType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002047 FunctionDecl::Extern, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002048}
2049
2050// SynthMsgSendSuperStretFunctionDecl -
2051// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002052void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002053 IdentifierInfo *msgSendIdent =
2054 &Context->Idents.get("objc_msgSendSuper_stret");
2055 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002056 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002057 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002058 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002059 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2060 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2061 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002062 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002063 assert(!argT.isNull() && "Can't find 'SEL' type");
2064 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002065 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002066 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002067 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002068 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnera98e58d2008-03-15 21:24:04 +00002069 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002070 msgSendIdent, msgSendType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002071 FunctionDecl::Extern, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002072}
2073
Steve Naroff1284db82008-05-08 22:02:18 +00002074// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002075void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002076 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2077 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002078 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002079 assert(!argT.isNull() && "Can't find 'id' type");
2080 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002081 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002082 assert(!argT.isNull() && "Can't find 'SEL' type");
2083 ArgTys.push_back(argT);
Steve Naroff1284db82008-05-08 22:02:18 +00002084 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002085 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002086 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002087 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002088 SourceLocation(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002089 msgSendIdent, msgSendType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002090 FunctionDecl::Extern, false);
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002091}
2092
Steve Naroff09b266e2007-10-30 23:14:51 +00002093// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002094void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002095 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2096 llvm::SmallVector<QualType, 16> ArgTys;
2097 ArgTys.push_back(Context->getPointerType(
2098 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002099 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002100 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002101 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002102 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002103 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002104 getClassIdent, getClassType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002105 FunctionDecl::Extern, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002106}
2107
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002108// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002109void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002110 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2111 llvm::SmallVector<QualType, 16> ArgTys;
2112 ArgTys.push_back(Context->getPointerType(
2113 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002114 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002115 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002116 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002117 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002118 SourceLocation(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002119 getClassIdent, getClassType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002120 FunctionDecl::Extern, false);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002121}
2122
Steve Naroffb29b4272008-04-14 22:03:09 +00002123Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002124 QualType strType = getConstantStringStructType();
2125
2126 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002127
2128 std::string tmpName = InFileName;
2129 unsigned i;
2130 for (i=0; i < tmpName.length(); i++) {
2131 char c = tmpName.at(i);
2132 // replace any non alphanumeric characters with '_'.
2133 if (!isalpha(c) && (c < '0' || c > '9'))
2134 tmpName[i] = '_';
2135 }
2136 S += tmpName;
2137 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002138 S += utostr(NumObjCStringLiterals++);
2139
Steve Naroffba92b2e2008-03-27 22:29:16 +00002140 Preamble += "static __NSConstantStringImpl " + S;
2141 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2142 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002143 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002144 std::string prettyBufS;
2145 llvm::raw_string_ostream prettyBuf(prettyBufS);
Eli Friedman3a9eb442009-05-30 05:19:26 +00002146 Exp->getString()->printPretty(prettyBuf, *Context);
Steve Naroffba92b2e2008-03-27 22:29:16 +00002147 Preamble += prettyBuf.str();
2148 Preamble += ",";
Steve Naroff3652c2d2008-03-15 01:36:04 +00002149 // The minus 2 removes the begin/end double quotes.
Steve Naroffba92b2e2008-03-27 22:29:16 +00002150 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002151
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002152 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Steve Naroff248a7532008-04-15 22:42:06 +00002153 &Context->Idents.get(S.c_str()), strType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002154 VarDecl::Static);
Ted Kremenek8189cde2009-02-07 01:47:29 +00002155 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
2156 Expr *Unop = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002157 Context->getPointerType(DRE->getType()),
2158 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002159 // cast to NSConstantString *
Ted Kremenek8189cde2009-02-07 01:47:29 +00002160 CastExpr *cast = new (Context) CStyleCastExpr(Exp->getType(), Unop,
Steve Naroffb2f9e512008-11-03 23:29:32 +00002161 Exp->getType(), SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002162 ReplaceStmt(Exp, cast);
Steve Naroff4c3580e2008-12-04 23:50:32 +00002163 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002164 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002165}
2166
Steve Naroffb29b4272008-04-14 22:03:09 +00002167ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002168 // check if we are sending a message to 'super'
Douglas Gregorf8d49f62009-01-09 17:18:27 +00002169 if (!CurMethodDef || !CurMethodDef->isInstanceMethod()) return 0;
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002170
Douglas Gregorcd9b46e2008-11-04 14:56:14 +00002171 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
2172 const PointerType *PT = Super->getType()->getAsPointerType();
Chris Lattner0d17f6f2008-06-21 18:04:54 +00002173 assert(PT);
2174 ObjCInterfaceType *IT = cast<ObjCInterfaceType>(PT->getPointeeType());
2175 return IT->getDecl();
2176 }
2177 return 0;
Steve Naroff874e2322007-11-15 10:28:18 +00002178}
2179
2180// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002181QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002182 if (!SuperStructDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002183 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002184 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002185 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002186 QualType FieldTypes[2];
2187
2188 // struct objc_object *receiver;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002189 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002190 // struct objc_class *super;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002191 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor44b43212008-12-11 16:49:14 +00002192
Steve Naroff874e2322007-11-15 10:28:18 +00002193 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002194 for (unsigned i = 0; i < 2; ++i) {
Douglas Gregor6ab35242009-04-09 21:40:53 +00002195 SuperStructDecl->addDecl(*Context,
2196 FieldDecl::Create(*Context, SuperStructDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00002197 SourceLocation(), 0,
2198 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002199 /*Mutable=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002200 }
Steve Naroff874e2322007-11-15 10:28:18 +00002201
Douglas Gregor44b43212008-12-11 16:49:14 +00002202 SuperStructDecl->completeDefinition(*Context);
Steve Naroff874e2322007-11-15 10:28:18 +00002203 }
2204 return Context->getTagDeclType(SuperStructDecl);
2205}
2206
Steve Naroffb29b4272008-04-14 22:03:09 +00002207QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002208 if (!ConstantStringDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002209 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002210 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002211 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002212 QualType FieldTypes[4];
2213
2214 // struct objc_object *receiver;
2215 FieldTypes[0] = Context->getObjCIdType();
2216 // int flags;
2217 FieldTypes[1] = Context->IntTy;
2218 // char *str;
2219 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2220 // long length;
2221 FieldTypes[3] = Context->LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002222
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002223 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002224 for (unsigned i = 0; i < 4; ++i) {
Douglas Gregor6ab35242009-04-09 21:40:53 +00002225 ConstantStringDecl->addDecl(*Context,
2226 FieldDecl::Create(*Context,
Douglas Gregor44b43212008-12-11 16:49:14 +00002227 ConstantStringDecl,
2228 SourceLocation(), 0,
2229 FieldTypes[i],
2230 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002231 /*Mutable=*/true));
Douglas Gregor44b43212008-12-11 16:49:14 +00002232 }
2233
2234 ConstantStringDecl->completeDefinition(*Context);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002235 }
2236 return Context->getTagDeclType(ConstantStringDecl);
2237}
2238
Steve Naroffb29b4272008-04-14 22:03:09 +00002239Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002240 if (!SelGetUidFunctionDecl)
2241 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002242 if (!MsgSendFunctionDecl)
2243 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002244 if (!MsgSendSuperFunctionDecl)
2245 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002246 if (!MsgSendStretFunctionDecl)
2247 SynthMsgSendStretFunctionDecl();
2248 if (!MsgSendSuperStretFunctionDecl)
2249 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002250 if (!MsgSendFpretFunctionDecl)
2251 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002252 if (!GetClassFunctionDecl)
2253 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002254 if (!GetMetaClassFunctionDecl)
2255 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002256
Steve Naroff874e2322007-11-15 10:28:18 +00002257 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002258 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2259 // May need to use objc_msgSend_stret() as well.
2260 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroff621edce2009-04-29 16:37:50 +00002261 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2262 QualType resultType = mDecl->getResultType();
Chris Lattner8b51fd72008-07-26 22:36:27 +00002263 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002264 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002265 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002266 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002267 }
Steve Naroff874e2322007-11-15 10:28:18 +00002268
Steve Naroff934f2762007-10-24 22:48:43 +00002269 // Synthesize a call to objc_msgSend().
2270 llvm::SmallVector<Expr*, 8> MsgExprs;
2271 IdentifierInfo *clsName = Exp->getClassName();
2272
2273 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2274 if (clsName) { // class message.
Steve Narofffc93d522008-07-24 19:44:33 +00002275 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2276 // the 'super' idiom within a class method.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002277 if (!strcmp(clsName->getName(), "super")) {
2278 MsgSendFlavor = MsgSendSuperFunctionDecl;
2279 if (MsgSendStretFlavor)
2280 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2281 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2282
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002283 ObjCInterfaceDecl *SuperDecl =
Steve Naroff54055232008-10-27 17:20:55 +00002284 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002285
2286 llvm::SmallVector<Expr*, 4> InitExprs;
2287
2288 // set the receiver to self, the first argument to all methods.
Steve Naroff621edce2009-04-29 16:37:50 +00002289 InitExprs.push_back(
2290 new (Context) CStyleCastExpr(Context->getObjCIdType(),
2291 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
2292 Context->getObjCIdType(),
2293 SourceLocation()),
2294 Context->getObjCIdType(),
2295 SourceLocation(), SourceLocation())); // set the 'receiver'.
2296
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002297 llvm::SmallVector<Expr*, 8> ClsExprs;
2298 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner2085fd62009-02-18 06:40:38 +00002299 ClsExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002300 SuperDecl->getIdentifier()->getName(),
2301 SuperDecl->getIdentifier()->getLength(),
Chris Lattner726e1682009-02-18 05:49:11 +00002302 false, argType, SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002303 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2304 &ClsExprs[0],
2305 ClsExprs.size());
2306 // To turn off a warning, type-cast to 'id'
Douglas Gregor49badde2008-10-27 19:41:14 +00002307 InitExprs.push_back( // set 'super class', using objc_getClass().
Ted Kremenek8189cde2009-02-07 01:47:29 +00002308 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002309 Cls, Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002310 SourceLocation(), SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002311 // struct objc_super
2312 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00002313 Expr *SuperRep;
Steve Naroffc0a123c2008-03-11 17:37:02 +00002314
Steve Naroff23f41272008-03-11 18:14:26 +00002315 if (LangOpts.Microsoft) {
2316 SynthSuperContructorFunctionDecl();
2317 // Simulate a contructor call...
Ted Kremenek8189cde2009-02-07 01:47:29 +00002318 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff23f41272008-03-11 18:14:26 +00002319 superType, SourceLocation());
Ted Kremenek668bf912009-02-09 20:51:47 +00002320 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2321 InitExprs.size(),
2322 superType, SourceLocation());
Steve Naroff46a98a72008-12-23 20:11:22 +00002323 // The code for super is a little tricky to prevent collision with
2324 // the structure definition in the header. The rewriter has it's own
2325 // internal definition (__rw_objc_super) that is uses. This is why
2326 // we need the cast below. For example:
2327 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2328 //
Ted Kremenek8189cde2009-02-07 01:47:29 +00002329 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Steve Naroff46a98a72008-12-23 20:11:22 +00002330 Context->getPointerType(SuperRep->getType()),
2331 SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00002332 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
Steve Naroff46a98a72008-12-23 20:11:22 +00002333 SuperRep, Context->getPointerType(superType),
2334 SourceLocation(), SourceLocation());
Steve Naroff23f41272008-03-11 18:14:26 +00002335 } else {
2336 // (struct objc_super) { <exprs from above> }
Ted Kremenek8189cde2009-02-07 01:47:29 +00002337 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
Steve Naroff23f41272008-03-11 18:14:26 +00002338 &InitExprs[0], InitExprs.size(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002339 SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00002340 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE,
Chris Lattner418f6c72008-10-26 23:43:26 +00002341 false);
Steve Naroff46a98a72008-12-23 20:11:22 +00002342 // struct objc_super *
Ted Kremenek8189cde2009-02-07 01:47:29 +00002343 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Steve Naroff46a98a72008-12-23 20:11:22 +00002344 Context->getPointerType(SuperRep->getType()),
2345 SourceLocation());
Steve Naroff23f41272008-03-11 18:14:26 +00002346 }
Steve Naroff46a98a72008-12-23 20:11:22 +00002347 MsgExprs.push_back(SuperRep);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002348 } else {
2349 llvm::SmallVector<Expr*, 8> ClsExprs;
2350 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner2085fd62009-02-18 06:40:38 +00002351 ClsExprs.push_back(StringLiteral::Create(*Context,
2352 clsName->getName(),
2353 clsName->getLength(),
2354 false, argType,
2355 SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002356 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2357 &ClsExprs[0],
2358 ClsExprs.size());
2359 MsgExprs.push_back(Cls);
2360 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002361 } else { // instance message.
2362 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00002363
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002364 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00002365 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002366 if (MsgSendStretFlavor)
2367 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00002368 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2369
2370 llvm::SmallVector<Expr*, 4> InitExprs;
2371
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002372 InitExprs.push_back(
Ted Kremenek8189cde2009-02-07 01:47:29 +00002373 new (Context) CStyleCastExpr(Context->getObjCIdType(),
2374 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Narofff616ebb2008-07-16 22:35:27 +00002375 Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002376 SourceLocation()),
2377 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002378 SourceLocation(), SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00002379
2380 llvm::SmallVector<Expr*, 8> ClsExprs;
2381 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner2085fd62009-02-18 06:40:38 +00002382 ClsExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002383 SuperDecl->getIdentifier()->getName(),
2384 SuperDecl->getIdentifier()->getLength(),
Chris Lattner726e1682009-02-18 05:49:11 +00002385 false, argType, SourceLocation()));
Steve Naroff874e2322007-11-15 10:28:18 +00002386 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002387 &ClsExprs[0],
2388 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00002389 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002390 InitExprs.push_back(
Douglas Gregor49badde2008-10-27 19:41:14 +00002391 // set 'super class', using objc_getClass().
Ted Kremenek8189cde2009-02-07 01:47:29 +00002392 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002393 Cls, Context->getObjCIdType(), SourceLocation(), SourceLocation()));
Steve Naroff874e2322007-11-15 10:28:18 +00002394 // struct objc_super
2395 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00002396 Expr *SuperRep;
2397
2398 if (LangOpts.Microsoft) {
2399 SynthSuperContructorFunctionDecl();
2400 // Simulate a contructor call...
Ted Kremenek8189cde2009-02-07 01:47:29 +00002401 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroffc0a123c2008-03-11 17:37:02 +00002402 superType, SourceLocation());
Ted Kremenek668bf912009-02-09 20:51:47 +00002403 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2404 InitExprs.size(),
2405 superType, SourceLocation());
Steve Naroff46a98a72008-12-23 20:11:22 +00002406 // The code for super is a little tricky to prevent collision with
2407 // the structure definition in the header. The rewriter has it's own
2408 // internal definition (__rw_objc_super) that is uses. This is why
2409 // we need the cast below. For example:
2410 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2411 //
Ted Kremenek8189cde2009-02-07 01:47:29 +00002412 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Steve Naroff46a98a72008-12-23 20:11:22 +00002413 Context->getPointerType(SuperRep->getType()),
2414 SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00002415 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
Steve Naroff46a98a72008-12-23 20:11:22 +00002416 SuperRep, Context->getPointerType(superType),
2417 SourceLocation(), SourceLocation());
Steve Naroffc0a123c2008-03-11 17:37:02 +00002418 } else {
2419 // (struct objc_super) { <exprs from above> }
Ted Kremenek8189cde2009-02-07 01:47:29 +00002420 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
Steve Naroffc0a123c2008-03-11 17:37:02 +00002421 &InitExprs[0], InitExprs.size(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002422 SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00002423 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002424 }
Steve Naroff46a98a72008-12-23 20:11:22 +00002425 MsgExprs.push_back(SuperRep);
Steve Naroff874e2322007-11-15 10:28:18 +00002426 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002427 // Remove all type-casts because it may contain objc-style types; e.g.
2428 // Foo<Proto> *.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002429 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002430 recExpr = CE->getSubExpr();
Ted Kremenek8189cde2009-02-07 01:47:29 +00002431 recExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(), recExpr,
Douglas Gregor49badde2008-10-27 19:41:14 +00002432 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002433 SourceLocation(), SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00002434 MsgExprs.push_back(recExpr);
2435 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002436 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00002437 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002438 llvm::SmallVector<Expr*, 8> SelExprs;
2439 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner2085fd62009-02-18 06:40:38 +00002440 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002441 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00002442 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00002443 false, argType, SourceLocation()));
Steve Naroff934f2762007-10-24 22:48:43 +00002444 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2445 &SelExprs[0], SelExprs.size());
2446 MsgExprs.push_back(SelExp);
2447
2448 // Now push any user supplied arguments.
2449 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002450 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002451 // Make all implicit casts explicit...ICE comes in handy:-)
2452 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2453 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregor49badde2008-10-27 19:41:14 +00002454 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002455 ? Context->getObjCIdType()
Douglas Gregor49badde2008-10-27 19:41:14 +00002456 : ICE->getType();
Ted Kremenek8189cde2009-02-07 01:47:29 +00002457 userExpr = new (Context) CStyleCastExpr(type, userExpr, type, SourceLocation(), SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002458 }
2459 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002460 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002461 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002462 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002463 userExpr = CE->getSubExpr();
Ted Kremenek8189cde2009-02-07 01:47:29 +00002464 userExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002465 userExpr, Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002466 SourceLocation(), SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002467 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00002468 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002469 MsgExprs.push_back(userExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00002470 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2471 // out the argument in the original expression (since we aren't deleting
2472 // the ObjCMessageExpr). See RewritePropertySetter() usage for more info.
2473 //Exp->setArg(i, 0);
Steve Naroff934f2762007-10-24 22:48:43 +00002474 }
Steve Naroffab972d32007-11-04 22:37:50 +00002475 // Generate the funky cast.
2476 CastExpr *cast;
2477 llvm::SmallVector<QualType, 8> ArgTypes;
2478 QualType returnType;
2479
2480 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002481 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2482 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2483 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002484 ArgTypes.push_back(Context->getObjCIdType());
2485 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner89951a82009-02-20 18:43:26 +00002486 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002487 // Push any user argument types.
Chris Lattner89951a82009-02-20 18:43:26 +00002488 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2489 E = OMD->param_end(); PI != E; ++PI) {
2490 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002491 ? Context->getObjCIdType()
Chris Lattner89951a82009-02-20 18:43:26 +00002492 : (*PI)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00002493 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroff01f2ffa2008-12-11 21:05:33 +00002494 if (isTopLevelBlockPointerType(t)) {
Steve Naroffa206b062008-10-29 14:49:46 +00002495 const BlockPointerType *BPT = t->getAsBlockPointerType();
2496 t = Context->getPointerType(BPT->getPointeeType());
2497 }
Steve Naroff352336b2007-11-05 14:36:37 +00002498 ArgTypes.push_back(t);
2499 }
Chris Lattner89951a82009-02-20 18:43:26 +00002500 returnType = OMD->getResultType()->isObjCQualifiedIdType()
2501 ? Context->getObjCIdType() : OMD->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00002502 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002503 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002504 }
2505 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002506 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00002507
2508 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002509 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002510 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002511
2512 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2513 // If we don't do this cast, we get the following bizarre warning/note:
2514 // xx.m:13: warning: function called through a non-compatible type
2515 // xx.m:13: note: if this code is reached, the program will abort
Ted Kremenek8189cde2009-02-07 01:47:29 +00002516 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy), DRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002517 Context->getPointerType(Context->VoidTy),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002518 SourceLocation(), SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00002519
Steve Naroffab972d32007-11-04 22:37:50 +00002520 // Now do the "normal" pointer to function cast.
2521 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002522 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00002523 // If we don't have a method decl, force a variadic cast.
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002524 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Naroffab972d32007-11-04 22:37:50 +00002525 castType = Context->getPointerType(castType);
Ted Kremenek8189cde2009-02-07 01:47:29 +00002526 cast = new (Context) CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002527
2528 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002529 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Steve Naroffab972d32007-11-04 22:37:50 +00002530
2531 const FunctionType *FT = msgSendType->getAsFunctionType();
Ted Kremenek668bf912009-02-09 20:51:47 +00002532 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2533 MsgExprs.size(),
2534 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002535 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002536 if (MsgSendStretFlavor) {
2537 // We have the method which returns a struct/union. Must also generate
2538 // call to objc_msgSend_stret and hang both varieties on a conditional
2539 // expression which dictate which one to envoke depending on size of
2540 // method's return type.
2541
2542 // Create a reference to the objc_msgSend_stret() declaration.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002543 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002544 SourceLocation());
2545 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Ted Kremenek8189cde2009-02-07 01:47:29 +00002546 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy), STDRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002547 Context->getPointerType(Context->VoidTy),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002548 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002549 // Now do the "normal" pointer to function cast.
2550 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002551 &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002552 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002553 castType = Context->getPointerType(castType);
Ted Kremenek8189cde2009-02-07 01:47:29 +00002554 cast = new (Context) CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002555
2556 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002557 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002558
2559 FT = msgSendType->getAsFunctionType();
Ted Kremenek668bf912009-02-09 20:51:47 +00002560 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2561 MsgExprs.size(),
2562 FT->getResultType(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002563
2564 // Build sizeof(returnType)
Douglas Gregorba498172009-03-13 21:01:28 +00002565 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
2566 returnType,
Sebastian Redl05189992008-11-11 17:56:53 +00002567 Context->getSizeType(),
2568 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002569 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2570 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2571 // For X86 it is more complicated and some kind of target specific routine
2572 // is needed to decide what to do.
Chris Lattner98be4942008-03-05 18:54:05 +00002573 unsigned IntSize =
2574 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Ted Kremenek8189cde2009-02-07 01:47:29 +00002575 IntegerLiteral *limit = new (Context) IntegerLiteral(llvm::APInt(IntSize, 8),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002576 Context->IntTy,
2577 SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00002578 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002579 BinaryOperator::LE,
2580 Context->IntTy,
2581 SourceLocation());
2582 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2583 ConditionalOperator *CondExpr =
Ted Kremenek8189cde2009-02-07 01:47:29 +00002584 new (Context) ConditionalOperator(lessThanExpr, CE, STCE, returnType);
2585 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002586 }
Steve Naroff621edce2009-04-29 16:37:50 +00002587 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002588 return ReplacingStmt;
2589}
2590
Steve Naroffb29b4272008-04-14 22:03:09 +00002591Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002592 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff80c28552008-10-27 20:54:44 +00002593
Steve Naroff934f2762007-10-24 22:48:43 +00002594 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002595 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff934f2762007-10-24 22:48:43 +00002596
Steve Naroff4c3580e2008-12-04 23:50:32 +00002597 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002598 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002599}
2600
Steve Naroff621edce2009-04-29 16:37:50 +00002601// typedef struct objc_object Protocol;
2602QualType RewriteObjC::getProtocolType() {
2603 if (!ProtocolTypeDecl) {
2604 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
2605 SourceLocation(),
2606 &Context->Idents.get("Protocol"),
2607 Context->getObjCIdType());
2608 }
2609 return Context->getTypeDeclType(ProtocolTypeDecl);
2610}
2611
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002612/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroff621edce2009-04-29 16:37:50 +00002613/// a synthesized/forward data reference (to the protocol's metadata).
2614/// The forward references (and metadata) are generated in
2615/// RewriteObjC::HandleTranslationUnit().
Steve Naroffb29b4272008-04-14 22:03:09 +00002616Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroff621edce2009-04-29 16:37:50 +00002617 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
2618 IdentifierInfo *ID = &Context->Idents.get(Name);
2619 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2620 ID, QualType()/*UNUSED*/, VarDecl::Extern);
2621 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), SourceLocation());
2622 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
2623 Context->getPointerType(DRE->getType()),
2624 SourceLocation());
2625 CastExpr *castExpr = new (Context) CStyleCastExpr(DerefExpr->getType(), DerefExpr,
2626 DerefExpr->getType(),
2627 SourceLocation(), SourceLocation());
2628 ReplaceStmt(Exp, castExpr);
2629 ProtocolExprDecls.insert(Exp->getProtocol());
2630 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
2631 return castExpr;
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002632
2633}
2634
Steve Naroffbaf58c32008-05-31 14:15:04 +00002635bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
2636 const char *endBuf) {
2637 while (startBuf < endBuf) {
2638 if (*startBuf == '#') {
2639 // Skip whitespace.
2640 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2641 ;
2642 if (!strncmp(startBuf, "if", strlen("if")) ||
2643 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2644 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2645 !strncmp(startBuf, "define", strlen("define")) ||
2646 !strncmp(startBuf, "undef", strlen("undef")) ||
2647 !strncmp(startBuf, "else", strlen("else")) ||
2648 !strncmp(startBuf, "elif", strlen("elif")) ||
2649 !strncmp(startBuf, "endif", strlen("endif")) ||
2650 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2651 !strncmp(startBuf, "include", strlen("include")) ||
2652 !strncmp(startBuf, "import", strlen("import")) ||
2653 !strncmp(startBuf, "include_next", strlen("include_next")))
2654 return true;
2655 }
2656 startBuf++;
2657 }
2658 return false;
2659}
2660
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002661/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002662/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00002663void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002664 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002665 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Chris Lattner8ec03f52008-11-24 03:54:41 +00002666 assert(CDecl->getNameAsCString() &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002667 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002668 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002669 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002670 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002671 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002672 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00002673 SourceLocation LocStart = CDecl->getLocStart();
2674 SourceLocation LocEnd = CDecl->getLocEnd();
2675
2676 const char *startBuf = SM->getCharacterData(LocStart);
2677 const char *endBuf = SM->getCharacterData(LocEnd);
Steve Naroffbaf58c32008-05-31 14:15:04 +00002678
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002679 // If no ivars and no root or if its root, directly or indirectly,
2680 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002681 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2682 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner2c78b872009-04-14 23:22:57 +00002683 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Chris Lattneraadaf782008-01-31 19:51:04 +00002684 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002685 return;
2686 }
2687
2688 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002689 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002690 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002691 Result += CDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002692 if (LangOpts.Microsoft)
2693 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00002694
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002695 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002696 const char *cursor = strchr(startBuf, '{');
2697 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002698 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00002699 // If the buffer contains preprocessor directives, we do more fine-grained
2700 // rewrites. This is intended to fix code that looks like (which occurs in
2701 // NSURL.h, for example):
2702 //
2703 // #ifdef XYZ
2704 // @interface Foo : NSObject
2705 // #else
2706 // @interface FooBar : NSObject
2707 // #endif
2708 // {
2709 // int i;
2710 // }
2711 // @end
2712 //
2713 // This clause is segregated to avoid breaking the common case.
2714 if (BufferContainsPPDirectives(startBuf, cursor)) {
2715 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
2716 CDecl->getClassLoc();
2717 const char *endHeader = SM->getCharacterData(L);
Chris Lattner2c78b872009-04-14 23:22:57 +00002718 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffbaf58c32008-05-31 14:15:04 +00002719
Chris Lattnercafeb352009-02-20 18:18:36 +00002720 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00002721 // advance to the end of the referenced protocols.
2722 while (endHeader < cursor && *endHeader != '>') endHeader++;
2723 endHeader++;
2724 }
2725 // rewrite the original header
2726 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2727 } else {
2728 // rewrite the original header *without* disturbing the '{'
2729 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
2730 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002731 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002732 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002733 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002734 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002735 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00002736 Result += "_IVARS;\n";
Steve Narofffea763e82007-11-14 19:25:57 +00002737
2738 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002739 SourceLocation OnePastCurly =
2740 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2741 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002742 }
2743 cursor++; // past '{'
2744
2745 // Now comment out any visibility specifiers.
2746 while (cursor < endBuf) {
2747 if (*cursor == '@') {
2748 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002749 // Skip whitespace.
2750 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2751 /*scan*/;
2752
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002753 // FIXME: presence of @public, etc. inside comment results in
2754 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002755 if (!strncmp(cursor, "public", strlen("public")) ||
2756 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00002757 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002758 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002759 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002760 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002761 // FIXME: If there are cases where '<' is used in ivar declaration part
2762 // of user code, then scan the ivar list and use needToScanForQualifiers
2763 // for type checking.
2764 else if (*cursor == '<') {
2765 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002766 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002767 cursor = strchr(cursor, '>');
2768 cursor++;
2769 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002770 InsertText(atLoc, " */", 3);
Steve Naroffced80a82008-10-30 12:09:33 +00002771 } else if (*cursor == '^') { // rewrite block specifier.
2772 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2773 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002774 }
Steve Narofffea763e82007-11-14 19:25:57 +00002775 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002776 }
Steve Narofffea763e82007-11-14 19:25:57 +00002777 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002778 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00002779 } else { // we don't have any instance variables - insert super struct.
Chris Lattner2c78b872009-04-14 23:22:57 +00002780 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Narofffea763e82007-11-14 19:25:57 +00002781 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002782 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002783 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002784 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00002785 Result += "_IVARS;\n};\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00002786 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002787 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002788 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002789 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00002790 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002791}
2792
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002793// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002794/// class methods.
Douglas Gregor653f1b12009-04-23 01:02:12 +00002795template<typename MethodIterator>
2796void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
2797 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002798 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002799 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002800 const char *ClassName,
2801 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002802 if (MethodBegin == MethodEnd) return;
2803
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002804 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002805 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002806 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002807 SEL _cmd;
2808 char *method_types;
2809 void *_imp;
2810 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002811 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002812 Result += "\nstruct _objc_method {\n";
2813 Result += "\tSEL _cmd;\n";
2814 Result += "\tchar *method_types;\n";
2815 Result += "\tvoid *_imp;\n";
2816 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002817
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002818 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002819 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002820
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002821 // Build _objc_method_list for class's methods if needed
Steve Naroff946a6932008-03-11 00:12:29 +00002822
2823 /* struct {
2824 struct _objc_method_list *next_method;
2825 int method_count;
2826 struct _objc_method method_list[];
2827 }
2828 */
Douglas Gregor653f1b12009-04-23 01:02:12 +00002829 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroff946a6932008-03-11 00:12:29 +00002830 Result += "\nstatic struct {\n";
2831 Result += "\tstruct _objc_method_list *next_method;\n";
2832 Result += "\tint method_count;\n";
2833 Result += "\tstruct _objc_method method_list[";
Douglas Gregor653f1b12009-04-23 01:02:12 +00002834 Result += utostr(NumMethods);
Steve Naroff946a6932008-03-11 00:12:29 +00002835 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002836 Result += prefix;
2837 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2838 Result += "_METHODS_";
2839 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002840 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002841 Result += IsInstanceMethod ? "inst" : "cls";
2842 Result += "_meth\")))= ";
Douglas Gregor653f1b12009-04-23 01:02:12 +00002843 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002844
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002845 Result += "\t,{{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002846 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002847 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002848 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002849 Result += "\", \"";
2850 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002851 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002852 Result += MethodInternalNames[*MethodBegin];
2853 Result += "}\n";
2854 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2855 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002856 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002857 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002858 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002859 Result += "\", \"";
2860 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002861 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002862 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002863 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002864 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002865 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002866}
2867
Steve Naroff621edce2009-04-29 16:37:50 +00002868/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00002869void RewriteObjC::
Steve Naroff621edce2009-04-29 16:37:50 +00002870RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, const char *prefix,
2871 const char *ClassName, std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002872 static bool objc_protocol_methods = false;
Steve Naroff621edce2009-04-29 16:37:50 +00002873
2874 // Output struct protocol_methods holder of method selector and type.
2875 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
2876 /* struct protocol_methods {
2877 SEL _cmd;
2878 char *method_types;
2879 }
2880 */
2881 Result += "\nstruct _protocol_methods {\n";
2882 Result += "\tstruct objc_selector *_cmd;\n";
2883 Result += "\tchar *method_types;\n";
2884 Result += "};\n";
2885
2886 objc_protocol_methods = true;
2887 }
2888 // Do not synthesize the protocol more than once.
2889 if (ObjCSynthesizedProtocols.count(PDecl))
2890 return;
2891
Douglas Gregor6ab35242009-04-09 21:40:53 +00002892 if (PDecl->instmeth_begin(*Context) != PDecl->instmeth_end(*Context)) {
2893 unsigned NumMethods = std::distance(PDecl->instmeth_begin(*Context),
2894 PDecl->instmeth_end(*Context));
Steve Naroff621edce2009-04-29 16:37:50 +00002895 /* struct _objc_protocol_method_list {
2896 int protocol_method_count;
2897 struct protocol_methods protocols[];
2898 }
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002899 */
Steve Naroff621edce2009-04-29 16:37:50 +00002900 Result += "\nstatic struct {\n";
2901 Result += "\tint protocol_method_count;\n";
2902 Result += "\tstruct _protocol_methods protocol_methods[";
2903 Result += utostr(NumMethods);
2904 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
2905 Result += PDecl->getNameAsString();
2906 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
2907 "{\n\t" + utostr(NumMethods) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002908
Steve Naroff621edce2009-04-29 16:37:50 +00002909 // Output instance methods declared in this protocol.
2910 for (ObjCProtocolDecl::instmeth_iterator
2911 I = PDecl->instmeth_begin(*Context),
2912 E = PDecl->instmeth_end(*Context);
2913 I != E; ++I) {
2914 if (I == PDecl->instmeth_begin(*Context))
2915 Result += "\t ,{{(struct objc_selector *)\"";
2916 else
2917 Result += "\t ,{(struct objc_selector *)\"";
2918 Result += (*I)->getSelector().getAsString().c_str();
2919 std::string MethodTypeString;
2920 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2921 Result += "\", \"";
2922 Result += MethodTypeString;
2923 Result += "\"}\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002924 }
Steve Naroff621edce2009-04-29 16:37:50 +00002925 Result += "\t }\n};\n";
2926 }
2927
2928 // Output class methods declared in this protocol.
2929 unsigned NumMethods = std::distance(PDecl->classmeth_begin(*Context),
2930 PDecl->classmeth_end(*Context));
2931 if (NumMethods > 0) {
2932 /* struct _objc_protocol_method_list {
2933 int protocol_method_count;
2934 struct protocol_methods protocols[];
2935 }
2936 */
2937 Result += "\nstatic struct {\n";
2938 Result += "\tint protocol_method_count;\n";
2939 Result += "\tstruct _protocol_methods protocol_methods[";
2940 Result += utostr(NumMethods);
2941 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
2942 Result += PDecl->getNameAsString();
2943 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2944 "{\n\t";
2945 Result += utostr(NumMethods);
2946 Result += "\n";
2947
2948 // Output instance methods declared in this protocol.
2949 for (ObjCProtocolDecl::classmeth_iterator
2950 I = PDecl->classmeth_begin(*Context),
2951 E = PDecl->classmeth_end(*Context);
2952 I != E; ++I) {
2953 if (I == PDecl->classmeth_begin(*Context))
2954 Result += "\t ,{{(struct objc_selector *)\"";
2955 else
2956 Result += "\t ,{(struct objc_selector *)\"";
2957 Result += (*I)->getSelector().getAsString().c_str();
2958 std::string MethodTypeString;
2959 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2960 Result += "\", \"";
2961 Result += MethodTypeString;
2962 Result += "\"}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002963 }
Steve Naroff621edce2009-04-29 16:37:50 +00002964 Result += "\t }\n};\n";
2965 }
2966
2967 // Output:
2968 /* struct _objc_protocol {
2969 // Objective-C 1.0 extensions
2970 struct _objc_protocol_extension *isa;
2971 char *protocol_name;
2972 struct _objc_protocol **protocol_list;
2973 struct _objc_protocol_method_list *instance_methods;
2974 struct _objc_protocol_method_list *class_methods;
2975 };
2976 */
2977 static bool objc_protocol = false;
2978 if (!objc_protocol) {
2979 Result += "\nstruct _objc_protocol {\n";
2980 Result += "\tstruct _objc_protocol_extension *isa;\n";
2981 Result += "\tchar *protocol_name;\n";
2982 Result += "\tstruct _objc_protocol **protocol_list;\n";
2983 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2984 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002985 Result += "};\n";
2986
Steve Naroff621edce2009-04-29 16:37:50 +00002987 objc_protocol = true;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002988 }
Steve Naroff621edce2009-04-29 16:37:50 +00002989
2990 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2991 Result += PDecl->getNameAsString();
2992 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
2993 "{\n\t0, \"";
2994 Result += PDecl->getNameAsString();
2995 Result += "\", 0, ";
2996 if (PDecl->instmeth_begin(*Context) != PDecl->instmeth_end(*Context)) {
2997 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
2998 Result += PDecl->getNameAsString();
2999 Result += ", ";
3000 }
3001 else
3002 Result += "0, ";
3003 if (PDecl->classmeth_begin(*Context) != PDecl->classmeth_end(*Context)) {
3004 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3005 Result += PDecl->getNameAsString();
3006 Result += "\n";
3007 }
3008 else
3009 Result += "0\n";
3010 Result += "};\n";
3011
3012 // Mark this protocol as having been generated.
3013 if (!ObjCSynthesizedProtocols.insert(PDecl))
3014 assert(false && "protocol already synthesized");
3015
3016}
3017
3018void RewriteObjC::
3019RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
3020 const char *prefix, const char *ClassName,
3021 std::string &Result) {
3022 if (Protocols.empty()) return;
3023
3024 for (unsigned i = 0; i != Protocols.size(); i++)
3025 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3026
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003027 // Output the top lovel protocol meta-data for the class.
3028 /* struct _objc_protocol_list {
3029 struct _objc_protocol_list *next;
3030 int protocol_count;
3031 struct _objc_protocol *class_protocols[];
3032 }
3033 */
3034 Result += "\nstatic struct {\n";
3035 Result += "\tstruct _objc_protocol_list *next;\n";
3036 Result += "\tint protocol_count;\n";
3037 Result += "\tstruct _objc_protocol *class_protocols[";
3038 Result += utostr(Protocols.size());
3039 Result += "];\n} _OBJC_";
3040 Result += prefix;
3041 Result += "_PROTOCOLS_";
3042 Result += ClassName;
3043 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3044 "{\n\t0, ";
3045 Result += utostr(Protocols.size());
3046 Result += "\n";
3047
3048 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003049 Result += Protocols[0]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003050 Result += " \n";
3051
3052 for (unsigned i = 1; i != Protocols.size(); i++) {
3053 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003054 Result += Protocols[i]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003055 Result += "\n";
3056 }
3057 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003058}
3059
Steve Naroff621edce2009-04-29 16:37:50 +00003060
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003061/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003062/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00003063void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003064 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003065 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003066 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003067 ObjCCategoryDecl *CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003068 for (CDecl = ClassDecl->getCategoryList(); CDecl;
3069 CDecl = CDecl->getNextClassCategory())
3070 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3071 break;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003072
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003073 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00003074 FullCategoryName += '_';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003075 FullCategoryName += IDecl->getNameAsString();
Steve Naroff621edce2009-04-29 16:37:50 +00003076
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003077 // Build _objc_method_list for class's instance methods if needed
Douglas Gregor653f1b12009-04-23 01:02:12 +00003078 llvm::SmallVector<ObjCMethodDecl *, 32>
3079 InstanceMethods(IDecl->instmeth_begin(*Context),
3080 IDecl->instmeth_end(*Context));
3081
3082 // If any of our property implementations have associated getters or
3083 // setters, produce metadata for them as well.
3084 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(*Context),
3085 PropEnd = IDecl->propimpl_end(*Context);
3086 Prop != PropEnd; ++Prop) {
3087 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3088 continue;
3089 if (!(*Prop)->getPropertyIvarDecl())
3090 continue;
3091 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3092 if (!PD)
3093 continue;
3094 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3095 InstanceMethods.push_back(Getter);
3096 if (PD->isReadOnly())
3097 continue;
3098 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3099 InstanceMethods.push_back(Setter);
3100 }
3101 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003102 true, "CATEGORY_", FullCategoryName.c_str(),
3103 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003104
3105 // Build _objc_method_list for class's class methods if needed
Douglas Gregor653f1b12009-04-23 01:02:12 +00003106 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(*Context),
3107 IDecl->classmeth_end(*Context),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003108 false, "CATEGORY_", FullCategoryName.c_str(),
3109 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003110
3111 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00003112 // Null CDecl is case of a category implementation with no category interface
3113 if (CDecl)
Steve Naroff621edce2009-04-29 16:37:50 +00003114 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
3115 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003116 /* struct _objc_category {
3117 char *category_name;
3118 char *class_name;
3119 struct _objc_method_list *instance_methods;
3120 struct _objc_method_list *class_methods;
3121 struct _objc_protocol_list *protocols;
3122 // Objective-C 1.0 extensions
3123 uint32_t size; // sizeof (struct _objc_category)
3124 struct _objc_property_list *instance_properties; // category's own
3125 // @property decl.
3126 };
3127 */
3128
3129 static bool objc_category = false;
3130 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003131 Result += "\nstruct _objc_category {\n";
3132 Result += "\tchar *category_name;\n";
3133 Result += "\tchar *class_name;\n";
3134 Result += "\tstruct _objc_method_list *instance_methods;\n";
3135 Result += "\tstruct _objc_method_list *class_methods;\n";
3136 Result += "\tstruct _objc_protocol_list *protocols;\n";
3137 Result += "\tunsigned int size;\n";
3138 Result += "\tstruct _objc_property_list *instance_properties;\n";
3139 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003140 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003141 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003142 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3143 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003144 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003145 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003146 Result += "\"\n\t, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003147 Result += ClassDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003148 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003149
Douglas Gregor653f1b12009-04-23 01:02:12 +00003150 if (IDecl->instmeth_begin(*Context) != IDecl->instmeth_end(*Context)) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003151 Result += "\t, (struct _objc_method_list *)"
3152 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3153 Result += FullCategoryName;
3154 Result += "\n";
3155 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003156 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003157 Result += "\t, 0\n";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003158 if (IDecl->classmeth_begin(*Context) != IDecl->classmeth_end(*Context)) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003159 Result += "\t, (struct _objc_method_list *)"
3160 "&_OBJC_CATEGORY_CLASS_METHODS_";
3161 Result += FullCategoryName;
3162 Result += "\n";
3163 }
3164 else
3165 Result += "\t, 0\n";
3166
Chris Lattnercafeb352009-02-20 18:18:36 +00003167 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003168 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
3169 Result += FullCategoryName;
3170 Result += "\n";
3171 }
3172 else
3173 Result += "\t, 0\n";
3174 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003175}
3176
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003177/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3178/// ivar offset.
Steve Naroffb29b4272008-04-14 22:03:09 +00003179void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003180 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003181 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00003182 if (ivar->isBitField()) {
3183 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3184 // place all bitfields at offset 0.
3185 Result += "0";
3186 } else {
3187 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003188 Result += IDecl->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003189 if (LangOpts.Microsoft)
3190 Result += "_IMPL";
3191 Result += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003192 Result += ivar->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003193 Result += ")";
3194 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003195}
3196
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003197//===----------------------------------------------------------------------===//
3198// Meta Data Emission
3199//===----------------------------------------------------------------------===//
3200
Steve Naroffb29b4272008-04-14 22:03:09 +00003201void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003202 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003203 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003204
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003205 // Explictly declared @interface's are already synthesized.
Steve Naroff33feeb02009-04-20 20:09:33 +00003206 if (CDecl->isImplicitInterfaceDecl()) {
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003207 // FIXME: Implementation of a class with no @interface (legacy) doese not
3208 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003209 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003210 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003211
Chris Lattnerbe6df082007-12-12 07:56:42 +00003212 // Build _objc_ivar_list metadata for classes ivars if needed
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003213 unsigned NumIvars = !IDecl->ivar_empty(*Context)
3214 ? IDecl->ivar_size(*Context)
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003215 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003216 if (NumIvars > 0) {
3217 static bool objc_ivar = false;
3218 if (!objc_ivar) {
3219 /* struct _objc_ivar {
3220 char *ivar_name;
3221 char *ivar_type;
3222 int ivar_offset;
3223 };
3224 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003225 Result += "\nstruct _objc_ivar {\n";
3226 Result += "\tchar *ivar_name;\n";
3227 Result += "\tchar *ivar_type;\n";
3228 Result += "\tint ivar_offset;\n";
3229 Result += "};\n";
3230
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003231 objc_ivar = true;
3232 }
3233
Steve Naroff946a6932008-03-11 00:12:29 +00003234 /* struct {
3235 int ivar_count;
3236 struct _objc_ivar ivar_list[nIvars];
3237 };
3238 */
3239 Result += "\nstatic struct {\n";
3240 Result += "\tint ivar_count;\n";
3241 Result += "\tstruct _objc_ivar ivar_list[";
3242 Result += utostr(NumIvars);
3243 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003244 Result += IDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003245 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003246 "{\n\t";
3247 Result += utostr(NumIvars);
3248 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003249
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003250 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003251 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
3252 if (!IDecl->ivar_empty(*Context)) {
3253 for (ObjCImplementationDecl::ivar_iterator
3254 IV = IDecl->ivar_begin(*Context),
3255 IVEnd = IDecl->ivar_end(*Context);
3256 IV != IVEnd; ++IV)
3257 IVars.push_back(*IV);
3258 IVI = IVars.begin();
3259 IVE = IVars.end();
Chris Lattnerbe6df082007-12-12 07:56:42 +00003260 } else {
3261 IVI = CDecl->ivar_begin();
3262 IVE = CDecl->ivar_end();
3263 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003264 Result += "\t,{{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003265 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003266 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003267 std::string TmpString, StrEncoding;
3268 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3269 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003270 Result += StrEncoding;
3271 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003272 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003273 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003274 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003275 Result += "\t ,{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003276 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003277 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003278 std::string TmpString, StrEncoding;
3279 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3280 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003281 Result += StrEncoding;
3282 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003283 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003284 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003285 }
3286
3287 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003288 }
3289
3290 // Build _objc_method_list for class's instance methods if needed
Douglas Gregor653f1b12009-04-23 01:02:12 +00003291 llvm::SmallVector<ObjCMethodDecl *, 32>
3292 InstanceMethods(IDecl->instmeth_begin(*Context),
3293 IDecl->instmeth_end(*Context));
3294
3295 // If any of our property implementations have associated getters or
3296 // setters, produce metadata for them as well.
3297 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(*Context),
3298 PropEnd = IDecl->propimpl_end(*Context);
3299 Prop != PropEnd; ++Prop) {
3300 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3301 continue;
3302 if (!(*Prop)->getPropertyIvarDecl())
3303 continue;
3304 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3305 if (!PD)
3306 continue;
3307 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3308 InstanceMethods.push_back(Getter);
3309 if (PD->isReadOnly())
3310 continue;
3311 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3312 InstanceMethods.push_back(Setter);
3313 }
3314 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003315 true, "", IDecl->getNameAsCString(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003316
3317 // Build _objc_method_list for class's class methods if needed
Douglas Gregor653f1b12009-04-23 01:02:12 +00003318 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(*Context),
3319 IDecl->classmeth_end(*Context),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003320 false, "", IDecl->getNameAsCString(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003321
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003322 // Protocols referenced in class declaration?
Steve Naroff621edce2009-04-29 16:37:50 +00003323 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
3324 "CLASS", CDecl->getNameAsCString(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003325
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003326 // Declaration of class/meta-class metadata
3327 /* struct _objc_class {
3328 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003329 const char *super_class_name;
3330 char *name;
3331 long version;
3332 long info;
3333 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003334 struct _objc_ivar_list *ivars;
3335 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003336 struct objc_cache *cache;
3337 struct objc_protocol_list *protocols;
3338 const char *ivar_layout;
3339 struct _objc_class_ext *ext;
3340 };
3341 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003342 static bool objc_class = false;
3343 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003344 Result += "\nstruct _objc_class {\n";
3345 Result += "\tstruct _objc_class *isa;\n";
3346 Result += "\tconst char *super_class_name;\n";
3347 Result += "\tchar *name;\n";
3348 Result += "\tlong version;\n";
3349 Result += "\tlong info;\n";
3350 Result += "\tlong instance_size;\n";
3351 Result += "\tstruct _objc_ivar_list *ivars;\n";
3352 Result += "\tstruct _objc_method_list *methods;\n";
3353 Result += "\tstruct objc_cache *cache;\n";
3354 Result += "\tstruct _objc_protocol_list *protocols;\n";
3355 Result += "\tconst char *ivar_layout;\n";
3356 Result += "\tstruct _objc_class_ext *ext;\n";
3357 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003358 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003359 }
3360
3361 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003362 ObjCInterfaceDecl *RootClass = 0;
3363 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003364 while (SuperClass) {
3365 RootClass = SuperClass;
3366 SuperClass = SuperClass->getSuperClass();
3367 }
3368 SuperClass = CDecl->getSuperClass();
3369
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003370 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003371 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003372 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003373 "{\n\t(struct _objc_class *)\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003374 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003375 Result += "\"";
3376
3377 if (SuperClass) {
3378 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003379 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003380 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003381 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003382 Result += "\"";
3383 }
3384 else {
3385 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003386 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003387 Result += "\"";
3388 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003389 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003390 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003391 Result += ", 0,2, sizeof(struct _objc_class), 0";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003392 if (IDecl->classmeth_begin(*Context) != IDecl->classmeth_end(*Context)) {
Steve Naroff23f41272008-03-11 18:14:26 +00003393 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003394 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003395 Result += "\n";
3396 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003397 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003398 Result += ", 0\n";
Chris Lattnercafeb352009-02-20 18:18:36 +00003399 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003400 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003401 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003402 Result += ",0,0\n";
3403 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003404 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003405 Result += "\t,0,0,0,0\n";
3406 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003407
3408 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003409 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003410 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003411 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003412 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003413 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003414 if (SuperClass) {
3415 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003416 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003417 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003418 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003419 Result += "\"";
3420 }
3421 else {
3422 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003423 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003424 Result += "\"";
3425 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003426 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003427 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003428 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003429 Result += ",0";
3430 else {
3431 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003432 Result += ",sizeof(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003433 Result += CDecl->getNameAsString();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003434 if (LangOpts.Microsoft)
3435 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003436 Result += ")";
3437 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003438 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00003439 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003440 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003441 Result += "\n\t";
3442 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003443 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003444 Result += ",0";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003445 if (IDecl->instmeth_begin(*Context) != IDecl->instmeth_end(*Context)) {
Steve Naroff946a6932008-03-11 00:12:29 +00003446 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003447 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003448 Result += ", 0\n\t";
3449 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003450 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003451 Result += ",0,0";
Chris Lattnercafeb352009-02-20 18:18:36 +00003452 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003453 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003454 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003455 Result += ", 0,0\n";
3456 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003457 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003458 Result += ",0,0,0\n";
3459 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003460}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003461
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003462/// RewriteImplementations - This routine rewrites all method implementations
3463/// and emits meta-data.
3464
Steve Narofface66252008-11-13 20:07:04 +00003465void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003466 int ClsDefCount = ClassImplementation.size();
3467 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003468
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003469 // Rewrite implemented methods
3470 for (int i = 0; i < ClsDefCount; i++)
3471 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003472
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003473 for (int i = 0; i < CatDefCount; i++)
3474 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00003475}
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003476
Steve Narofface66252008-11-13 20:07:04 +00003477void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3478 int ClsDefCount = ClassImplementation.size();
3479 int CatDefCount = CategoryImplementation.size();
3480
Steve Naroff5df5b762008-05-07 21:23:49 +00003481 // This is needed for determining instance variable offsets.
Steve Naroffa11440b2008-08-05 18:47:23 +00003482 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003483 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003484 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003485 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003486
3487 // For each implemented category, write out all its meta data.
3488 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003489 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroff621edce2009-04-29 16:37:50 +00003490
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003491 // Write objc_symtab metadata
3492 /*
3493 struct _objc_symtab
3494 {
3495 long sel_ref_cnt;
3496 SEL *refs;
3497 short cls_def_cnt;
3498 short cat_def_cnt;
3499 void *defs[cls_def_cnt + cat_def_cnt];
3500 };
3501 */
3502
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003503 Result += "\nstruct _objc_symtab {\n";
3504 Result += "\tlong sel_ref_cnt;\n";
3505 Result += "\tSEL *refs;\n";
3506 Result += "\tshort cls_def_cnt;\n";
3507 Result += "\tshort cat_def_cnt;\n";
3508 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3509 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003510
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003511 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00003512 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003513 Result += "\t0, 0, " + utostr(ClsDefCount)
3514 + ", " + utostr(CatDefCount) + "\n";
3515 for (int i = 0; i < ClsDefCount; i++) {
3516 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003517 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003518 Result += "\n";
3519 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003520
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003521 for (int i = 0; i < CatDefCount; i++) {
3522 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003523 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003524 Result += "_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003525 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003526 Result += "\n";
3527 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003528
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003529 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003530
3531 // Write objc_module metadata
3532
3533 /*
3534 struct _objc_module {
3535 long version;
3536 long size;
3537 const char *name;
3538 struct _objc_symtab *symtab;
3539 }
3540 */
3541
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003542 Result += "\nstruct _objc_module {\n";
3543 Result += "\tlong version;\n";
3544 Result += "\tlong size;\n";
3545 Result += "\tconst char *name;\n";
3546 Result += "\tstruct _objc_symtab *symtab;\n";
3547 Result += "};\n\n";
3548 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00003549 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003550 Result += "\t" + utostr(OBJC_ABI_VERSION) +
3551 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003552 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003553
3554 if (LangOpts.Microsoft) {
Steve Naroff621edce2009-04-29 16:37:50 +00003555 if (ProtocolExprDecls.size()) {
3556 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
3557 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
3558 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
3559 E = ProtocolExprDecls.end(); I != E; ++I) {
3560 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
3561 Result += (*I)->getNameAsString();
3562 Result += " = &_OBJC_PROTOCOL_";
3563 Result += (*I)->getNameAsString();
3564 Result += ";\n";
3565 }
3566 Result += "#pragma data_seg(pop)\n\n";
3567 }
Steve Naroff4f943c22008-03-10 20:43:59 +00003568 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00003569 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003570 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3571 Result += "&_OBJC_MODULES;\n";
3572 Result += "#pragma data_seg(pop)\n\n";
3573 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003574}
Chris Lattner311ff022007-10-16 22:36:42 +00003575
Steve Naroff54055232008-10-27 17:20:55 +00003576std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3577 const char *funcName,
3578 std::string Tag) {
3579 const FunctionType *AFT = CE->getFunctionType();
3580 QualType RT = AFT->getResultType();
3581 std::string StructRef = "struct " + Tag;
3582 std::string S = "static " + RT.getAsString() + " __" +
3583 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003584
Steve Naroff54055232008-10-27 17:20:55 +00003585 BlockDecl *BD = CE->getBlockDecl();
3586
Douglas Gregor72564e72009-02-26 23:50:07 +00003587 if (isa<FunctionNoProtoType>(AFT)) {
Steve Naroffdf8570d2009-02-02 17:19:26 +00003588 // No user-supplied arguments. Still need to pass in a pointer to the
3589 // block (to reference imported block decl refs).
3590 S += "(" + StructRef + " *__cself)";
Steve Naroff54055232008-10-27 17:20:55 +00003591 } else if (BD->param_empty()) {
3592 S += "(" + StructRef + " *__cself)";
3593 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00003594 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff54055232008-10-27 17:20:55 +00003595 assert(FT && "SynthesizeBlockFunc: No function proto");
3596 S += '(';
3597 // first add the implicit argument.
3598 S += StructRef + " *__cself, ";
3599 std::string ParamStr;
3600 for (BlockDecl::param_iterator AI = BD->param_begin(),
3601 E = BD->param_end(); AI != E; ++AI) {
3602 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003603 ParamStr = (*AI)->getNameAsString();
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00003604 (*AI)->getType().getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00003605 S += ParamStr;
3606 }
3607 if (FT->isVariadic()) {
3608 if (!BD->param_empty()) S += ", ";
3609 S += "...";
3610 }
3611 S += ')';
3612 }
3613 S += " {\n";
3614
3615 // Create local declarations to avoid rewriting all closure decl ref exprs.
3616 // First, emit a declaration for all "by ref" decls.
3617 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3618 E = BlockByRefDecls.end(); I != E; ++I) {
3619 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003620 std::string Name = (*I)->getNameAsString();
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00003621 Context->getPointerType((*I)->getType()).getAsStringInternal(Name,
3622 Context->PrintingPolicy);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003623 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Steve Naroff54055232008-10-27 17:20:55 +00003624 }
3625 // Next, emit a declaration for all "by copy" declarations.
3626 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3627 E = BlockByCopyDecls.end(); I != E; ++I) {
3628 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003629 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003630 // Handle nested closure invocation. For example:
3631 //
3632 // void (^myImportedClosure)(void);
3633 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3634 //
3635 // void (^anotherClosure)(void);
3636 // anotherClosure = ^(void) {
3637 // myImportedClosure(); // import and invoke the closure
3638 // };
3639 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003640 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00003641 S += "struct __block_impl *";
3642 else
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00003643 (*I)->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003644 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff54055232008-10-27 17:20:55 +00003645 }
3646 std::string RewrittenStr = RewrittenBlockExprs[CE];
3647 const char *cstr = RewrittenStr.c_str();
3648 while (*cstr++ != '{') ;
3649 S += cstr;
3650 S += "\n";
3651 return S;
3652}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003653
Steve Naroff54055232008-10-27 17:20:55 +00003654std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3655 const char *funcName,
3656 std::string Tag) {
3657 std::string StructRef = "struct " + Tag;
3658 std::string S = "static void __";
3659
3660 S += funcName;
3661 S += "_block_copy_" + utostr(i);
3662 S += "(" + StructRef;
3663 S += "*dst, " + StructRef;
3664 S += "*src) {";
3665 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3666 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00003667 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003668 S += (*I)->getNameAsString();
Steve Naroff47a24222008-12-11 20:51:38 +00003669 S += ", (void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003670 S += (*I)->getNameAsString();
Steve Naroff5bc60d02008-12-16 15:50:30 +00003671 S += ", 3/*BLOCK_FIELD_IS_OBJECT*/);}";
Steve Naroff54055232008-10-27 17:20:55 +00003672 }
3673 S += "\nstatic void __";
3674 S += funcName;
3675 S += "_block_dispose_" + utostr(i);
3676 S += "(" + StructRef;
3677 S += "*src) {";
3678 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3679 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00003680 S += "_Block_object_dispose((void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003681 S += (*I)->getNameAsString();
Steve Naroff5bc60d02008-12-16 15:50:30 +00003682 S += ", 3/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00003683 }
3684 S += "}\n";
3685 return S;
3686}
3687
3688std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3689 bool hasCopyDisposeHelpers) {
Steve Naroffced80a82008-10-30 12:09:33 +00003690 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00003691 std::string Constructor = " " + Tag;
3692
3693 S += " {\n struct __block_impl impl;\n";
3694
3695 if (hasCopyDisposeHelpers)
3696 S += " void *copy;\n void *dispose;\n";
3697
3698 Constructor += "(void *fp";
3699
3700 if (hasCopyDisposeHelpers)
3701 Constructor += ", void *copyHelp, void *disposeHelp";
3702
3703 if (BlockDeclRefs.size()) {
3704 // Output all "by copy" declarations.
3705 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3706 E = BlockByCopyDecls.end(); I != E; ++I) {
3707 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003708 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003709 std::string ArgName = "_" + FieldName;
3710 // Handle nested closure invocation. For example:
3711 //
3712 // void (^myImportedBlock)(void);
3713 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3714 //
3715 // void (^anotherBlock)(void);
3716 // anotherBlock = ^(void) {
3717 // myImportedBlock(); // import and invoke the closure
3718 // };
3719 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003720 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00003721 S += "struct __block_impl *";
3722 Constructor += ", void *" + ArgName;
3723 } else {
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00003724 (*I)->getType().getAsStringInternal(FieldName, Context->PrintingPolicy);
3725 (*I)->getType().getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00003726 Constructor += ", " + ArgName;
3727 }
3728 S += FieldName + ";\n";
3729 }
3730 // Output all "by ref" declarations.
3731 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3732 E = BlockByRefDecls.end(); I != E; ++I) {
3733 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003734 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003735 std::string ArgName = "_" + FieldName;
3736 // Handle nested closure invocation. For example:
3737 //
3738 // void (^myImportedBlock)(void);
3739 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3740 //
3741 // void (^anotherBlock)(void);
3742 // anotherBlock = ^(void) {
3743 // myImportedBlock(); // import and invoke the closure
3744 // };
3745 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003746 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00003747 S += "struct __block_impl *";
3748 Constructor += ", void *" + ArgName;
3749 } else {
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00003750 Context->getPointerType((*I)->getType()).getAsStringInternal(FieldName,
3751 Context->PrintingPolicy);
3752 Context->getPointerType((*I)->getType()).getAsStringInternal(ArgName,
3753 Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00003754 Constructor += ", " + ArgName;
3755 }
3756 S += FieldName + "; // by ref\n";
3757 }
3758 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00003759 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00003760 if (GlobalVarDecl)
3761 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3762 else
3763 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3764 Constructor += " impl.Size = sizeof(";
Steve Naroff54055232008-10-27 17:20:55 +00003765 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3766
3767 if (hasCopyDisposeHelpers)
3768 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3769
3770 // Initialize all "by copy" arguments.
3771 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3772 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003773 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003774 Constructor += " ";
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003775 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00003776 Constructor += Name + " = (struct __block_impl *)_";
3777 else
3778 Constructor += Name + " = _";
3779 Constructor += Name + ";\n";
3780 }
3781 // Initialize all "by ref" arguments.
3782 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3783 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003784 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003785 Constructor += " ";
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003786 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00003787 Constructor += Name + " = (struct __block_impl *)_";
3788 else
3789 Constructor += Name + " = _";
3790 Constructor += Name + ";\n";
3791 }
3792 } else {
3793 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00003794 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00003795 if (GlobalVarDecl)
3796 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3797 else
3798 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3799 Constructor += " impl.Size = sizeof(";
Steve Naroff54055232008-10-27 17:20:55 +00003800 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3801 if (hasCopyDisposeHelpers)
3802 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3803 }
3804 Constructor += " ";
3805 Constructor += "}\n";
3806 S += Constructor;
3807 S += "};\n";
3808 return S;
3809}
3810
3811void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3812 const char *FunName) {
3813 // Insert closures that were part of the function.
3814 for (unsigned i = 0; i < Blocks.size(); i++) {
3815
3816 CollectBlockDeclRefInfo(Blocks[i]);
3817
3818 std::string Tag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
3819
3820 std::string CI = SynthesizeBlockImpl(Blocks[i], Tag,
3821 ImportedBlockDecls.size() > 0);
3822
3823 InsertText(FunLocStart, CI.c_str(), CI.size());
3824
3825 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, Tag);
3826
3827 InsertText(FunLocStart, CF.c_str(), CF.size());
3828
3829 if (ImportedBlockDecls.size()) {
3830 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, Tag);
3831 InsertText(FunLocStart, HF.c_str(), HF.size());
3832 }
3833
3834 BlockDeclRefs.clear();
3835 BlockByRefDecls.clear();
3836 BlockByCopyDecls.clear();
3837 BlockCallExprs.clear();
3838 ImportedBlockDecls.clear();
3839 }
3840 Blocks.clear();
3841 RewrittenBlockExprs.clear();
3842}
3843
3844void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3845 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner8ec03f52008-11-24 03:54:41 +00003846 const char *FuncName = FD->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003847
3848 SynthesizeBlockLiterals(FunLocStart, FuncName);
3849}
3850
3851void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00003852 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3853 //SourceLocation FunLocStart = MD->getLocStart();
3854 // FIXME: This hack works around a bug in Rewrite.InsertText().
3855 SourceLocation FunLocStart = MD->getLocStart().getFileLocWithOffset(-1);
Chris Lattner077bf5e2008-11-24 03:33:13 +00003856 std::string FuncName = MD->getSelector().getAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003857 // Convert colons to underscores.
3858 std::string::size_type loc = 0;
3859 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3860 FuncName.replace(loc, 1, "_");
3861
3862 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
3863}
3864
3865void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
3866 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3867 CI != E; ++CI)
3868 if (*CI) {
3869 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3870 GetBlockDeclRefExprs(CBE->getBody());
3871 else
3872 GetBlockDeclRefExprs(*CI);
3873 }
3874 // Handle specific things.
3875 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
3876 // FIXME: Handle enums.
3877 if (!isa<FunctionDecl>(CDRE->getDecl()))
3878 BlockDeclRefs.push_back(CDRE);
3879 return;
3880}
3881
3882void RewriteObjC::GetBlockCallExprs(Stmt *S) {
3883 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3884 CI != E; ++CI)
3885 if (*CI) {
3886 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3887 GetBlockCallExprs(CBE->getBody());
3888 else
3889 GetBlockCallExprs(*CI);
3890 }
3891
3892 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
3893 if (CE->getCallee()->getType()->isBlockPointerType()) {
3894 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
3895 }
3896 }
3897 return;
3898}
3899
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003900Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00003901 // Navigate to relevant type information.
3902 const char *closureName = 0;
3903 const BlockPointerType *CPT = 0;
3904
3905 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003906 closureName = DRE->getDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003907 CPT = DRE->getType()->getAsBlockPointerType();
3908 } else if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003909 closureName = CDRE->getDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003910 CPT = CDRE->getType()->getAsBlockPointerType();
3911 } else if (MemberExpr *MExpr = dyn_cast<MemberExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003912 closureName = MExpr->getMemberDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003913 CPT = MExpr->getType()->getAsBlockPointerType();
3914 } else {
3915 assert(1 && "RewriteBlockClass: Bad type");
3916 }
3917 assert(CPT && "RewriteBlockClass: Bad type");
3918 const FunctionType *FT = CPT->getPointeeType()->getAsFunctionType();
3919 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor72564e72009-02-26 23:50:07 +00003920 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff54055232008-10-27 17:20:55 +00003921 // FTP will be null for closures that don't take arguments.
3922
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003923 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
3924 SourceLocation(),
3925 &Context->Idents.get("__block_impl"));
3926 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00003927
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003928 // Generate a funky cast.
3929 llvm::SmallVector<QualType, 8> ArgTypes;
3930
3931 // Push the block argument type.
3932 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00003933 if (FTP) {
Douglas Gregor72564e72009-02-26 23:50:07 +00003934 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003935 E = FTP->arg_type_end(); I && (I != E); ++I) {
3936 QualType t = *I;
3937 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003938 if (isTopLevelBlockPointerType(t)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003939 const BlockPointerType *BPT = t->getAsBlockPointerType();
3940 t = Context->getPointerType(BPT->getPointeeType());
3941 }
3942 ArgTypes.push_back(t);
3943 }
Steve Naroff54055232008-10-27 17:20:55 +00003944 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003945 // Now do the pointer to function cast.
3946 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
3947 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
3948
3949 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Steve Naroff54055232008-10-27 17:20:55 +00003950
Ted Kremenek8189cde2009-02-07 01:47:29 +00003951 CastExpr *BlkCast = new (Context) CStyleCastExpr(PtrBlock, Exp->getCallee(),
3952 PtrBlock, SourceLocation(),
3953 SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003954 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003955 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3956 BlkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003957 //PE->dump();
Steve Naroff54055232008-10-27 17:20:55 +00003958
Douglas Gregor44b43212008-12-11 16:49:14 +00003959 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
3960 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003961 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek8189cde2009-02-07 01:47:29 +00003962 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
3963 FD->getType());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003964
Ted Kremenek8189cde2009-02-07 01:47:29 +00003965 CastExpr *FunkCast = new (Context) CStyleCastExpr(PtrToFuncCastType, ME,
3966 PtrToFuncCastType,
3967 SourceLocation(),
3968 SourceLocation());
3969 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003970
3971 llvm::SmallVector<Expr*, 8> BlkExprs;
3972 // Add the implicit argument.
3973 BlkExprs.push_back(BlkCast);
3974 // Add the user arguments.
Steve Naroff54055232008-10-27 17:20:55 +00003975 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3976 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003977 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00003978 }
Ted Kremenek668bf912009-02-09 20:51:47 +00003979 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
3980 BlkExprs.size(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00003981 Exp->getType(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003982 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00003983}
3984
3985void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003986 Stmt *BlockCall = SynthesizeBlockCall(Exp);
3987 ReplaceStmt(Exp, BlockCall);
Steve Naroff54055232008-10-27 17:20:55 +00003988}
3989
Steve Naroff621edce2009-04-29 16:37:50 +00003990// We need to return the rewritten expression to handle cases where the
3991// BlockDeclRefExpr is embedded in another expression being rewritten.
3992// For example:
3993//
3994// int main() {
3995// __block Foo *f;
3996// __block int i;
3997//
3998// void (^myblock)() = ^() {
3999// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4000// i = 77;
4001// };
4002//}
4003Stmt *RewriteObjC::RewriteBlockDeclRefExpr(BlockDeclRefExpr *BDRE) {
Steve Naroff54055232008-10-27 17:20:55 +00004004 // FIXME: Add more elaborate code generation required by the ABI.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004005 Expr *DerefExpr = new (Context) UnaryOperator(BDRE, UnaryOperator::Deref,
Steve Naroffdf8570d2009-02-02 17:19:26 +00004006 Context->getPointerType(BDRE->getType()),
4007 SourceLocation());
4008 // Need parens to enforce precedence.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004009 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), DerefExpr);
Steve Naroffdf8570d2009-02-02 17:19:26 +00004010 ReplaceStmt(BDRE, PE);
Steve Naroff621edce2009-04-29 16:37:50 +00004011 return PE;
Steve Naroff54055232008-10-27 17:20:55 +00004012}
4013
Steve Naroffb2f9e512008-11-03 23:29:32 +00004014void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4015 SourceLocation LocStart = CE->getLParenLoc();
4016 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00004017
4018 // Need to avoid trying to rewrite synthesized casts.
4019 if (LocStart.isInvalid())
4020 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00004021 // Need to avoid trying to rewrite casts contained in macros.
4022 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4023 return;
Steve Narofffa15fd92008-10-28 20:29:00 +00004024
Steve Naroff54055232008-10-27 17:20:55 +00004025 const char *startBuf = SM->getCharacterData(LocStart);
4026 const char *endBuf = SM->getCharacterData(LocEnd);
4027
4028 // advance the location to startArgList.
4029 const char *argPtr = startBuf;
4030
4031 while (*argPtr++ && (argPtr < endBuf)) {
4032 switch (*argPtr) {
4033 case '^':
4034 // Replace the '^' with '*'.
4035 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
4036 ReplaceText(LocStart, 1, "*", 1);
4037 break;
4038 }
4039 }
4040 return;
4041}
4042
4043void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4044 SourceLocation DeclLoc = FD->getLocation();
4045 unsigned parenCount = 0;
4046
4047 // We have 1 or more arguments that have closure pointers.
4048 const char *startBuf = SM->getCharacterData(DeclLoc);
4049 const char *startArgList = strchr(startBuf, '(');
4050
4051 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4052
4053 parenCount++;
4054 // advance the location to startArgList.
4055 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4056 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4057
4058 const char *argPtr = startArgList;
4059
4060 while (*argPtr++ && parenCount) {
4061 switch (*argPtr) {
4062 case '^':
4063 // Replace the '^' with '*'.
4064 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
4065 ReplaceText(DeclLoc, 1, "*", 1);
4066 break;
4067 case '(':
4068 parenCount++;
4069 break;
4070 case ')':
4071 parenCount--;
4072 break;
4073 }
4074 }
4075 return;
4076}
4077
4078bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004079 const FunctionProtoType *FTP;
Steve Naroff54055232008-10-27 17:20:55 +00004080 const PointerType *PT = QT->getAsPointerType();
4081 if (PT) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004082 FTP = PT->getPointeeType()->getAsFunctionProtoType();
Steve Naroff54055232008-10-27 17:20:55 +00004083 } else {
4084 const BlockPointerType *BPT = QT->getAsBlockPointerType();
4085 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
Douglas Gregor72564e72009-02-26 23:50:07 +00004086 FTP = BPT->getPointeeType()->getAsFunctionProtoType();
Steve Naroff54055232008-10-27 17:20:55 +00004087 }
4088 if (FTP) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004089 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004090 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004091 if (isTopLevelBlockPointerType(*I))
Steve Naroff54055232008-10-27 17:20:55 +00004092 return true;
4093 }
4094 return false;
4095}
4096
Ted Kremenek8189cde2009-02-07 01:47:29 +00004097void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4098 const char *&RParen) {
Steve Naroff54055232008-10-27 17:20:55 +00004099 const char *argPtr = strchr(Name, '(');
4100 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4101
4102 LParen = argPtr; // output the start.
4103 argPtr++; // skip past the left paren.
4104 unsigned parenCount = 1;
4105
4106 while (*argPtr && parenCount) {
4107 switch (*argPtr) {
4108 case '(': parenCount++; break;
4109 case ')': parenCount--; break;
4110 default: break;
4111 }
4112 if (parenCount) argPtr++;
4113 }
4114 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4115 RParen = argPtr; // output the end
4116}
4117
4118void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4119 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4120 RewriteBlockPointerFunctionArgs(FD);
4121 return;
4122 }
4123 // Handle Variables and Typedefs.
4124 SourceLocation DeclLoc = ND->getLocation();
4125 QualType DeclT;
4126 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4127 DeclT = VD->getType();
4128 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4129 DeclT = TDD->getUnderlyingType();
4130 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4131 DeclT = FD->getType();
4132 else
4133 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
4134
4135 const char *startBuf = SM->getCharacterData(DeclLoc);
4136 const char *endBuf = startBuf;
4137 // scan backward (from the decl location) for the end of the previous decl.
4138 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4139 startBuf--;
4140
4141 // *startBuf != '^' if we are dealing with a pointer to function that
4142 // may take block argument types (which will be handled below).
4143 if (*startBuf == '^') {
4144 // Replace the '^' with '*', computing a negative offset.
4145 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
4146 ReplaceText(DeclLoc, 1, "*", 1);
4147 }
4148 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4149 // Replace the '^' with '*' for arguments.
4150 DeclLoc = ND->getLocation();
4151 startBuf = SM->getCharacterData(DeclLoc);
4152 const char *argListBegin, *argListEnd;
4153 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4154 while (argListBegin < argListEnd) {
4155 if (*argListBegin == '^') {
4156 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
4157 ReplaceText(CaretLoc, 1, "*", 1);
4158 }
4159 argListBegin++;
4160 }
4161 }
4162 return;
4163}
4164
4165void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
4166 // Add initializers for any closure decl refs.
4167 GetBlockDeclRefExprs(Exp->getBody());
4168 if (BlockDeclRefs.size()) {
4169 // Unique all "by copy" declarations.
4170 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4171 if (!BlockDeclRefs[i]->isByRef())
4172 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
4173 // Unique all "by ref" declarations.
4174 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4175 if (BlockDeclRefs[i]->isByRef()) {
4176 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
4177 }
4178 // Find any imported blocks...they will need special attention.
4179 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Steve Naroff47a24222008-12-11 20:51:38 +00004180 if (BlockDeclRefs[i]->getType()->isBlockPointerType()) {
Steve Naroff00072682008-11-13 17:40:07 +00004181 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff54055232008-10-27 17:20:55 +00004182 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4183 }
4184 }
4185}
4186
Steve Narofffa15fd92008-10-28 20:29:00 +00004187FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
4188 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor72564e72009-02-26 23:50:07 +00004189 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Steve Narofffa15fd92008-10-28 20:29:00 +00004190 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
Douglas Gregor2224f842009-02-25 16:33:18 +00004191 ID, FType, FunctionDecl::Extern, false,
4192 false);
Steve Narofffa15fd92008-10-28 20:29:00 +00004193}
4194
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004195Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004196 Blocks.push_back(Exp);
4197
4198 CollectBlockDeclRefInfo(Exp);
4199 std::string FuncName;
4200
4201 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00004202 FuncName = CurFunctionDef->getNameAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00004203 else if (CurMethodDef) {
Chris Lattner077bf5e2008-11-24 03:33:13 +00004204 FuncName = CurMethodDef->getSelector().getAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00004205 // Convert colons to underscores.
4206 std::string::size_type loc = 0;
4207 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4208 FuncName.replace(loc, 1, "_");
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004209 } else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004210 FuncName = std::string(GlobalVarDecl->getNameAsString());
Steve Narofffa15fd92008-10-28 20:29:00 +00004211
4212 std::string BlockNumber = utostr(Blocks.size()-1);
4213
4214 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4215 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
4216
4217 // Get a pointer to the function type so we can cast appropriately.
4218 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
4219
4220 FunctionDecl *FD;
4221 Expr *NewRep;
4222
4223 // Simulate a contructor call...
4224 FD = SynthBlockInitFunctionDecl(Tag.c_str());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004225 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004226
4227 llvm::SmallVector<Expr*, 4> InitExprs;
4228
Steve Narofffdc03722008-10-29 21:23:59 +00004229 // Initialize the block function.
Steve Narofffa15fd92008-10-28 20:29:00 +00004230 FD = SynthBlockInitFunctionDecl(Func.c_str());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004231 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
4232 SourceLocation());
4233 CastExpr *castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy, Arg,
4234 Context->VoidPtrTy, SourceLocation(),
4235 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004236 InitExprs.push_back(castExpr);
Steve Narofffa15fd92008-10-28 20:29:00 +00004237
4238 if (ImportedBlockDecls.size()) {
4239 std::string Buf = "__" + FuncName + "_block_copy_" + BlockNumber;
Steve Narofffdc03722008-10-29 21:23:59 +00004240 FD = SynthBlockInitFunctionDecl(Buf.c_str());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004241 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4242 castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy, Arg,
4243 Context->VoidPtrTy, SourceLocation(),
4244 SourceLocation());
Steve Narofffdc03722008-10-29 21:23:59 +00004245 InitExprs.push_back(castExpr);
4246
Steve Narofffa15fd92008-10-28 20:29:00 +00004247 Buf = "__" + FuncName + "_block_dispose_" + BlockNumber;
Steve Narofffdc03722008-10-29 21:23:59 +00004248 FD = SynthBlockInitFunctionDecl(Buf.c_str());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004249 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4250 castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy, Arg,
4251 Context->VoidPtrTy, SourceLocation(),
4252 SourceLocation());
Steve Narofffdc03722008-10-29 21:23:59 +00004253 InitExprs.push_back(castExpr);
Steve Narofffa15fd92008-10-28 20:29:00 +00004254 }
4255 // Add initializers for any closure decl refs.
4256 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00004257 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00004258 // Output all "by copy" declarations.
4259 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4260 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004261 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00004262 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner8ec03f52008-11-24 03:54:41 +00004263 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004264 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004265 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004266 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004267 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4268 Exp = new (Context) CStyleCastExpr(Context->VoidPtrTy, Arg,
4269 Context->VoidPtrTy, SourceLocation(),
4270 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004271 } else {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004272 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004273 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004274 }
Steve Narofffdc03722008-10-29 21:23:59 +00004275 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004276 }
4277 // Output all "by ref" declarations.
4278 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4279 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004280 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004281 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4282 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf,
Steve Narofffdc03722008-10-29 21:23:59 +00004283 Context->getPointerType(Exp->getType()),
4284 SourceLocation());
Steve Naroff707b0fe2008-11-14 21:36:12 +00004285 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004286 }
4287 }
Ted Kremenek668bf912009-02-09 20:51:47 +00004288 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4289 FType, SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004290 NewRep = new (Context) UnaryOperator(NewRep, UnaryOperator::AddrOf,
Steve Narofffa15fd92008-10-28 20:29:00 +00004291 Context->getPointerType(NewRep->getType()),
4292 SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004293 NewRep = new (Context) CStyleCastExpr(FType, NewRep, FType, SourceLocation(),
4294 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004295 BlockDeclRefs.clear();
4296 BlockByRefDecls.clear();
4297 BlockByCopyDecls.clear();
4298 ImportedBlockDecls.clear();
4299 return NewRep;
4300}
4301
4302//===----------------------------------------------------------------------===//
4303// Function Body / Expression rewriting
4304//===----------------------------------------------------------------------===//
4305
Steve Naroffc77a6362008-12-04 16:24:46 +00004306// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
4307// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
4308// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
4309// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
4310// Since the rewriter isn't capable of rewriting rewritten code, it's important
4311// we get this right.
4312void RewriteObjC::CollectPropertySetters(Stmt *S) {
4313 // Perform a bottom up traversal of all children.
4314 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4315 CI != E; ++CI)
4316 if (*CI)
4317 CollectPropertySetters(*CI);
4318
4319 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
4320 if (BinOp->isAssignmentOp()) {
4321 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
4322 PropSetters[PRE] = BinOp;
4323 }
4324 }
4325}
4326
Steve Narofffa15fd92008-10-28 20:29:00 +00004327Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
4328 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4329 isa<DoStmt>(S) || isa<ForStmt>(S))
4330 Stmts.push_back(S);
4331 else if (isa<ObjCForCollectionStmt>(S)) {
4332 Stmts.push_back(S);
4333 ObjCBcLabelNo.push_back(++BcLabelCount);
4334 }
4335
4336 SourceRange OrigStmtRange = S->getSourceRange();
4337
4338 // Perform a bottom up rewrite of all children.
4339 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4340 CI != E; ++CI)
4341 if (*CI) {
4342 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
4343 if (newStmt)
4344 *CI = newStmt;
4345 }
4346
4347 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4348 // Rewrite the block body in place.
4349 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
4350
4351 // Now we snarf the rewritten text and stash it away for later use.
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004352 std::string Str = Rewrite.getRewritenText(BE->getSourceRange());
4353 RewrittenBlockExprs[BE] = Str;
Steve Narofffa15fd92008-10-28 20:29:00 +00004354
4355 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
4356 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004357 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00004358 return blockTranscribed;
4359 }
4360 // Handle specific things.
4361 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4362 return RewriteAtEncode(AtEncode);
4363
4364 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
4365 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
4366
Steve Naroffc77a6362008-12-04 16:24:46 +00004367 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
4368 BinaryOperator *BinOp = PropSetters[PropRefExpr];
4369 if (BinOp) {
4370 // Because the rewriter doesn't allow us to rewrite rewritten code,
4371 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroffb619d952008-12-09 12:56:34 +00004372 DisableReplaceStmt = true;
4373 // Save the source range. Even if we disable the replacement, the
4374 // rewritten node will have been inserted into the tree. If the synthesized
4375 // node is at the 'end', the rewriter will fail. Consider this:
4376 // self.errorHandler = handler ? handler :
4377 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
4378 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroffc77a6362008-12-04 16:24:46 +00004379 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroffb619d952008-12-09 12:56:34 +00004380 DisableReplaceStmt = false;
Steve Naroff4c3580e2008-12-04 23:50:32 +00004381 //
4382 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
4383 // we changed the RHS of BinOp, the rewriter would fail (since it needs
4384 // to see the original expression). Consider this example:
4385 //
4386 // Foo *obj1, *obj2;
4387 //
4388 // obj1.i = [obj2 rrrr];
4389 //
4390 // 'BinOp' for the previous expression looks like:
4391 //
4392 // (BinaryOperator 0x231ccf0 'int' '='
4393 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
4394 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
4395 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
4396 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
4397 //
4398 // 'newStmt' represents the rewritten message expression. For example:
4399 //
4400 // (CallExpr 0x231d300 'id':'struct objc_object *'
4401 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
4402 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
4403 // (CStyleCastExpr 0x231d220 'void *'
4404 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
4405 //
4406 // Note that 'newStmt' is passed to RewritePropertySetter so that it
4407 // can be used as the setter argument. ReplaceStmt() will still 'see'
4408 // the original RHS (since we haven't altered BinOp).
4409 //
4410 // This implies the Rewrite* routines can no longer delete the original
4411 // node. As a result, we now leak the original AST nodes.
4412 //
Steve Naroffb619d952008-12-09 12:56:34 +00004413 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroffc77a6362008-12-04 16:24:46 +00004414 } else {
4415 return RewritePropertyGetter(PropRefExpr);
Steve Naroff15f081d2008-12-03 00:56:33 +00004416 }
4417 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004418 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4419 return RewriteAtSelector(AtSelector);
4420
4421 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4422 return RewriteObjCStringLiteral(AtString);
4423
4424 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00004425#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00004426 // Before we rewrite it, put the original message expression in a comment.
4427 SourceLocation startLoc = MessExpr->getLocStart();
4428 SourceLocation endLoc = MessExpr->getLocEnd();
4429
4430 const char *startBuf = SM->getCharacterData(startLoc);
4431 const char *endBuf = SM->getCharacterData(endLoc);
4432
4433 std::string messString;
4434 messString += "// ";
4435 messString.append(startBuf, endBuf-startBuf+1);
4436 messString += "\n";
4437
4438 // FIXME: Missing definition of
4439 // InsertText(clang::SourceLocation, char const*, unsigned int).
4440 // InsertText(startLoc, messString.c_str(), messString.size());
4441 // Tried this, but it didn't work either...
4442 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00004443#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00004444 return RewriteMessageExpr(MessExpr);
4445 }
4446
4447 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4448 return RewriteObjCTryStmt(StmtTry);
4449
4450 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4451 return RewriteObjCSynchronizedStmt(StmtTry);
4452
4453 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4454 return RewriteObjCThrowStmt(StmtThrow);
4455
4456 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4457 return RewriteObjCProtocolExpr(ProtocolExp);
4458
4459 if (ObjCForCollectionStmt *StmtForCollection =
4460 dyn_cast<ObjCForCollectionStmt>(S))
4461 return RewriteObjCForCollectionStmt(StmtForCollection,
4462 OrigStmtRange.getEnd());
4463 if (BreakStmt *StmtBreakStmt =
4464 dyn_cast<BreakStmt>(S))
4465 return RewriteBreakStmt(StmtBreakStmt);
4466 if (ContinueStmt *StmtContinueStmt =
4467 dyn_cast<ContinueStmt>(S))
4468 return RewriteContinueStmt(StmtContinueStmt);
4469
4470 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
4471 // and cast exprs.
4472 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4473 // FIXME: What we're doing here is modifying the type-specifier that
4474 // precedes the first Decl. In the future the DeclGroup should have
4475 // a separate type-specifier that we can rewrite.
4476 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
4477
4478 // Blocks rewrite rules.
4479 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4480 DI != DE; ++DI) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004481 Decl *SD = *DI;
Steve Narofffa15fd92008-10-28 20:29:00 +00004482 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004483 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004484 RewriteBlockPointerDecl(ND);
4485 else if (ND->getType()->isFunctionPointerType())
4486 CheckFunctionPointerDecl(ND->getType(), ND);
4487 }
4488 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004489 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004490 RewriteBlockPointerDecl(TD);
4491 else if (TD->getUnderlyingType()->isFunctionPointerType())
4492 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4493 }
4494 }
4495 }
4496
4497 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4498 RewriteObjCQualifiedInterfaceTypes(CE);
4499
4500 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4501 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4502 assert(!Stmts.empty() && "Statement stack is empty");
4503 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4504 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
4505 && "Statement stack mismatch");
4506 Stmts.pop_back();
4507 }
4508 // Handle blocks rewriting.
4509 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4510 if (BDRE->isByRef())
Steve Naroff621edce2009-04-29 16:37:50 +00004511 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofffa15fd92008-10-28 20:29:00 +00004512 }
4513 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004514 if (CE->getCallee()->getType()->isBlockPointerType()) {
4515 Stmt *BlockCall = SynthesizeBlockCall(CE);
4516 ReplaceStmt(S, BlockCall);
4517 return BlockCall;
4518 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004519 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00004520 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004521 RewriteCastExpr(CE);
4522 }
4523#if 0
4524 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00004525 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004526 // Get the new text.
4527 std::string SStr;
4528 llvm::raw_string_ostream Buf(SStr);
Eli Friedman3a9eb442009-05-30 05:19:26 +00004529 Replacement->printPretty(Buf, *Context);
Steve Narofffa15fd92008-10-28 20:29:00 +00004530 const std::string &Str = Buf.str();
4531
4532 printf("CAST = %s\n", &Str[0]);
4533 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4534 delete S;
4535 return Replacement;
4536 }
4537#endif
4538 // Return this stmt unmodified.
4539 return S;
4540}
4541
4542/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4543/// main file of the input.
4544void RewriteObjC::HandleDeclInMainFile(Decl *D) {
4545 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffcb735302008-12-17 00:20:22 +00004546 if (FD->isOverloadedOperator())
4547 return;
4548
Steve Narofffa15fd92008-10-28 20:29:00 +00004549 // Since function prototypes don't have ParmDecl's, we check the function
4550 // prototype. This enables us to rewrite function declarations and
4551 // definitions using the same code.
Douglas Gregor72564e72009-02-26 23:50:07 +00004552 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofffa15fd92008-10-28 20:29:00 +00004553
Sebastian Redld3a413d2009-04-26 20:35:05 +00004554 // FIXME: If this should support Obj-C++, support CXXTryStmt
4555 if (CompoundStmt *Body = FD->getCompoundBody(*Context)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004556 CurFunctionDef = FD;
Steve Naroffc77a6362008-12-04 16:24:46 +00004557 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00004558 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00004559 Body =
4560 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4561 FD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00004562 CurrentBody = 0;
4563 if (PropParentMap) {
4564 delete PropParentMap;
4565 PropParentMap = 0;
4566 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004567 // This synthesizes and inserts the block "impl" struct, invoke function,
4568 // and any copy/dispose helper functions.
4569 InsertBlockLiteralsWithinFunction(FD);
4570 CurFunctionDef = 0;
4571 }
4572 return;
4573 }
4574 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Ted Kremenekeaab2062009-03-12 18:33:24 +00004575 if (CompoundStmt *Body = MD->getBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004576 CurMethodDef = MD;
Steve Naroffc77a6362008-12-04 16:24:46 +00004577 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00004578 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00004579 Body =
4580 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4581 MD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00004582 CurrentBody = 0;
4583 if (PropParentMap) {
4584 delete PropParentMap;
4585 PropParentMap = 0;
4586 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004587 InsertBlockLiteralsWithinMethod(MD);
4588 CurMethodDef = 0;
4589 }
4590 }
4591 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
4592 ClassImplementation.push_back(CI);
4593 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
4594 CategoryImplementation.push_back(CI);
4595 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
4596 RewriteForwardClassDecl(CD);
4597 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4598 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004599 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004600 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004601 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004602 CheckFunctionPointerDecl(VD->getType(), VD);
4603 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00004604 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004605 RewriteCastExpr(CE);
4606 }
4607 }
4608 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004609 if (VD->getInit()) {
4610 GlobalVarDecl = VD;
Steve Naroffc77a6362008-12-04 16:24:46 +00004611 CollectPropertySetters(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00004612 CurrentBody = VD->getInit();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004613 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00004614 CurrentBody = 0;
4615 if (PropParentMap) {
4616 delete PropParentMap;
4617 PropParentMap = 0;
4618 }
Douglas Gregor2e1cd422008-11-17 14:58:09 +00004619 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00004620 VD->getNameAsCString());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004621 GlobalVarDecl = 0;
4622
4623 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00004624 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004625 RewriteCastExpr(CE);
4626 }
4627 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004628 return;
4629 }
4630 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004631 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004632 RewriteBlockPointerDecl(TD);
4633 else if (TD->getUnderlyingType()->isFunctionPointerType())
4634 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4635 return;
4636 }
4637 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
4638 if (RD->isDefinition()) {
Douglas Gregor6ab35242009-04-09 21:40:53 +00004639 for (RecordDecl::field_iterator i = RD->field_begin(*Context),
4640 e = RD->field_end(*Context); i != e; ++i) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004641 FieldDecl *FD = *i;
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004642 if (isTopLevelBlockPointerType(FD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004643 RewriteBlockPointerDecl(FD);
4644 }
4645 }
4646 return;
4647 }
4648 // Nothing yet.
4649}
4650
Chris Lattnerdacbc5d2009-03-28 04:11:33 +00004651void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004652 // Get the top-level buffer that this corresponds to.
4653
4654 // Rewrite tabs if we care.
4655 //RewriteTabs();
4656
4657 if (Diags.hasErrorOccurred())
4658 return;
Steve Narofffa15fd92008-10-28 20:29:00 +00004659
4660 RewriteInclude();
4661
Steve Naroff621edce2009-04-29 16:37:50 +00004662 // Here's a great place to add any extra declarations that may be needed.
4663 // Write out meta data for each @protocol(<expr>).
4664 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
4665 E = ProtocolExprDecls.end(); I != E; ++I)
4666 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
4667
Chris Lattner2b2453a2009-01-17 06:22:33 +00004668 InsertText(SM->getLocForStartOfFile(MainFileID),
Steve Narofffa15fd92008-10-28 20:29:00 +00004669 Preamble.c_str(), Preamble.size(), false);
Steve Naroff0aab7962008-11-14 14:10:01 +00004670 if (ClassImplementation.size() || CategoryImplementation.size())
4671 RewriteImplementations();
Steve Naroff621edce2009-04-29 16:37:50 +00004672
Steve Narofffa15fd92008-10-28 20:29:00 +00004673 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
4674 // we are done.
4675 if (const RewriteBuffer *RewriteBuf =
4676 Rewrite.getRewriteBufferFor(MainFileID)) {
4677 //printf("Changed:\n");
4678 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4679 } else {
4680 fprintf(stderr, "No changes\n");
4681 }
Steve Narofface66252008-11-13 20:07:04 +00004682
Steve Naroff621edce2009-04-29 16:37:50 +00004683 if (ClassImplementation.size() || CategoryImplementation.size() ||
4684 ProtocolExprDecls.size()) {
Steve Naroff0aab7962008-11-14 14:10:01 +00004685 // Rewrite Objective-c meta data*
4686 std::string ResultStr;
4687 SynthesizeMetaDataIntoBuffer(ResultStr);
4688 // Emit metadata.
4689 *OutFile << ResultStr;
4690 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004691 OutFile->flush();
4692}
4693