blob: 0e9eb90da7ba6cf126cb1739e92f33704f8c4f19 [file] [log] [blame]
Steve Naroffb29b4272008-04-14 22:03:09 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
Chris Lattner77cd2a02007-10-11 00:43:27 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner77cd2a02007-10-11 00:43:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
14#include "ASTConsumers.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Ted Kremeneke3a61982008-05-31 20:11:04 +000018#include "clang/AST/TranslationUnit.h"
Steve Naroff8599e7a2008-12-08 16:43:47 +000019#include "clang/AST/ParentMap.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000020#include "clang/Basic/SourceManager.h"
Steve Naroffebf2b562007-10-23 23:50:29 +000021#include "clang/Basic/IdentifierTable.h"
Chris Lattner07506182007-11-30 22:53:43 +000022#include "clang/Basic/Diagnostic.h"
Chris Lattner26de4652007-12-02 01:13:47 +000023#include "clang/Lex/Lexer.h"
Chris Lattner158ecb92007-10-25 17:07:24 +000024#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000025#include "llvm/ADT/SmallPtrSet.h"
Ted Kremeneka95d3752008-09-13 05:16:45 +000026#include "llvm/ADT/OwningPtr.h"
Chris Lattner26de4652007-12-02 01:13:47 +000027#include "llvm/Support/MemoryBuffer.h"
Steve Naroff0113c9d2008-01-28 21:34:52 +000028#include "llvm/Support/CommandLine.h"
Dan Gohman63e2dcc2008-05-21 20:19:16 +000029#include "llvm/Support/Streams.h"
Ted Kremeneka95d3752008-09-13 05:16:45 +000030#include "llvm/Support/raw_ostream.h"
Chris Lattnerc68ab772008-03-22 00:08:40 +000031#include "llvm/System/Path.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000032using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000033using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000034
Steve Naroff0113c9d2008-01-28 21:34:52 +000035static llvm::cl::opt<bool>
36SilenceRewriteMacroWarning("Wno-rewrite-macros", llvm::cl::init(false),
37 llvm::cl::desc("Silence ObjC rewriting warnings"));
38
Chris Lattner77cd2a02007-10-11 00:43:27 +000039namespace {
Steve Naroffb29b4272008-04-14 22:03:09 +000040 class RewriteObjC : public ASTConsumer {
Chris Lattner2c64b7b2007-10-16 21:07:07 +000041 Rewriter Rewrite;
Chris Lattnere365c502007-11-30 22:25:36 +000042 Diagnostic &Diags;
Steve Naroff4f943c22008-03-10 20:43:59 +000043 const LangOptions &LangOpts;
Steve Narofff69cc5d2008-01-30 19:17:43 +000044 unsigned RewriteFailedDiag;
Steve Naroff8c565152008-12-05 17:03:39 +000045 unsigned TryFinallyContainsReturnDiag;
46
Chris Lattner01c57482007-10-17 22:35:30 +000047 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000048 SourceManager *SM;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000049 TranslationUnitDecl *TUDecl;
Chris Lattner2b2453a2009-01-17 06:22:33 +000050 FileID MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000051 const char *MainFileStart, *MainFileEnd;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000052 SourceLocation LastIncLoc;
Steve Naroffba92b2e2008-03-27 22:29:16 +000053
Ted Kremeneka526c5c2008-01-07 19:49:32 +000054 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
55 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
56 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Narofffbfe8252008-05-06 18:26:51 +000057 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000058 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
59 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000060 llvm::SmallVector<Stmt *, 32> Stmts;
61 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroffebf2b562007-10-23 23:50:29 +000062
Steve Naroffd82a9ab2008-03-15 00:55:56 +000063 unsigned NumObjCStringLiterals;
64
Steve Naroffebf2b562007-10-23 23:50:29 +000065 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000066 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000067 FunctionDecl *MsgSendStretFunctionDecl;
68 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000069 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000070 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000071 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000072 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000073 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +000074 FunctionDecl *GetProtocolFunctionDecl;
Steve Naroffc0a123c2008-03-11 17:37:02 +000075 FunctionDecl *SuperContructorFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000076
Steve Naroffbeaf2992007-11-03 11:27:19 +000077 // ObjC string constant support.
Steve Naroff248a7532008-04-15 22:42:06 +000078 VarDecl *ConstantStringClassReference;
Steve Naroffbeaf2992007-11-03 11:27:19 +000079 RecordDecl *NSStringRecord;
Steve Naroffab972d32007-11-04 22:37:50 +000080
Fariborz Jahanianb586cce2008-01-16 00:09:11 +000081 // ObjC foreach break/continue generation support.
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000082 int BcLabelCount;
83
Steve Naroff874e2322007-11-15 10:28:18 +000084 // Needed for super.
Steve Naroff54055232008-10-27 17:20:55 +000085 ObjCMethodDecl *CurMethodDef;
Steve Naroff874e2322007-11-15 10:28:18 +000086 RecordDecl *SuperStructDecl;
Steve Naroffd82a9ab2008-03-15 00:55:56 +000087 RecordDecl *ConstantStringDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000088
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +000089 // Needed for header files being rewritten
90 bool IsHeader;
91
Steve Naroffa7b402d2008-03-28 22:26:09 +000092 std::string InFileName;
93 std::string OutFileName;
94
Steve Naroffba92b2e2008-03-27 22:29:16 +000095 std::string Preamble;
Steve Naroff54055232008-10-27 17:20:55 +000096
97 // Block expressions.
98 llvm::SmallVector<BlockExpr *, 32> Blocks;
99 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
100 llvm::DenseMap<BlockDeclRefExpr *, CallExpr *> BlockCallExprs;
Steve Naroffba92b2e2008-03-27 22:29:16 +0000101
Steve Naroff54055232008-10-27 17:20:55 +0000102 // Block related declarations.
103 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDecls;
104 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDecls;
105 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
106
107 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
108
Steve Naroffc77a6362008-12-04 16:24:46 +0000109 // This maps a property to it's assignment statement.
110 llvm::DenseMap<ObjCPropertyRefExpr *, BinaryOperator *> PropSetters;
Steve Naroff8599e7a2008-12-08 16:43:47 +0000111 // This maps a property to it's synthesied message expression.
112 // This allows us to rewrite chained getters (e.g. o.a.b.c).
113 llvm::DenseMap<ObjCPropertyRefExpr *, Stmt *> PropGetters;
114
Steve Naroff4c3580e2008-12-04 23:50:32 +0000115 // This maps an original source AST to it's rewritten form. This allows
116 // us to avoid rewriting the same node twice (which is very uncommon).
117 // This is needed to support some of the exotic property rewriting.
118 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Naroff15f081d2008-12-03 00:56:33 +0000119
Steve Naroff54055232008-10-27 17:20:55 +0000120 FunctionDecl *CurFunctionDef;
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000121 VarDecl *GlobalVarDecl;
122
Steve Naroffb619d952008-12-09 12:56:34 +0000123 bool DisableReplaceStmt;
124
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000125 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +0000126 public:
Ted Kremeneke3a61982008-05-31 20:11:04 +0000127 virtual void Initialize(ASTContext &context);
128
129 virtual void InitializeTU(TranslationUnit &TU) {
130 TU.SetOwnsDecls(false);
131 Initialize(TU.getContext());
132 }
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000133
Chris Lattner8a12c272007-10-11 18:38:32 +0000134
Chris Lattnerf04da132007-10-24 17:06:59 +0000135 // Top Level Driver code.
136 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000137 void HandleDeclInMainFile(Decl *D);
Steve Naroffb29b4272008-04-14 22:03:09 +0000138 RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000139 Diagnostic &D, const LangOptions &LOpts);
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000140
141 ~RewriteObjC() {}
142
143 virtual void HandleTranslationUnit(TranslationUnit& TU);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000144
145 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000146 Stmt *ReplacingStmt = ReplacedNodes[Old];
147
148 if (ReplacingStmt)
149 return; // We can't rewrite the same node twice.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000150
Steve Naroffb619d952008-12-09 12:56:34 +0000151 if (DisableReplaceStmt)
152 return; // Used when rewriting the assignment of a property setter.
153
Steve Naroff4c3580e2008-12-04 23:50:32 +0000154 // If replacement succeeded or warning disabled return with no warning.
155 if (!Rewrite.ReplaceStmt(Old, New)) {
156 ReplacedNodes[Old] = New;
157 return;
158 }
159 if (SilenceRewriteMacroWarning)
160 return;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000161 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
162 << Old->getSourceRange();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000163 }
Steve Naroffb619d952008-12-09 12:56:34 +0000164
165 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
166 // Measaure the old text.
167 int Size = Rewrite.getRangeSize(SrcRange);
168 if (Size == -1) {
169 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
170 << Old->getSourceRange();
171 return;
172 }
173 // Get the new text.
174 std::string SStr;
175 llvm::raw_string_ostream S(SStr);
176 New->printPretty(S);
177 const std::string &Str = S.str();
178
179 // If replacement succeeded or warning disabled return with no warning.
180 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, &Str[0], Str.size())) {
181 ReplacedNodes[Old] = New;
182 return;
183 }
184 if (SilenceRewriteMacroWarning)
185 return;
186 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
187 << Old->getSourceRange();
188 }
189
Steve Naroffba92b2e2008-03-27 22:29:16 +0000190 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
191 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000192 // If insertion succeeded or warning disabled return with no warning.
Steve Naroffba92b2e2008-03-27 22:29:16 +0000193 if (!Rewrite.InsertText(Loc, StrData, StrLen, InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000194 SilenceRewriteMacroWarning)
195 return;
196
197 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
198 }
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000199
Chris Lattneraadaf782008-01-31 19:51:04 +0000200 void RemoveText(SourceLocation Loc, unsigned StrLen) {
201 // If removal succeeded or warning disabled return with no warning.
202 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
203 return;
204
205 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
206 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000207
Chris Lattneraadaf782008-01-31 19:51:04 +0000208 void ReplaceText(SourceLocation Start, unsigned OrigLength,
209 const char *NewStr, unsigned NewLength) {
210 // If removal succeeded or warning disabled return with no warning.
211 if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength) ||
212 SilenceRewriteMacroWarning)
213 return;
214
215 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
216 }
217
Chris Lattnerf04da132007-10-24 17:06:59 +0000218 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000219 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000220 void RewriteInclude();
Chris Lattnerf04da132007-10-24 17:06:59 +0000221 void RewriteTabs();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000222 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffa0876e82008-12-02 17:36:43 +0000223 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
224 ObjCImplementationDecl *IMD,
225 ObjCCategoryImplDecl *CID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000226 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000227 void RewriteImplementationDecl(Decl *Dcl);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000228 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
229 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
230 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
231 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
232 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff6327e0d2009-01-11 01:06:09 +0000233 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff09b266e2007-10-30 23:14:51 +0000234 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000235 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroff4f95b752008-07-29 18:15:38 +0000236 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffd5255f52007-11-01 13:24:47 +0000237 bool needToScanForQualifiers(QualType T);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000238 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000239 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000240 QualType getConstantStringStructType();
Steve Naroffbaf58c32008-05-31 14:15:04 +0000241 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Chris Lattner311ff022007-10-16 22:36:42 +0000242
Chris Lattnerf04da132007-10-24 17:06:59 +0000243 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000244 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroffc77a6362008-12-04 16:24:46 +0000245 void CollectPropertySetters(Stmt *S);
246
Steve Naroff8599e7a2008-12-08 16:43:47 +0000247 Stmt *CurrentBody;
248 ParentMap *PropParentMap; // created lazily.
249
Chris Lattnere64b7772007-10-24 16:57:36 +0000250 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000251 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart);
Steve Naroffc77a6362008-12-04 16:24:46 +0000252 Stmt *RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr);
Steve Naroffb619d952008-12-09 12:56:34 +0000253 Stmt *RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
254 SourceRange SrcRange);
Steve Naroffb42f8412007-11-05 14:50:49 +0000255 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000256 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000257 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000258 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroff8c565152008-12-05 17:03:39 +0000259 void WarnAboutReturnGotoContinueOrBreakStmts(Stmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000260 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000261 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000262 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
263 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
264 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000265 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
266 SourceLocation OrigEnd);
Steve Naroff934f2762007-10-24 22:48:43 +0000267 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
268 Expr **args, unsigned nargs);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000269 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000270 Stmt *RewriteBreakStmt(BreakStmt *S);
271 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000272 void SynthCountByEnumWithState(std::string &buf);
273
Steve Naroff09b266e2007-10-30 23:14:51 +0000274 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000275 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000276 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000277 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000278 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000279 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000280 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000281 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000282 void SynthGetProtocolFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000283 void SynthSuperContructorFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000284
Chris Lattnerf04da132007-10-24 17:06:59 +0000285 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000286 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000287 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000288
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000289 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000290 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000291
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000292 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
293 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000294 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000295 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000296 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000297 const char *ClassName,
298 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000299
Chris Lattner780f3292008-07-21 21:32:27 +0000300 void RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl>
301 &Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000302 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000303 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.
314 void RewriteBlocksInFunctionTypeProto(QualType funcType, NamedDecl *D);
315 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);
323 void RewriteBlockDeclRefExpr(BlockDeclRefExpr *VD);
324 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);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000371 };
372}
373
Steve Naroff54055232008-10-27 17:20:55 +0000374void RewriteObjC::RewriteBlocksInFunctionTypeProto(QualType funcType,
375 NamedDecl *D) {
376 if (FunctionTypeProto *fproto = dyn_cast<FunctionTypeProto>(funcType)) {
377 for (FunctionTypeProto::arg_type_iterator I = fproto->arg_type_begin(),
378 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000379 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff54055232008-10-27 17:20:55 +0000380 // All the args are checked/rewritten. Don't call twice!
381 RewriteBlockPointerDecl(D);
382 break;
383 }
384 }
385}
386
387void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
388 const PointerType *PT = funcType->getAsPointerType();
389 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
390 RewriteBlocksInFunctionTypeProto(PT->getPointeeType(), ND);
391}
392
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000393static bool IsHeaderFile(const std::string &Filename) {
394 std::string::size_type DotPos = Filename.rfind('.');
395
396 if (DotPos == std::string::npos) {
397 // no file extension
398 return false;
399 }
400
401 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
402 // C header: .h
403 // C++ header: .hh or .H;
404 return Ext == "h" || Ext == "hh" || Ext == "H";
405}
406
Steve Naroffb29b4272008-04-14 22:03:09 +0000407RewriteObjC::RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000408 Diagnostic &D, const LangOptions &LOpts)
409 : Diags(D), LangOpts(LOpts) {
410 IsHeader = IsHeaderFile(inFile);
411 InFileName = inFile;
412 OutFileName = outFile;
413 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
414 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff8c565152008-12-05 17:03:39 +0000415 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000416 "rewriter doesn't support user-specified control flow semantics "
417 "for @try/@finally (code may not execute properly)");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000418}
419
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000420ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
Chris Lattnerc68ab772008-03-22 00:08:40 +0000421 const std::string& OutFile,
Steve Naroff4f943c22008-03-10 20:43:59 +0000422 Diagnostic &Diags,
423 const LangOptions &LOpts) {
Steve Naroffb29b4272008-04-14 22:03:09 +0000424 return new RewriteObjC(InFile, OutFile, Diags, LOpts);
Chris Lattnere365c502007-11-30 22:25:36 +0000425}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000426
Steve Naroffb29b4272008-04-14 22:03:09 +0000427void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000428 Context = &context;
429 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000430 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000431 MsgSendFunctionDecl = 0;
432 MsgSendSuperFunctionDecl = 0;
433 MsgSendStretFunctionDecl = 0;
434 MsgSendSuperStretFunctionDecl = 0;
435 MsgSendFpretFunctionDecl = 0;
436 GetClassFunctionDecl = 0;
437 GetMetaClassFunctionDecl = 0;
438 SelGetUidFunctionDecl = 0;
439 CFStringFunctionDecl = 0;
440 GetProtocolFunctionDecl = 0;
441 ConstantStringClassReference = 0;
442 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000443 CurMethodDef = 0;
444 CurFunctionDef = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000445 GlobalVarDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000446 SuperStructDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000447 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000448 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000449 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000450 NumObjCStringLiterals = 0;
Steve Naroff68272b82008-12-08 20:01:41 +0000451 PropParentMap = 0;
452 CurrentBody = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000453 DisableReplaceStmt = false;
454
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000455 // Get the ID and start/end of the main file.
456 MainFileID = SM->getMainFileID();
457 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
458 MainFileStart = MainBuf->getBufferStart();
459 MainFileEnd = MainBuf->getBufferEnd();
Steve Naroffba92b2e2008-03-27 22:29:16 +0000460
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000461 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000462
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000463 // declaring objc_selector outside the parameter list removes a silly
464 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000465 if (IsHeader)
Steve Naroff62c26322009-02-03 20:39:18 +0000466 Preamble = "#pragma once\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000467 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff46a98a72008-12-23 20:11:22 +0000468 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000469 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000470 if (LangOpts.Microsoft) {
471 // Add a constructor for creating temporary objects.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000472 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
473 ": ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000474 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000475 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000476 Preamble += "};\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000477 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
478 Preamble += "typedef struct objc_object Protocol;\n";
479 Preamble += "#define _REWRITER_typedef_Protocol\n";
480 Preamble += "#endif\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000481 if (LangOpts.Microsoft) {
482 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
483 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
484 } else
485 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
486 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000487 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000488 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000489 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000490 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000491 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000492 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000493 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000494 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000495 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000496 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000497 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000498 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000499 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000500 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
501 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
502 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
503 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
504 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000505 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000506 // @synchronized hooks.
Steve Naroff4ebd7162008-12-08 17:30:33 +0000507 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
508 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
509 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000510 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
511 Preamble += "struct __objcFastEnumerationState {\n\t";
512 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000513 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000514 Preamble += "unsigned long *mutationsPtr;\n\t";
515 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000516 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000517 Preamble += "#define __FASTENUMERATIONSTATE\n";
518 Preamble += "#endif\n";
519 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
520 Preamble += "struct __NSConstantStringImpl {\n";
521 Preamble += " int *isa;\n";
522 Preamble += " int flags;\n";
523 Preamble += " char *str;\n";
524 Preamble += " long length;\n";
525 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000526 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
527 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
528 Preamble += "#else\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000529 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000530 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000531 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
532 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000533 // Blocks preamble.
534 Preamble += "#ifndef BLOCK_IMPL\n";
535 Preamble += "#define BLOCK_IMPL\n";
536 Preamble += "struct __block_impl {\n";
537 Preamble += " void *isa;\n";
538 Preamble += " int Flags;\n";
539 Preamble += " int Size;\n";
540 Preamble += " void *FuncPtr;\n";
541 Preamble += "};\n";
Steve Naroff5bc60d02008-12-16 15:50:30 +0000542 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
543 Preamble += "__OBJC_RW_STATICIMPORT void _Block_object_assign(void *, const void *, const int);\n";
544 Preamble += "__OBJC_RW_STATICIMPORT void _Block_object_dispose(const void *, const int);\n";
545 Preamble += "__OBJC_RW_STATICIMPORT void *_NSConcreteGlobalBlock[32];\n";
546 Preamble += "__OBJC_RW_STATICIMPORT void *_NSConcreteStackBlock[32];\n";
Steve Naroff54055232008-10-27 17:20:55 +0000547 Preamble += "#endif\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000548 if (LangOpts.Microsoft) {
Steve Naroff4ebd7162008-12-08 17:30:33 +0000549 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
550 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000551 Preamble += "#define __attribute__(X)\n";
552 }
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000553}
554
555
Chris Lattnerf04da132007-10-24 17:06:59 +0000556//===----------------------------------------------------------------------===//
557// Top Level Driver Code
558//===----------------------------------------------------------------------===//
559
Steve Naroffb29b4272008-04-14 22:03:09 +0000560void RewriteObjC::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000561 // Two cases: either the decl could be in the main file, or it could be in a
562 // #included file. If the former, rewrite it now. If the later, check to see
563 // if we rewrote the #include/#import.
564 SourceLocation Loc = D->getLocation();
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000565 Loc = SM->getInstantiationLoc(Loc);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000566
567 // If this is for a builtin, ignore it.
568 if (Loc.isInvalid()) return;
569
Steve Naroffebf2b562007-10-23 23:50:29 +0000570 // Look for built-in declarations that we need to refer during the rewrite.
571 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000572 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000573 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000574 // declared in <Foundation/NSString.h>
Chris Lattner8ec03f52008-11-24 03:54:41 +0000575 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000576 ConstantStringClassReference = FVD;
577 return;
578 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000579 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000580 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000581 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000582 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000583 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000584 RewriteProtocolDecl(PD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000585 } else if (ObjCForwardProtocolDecl *FP =
586 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000587 RewriteForwardProtocolDecl(FP);
Douglas Gregord0434102009-01-09 00:49:46 +0000588 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
589 // Recurse into linkage specifications
590 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
591 DIEnd = LSD->decls_end();
592 DI != DIEnd; ++DI)
593 HandleTopLevelDecl(*DI);
Steve Naroffebf2b562007-10-23 23:50:29 +0000594 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000595 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000596 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000597 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000598}
599
Chris Lattnerf04da132007-10-24 17:06:59 +0000600//===----------------------------------------------------------------------===//
601// Syntactic (non-AST) Rewriting Code
602//===----------------------------------------------------------------------===//
603
Steve Naroffb29b4272008-04-14 22:03:09 +0000604void RewriteObjC::RewriteInclude() {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000605 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000606 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
607 const char *MainBufStart = MainBuf.first;
608 const char *MainBufEnd = MainBuf.second;
609 size_t ImportLen = strlen("import");
610 size_t IncludeLen = strlen("include");
611
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000612 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000613 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
614 if (*BufPtr == '#') {
615 if (++BufPtr == MainBufEnd)
616 return;
617 while (*BufPtr == ' ' || *BufPtr == '\t')
618 if (++BufPtr == MainBufEnd)
619 return;
620 if (!strncmp(BufPtr, "import", ImportLen)) {
621 // replace import with include
622 SourceLocation ImportLoc =
623 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattneraadaf782008-01-31 19:51:04 +0000624 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000625 BufPtr += ImportLen;
626 }
627 }
628 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000629}
630
Steve Naroffb29b4272008-04-14 22:03:09 +0000631void RewriteObjC::RewriteTabs() {
Chris Lattnerf04da132007-10-24 17:06:59 +0000632 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
633 const char *MainBufStart = MainBuf.first;
634 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000635
Chris Lattnerf04da132007-10-24 17:06:59 +0000636 // Loop over the whole file, looking for tabs.
637 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
638 if (*BufPtr != '\t')
639 continue;
640
641 // Okay, we found a tab. This tab will turn into at least one character,
642 // but it depends on which 'virtual column' it is in. Compute that now.
643 unsigned VCol = 0;
644 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
645 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
646 ++VCol;
647
648 // Okay, now that we know the virtual column, we know how many spaces to
649 // insert. We assume 8-character tab-stops.
650 unsigned Spaces = 8-(VCol & 7);
651
652 // Get the location of the tab.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000653 SourceLocation TabLoc = SM->getLocForStartOfFile(MainFileID);
654 TabLoc = TabLoc.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattnerf04da132007-10-24 17:06:59 +0000655
656 // Rewrite the single tab character into a sequence of spaces.
Chris Lattneraadaf782008-01-31 19:51:04 +0000657 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerf04da132007-10-24 17:06:59 +0000658 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000659}
660
Steve Naroffeb0646c2008-12-02 15:48:25 +0000661static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
662 ObjCIvarDecl *OID) {
663 std::string S;
664 S = "((struct ";
665 S += ClassDecl->getIdentifier()->getName();
666 S += "_IMPL *)self)->";
667 S += OID->getNameAsCString();
668 return S;
669}
670
Steve Naroffa0876e82008-12-02 17:36:43 +0000671void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
672 ObjCImplementationDecl *IMD,
673 ObjCCategoryImplDecl *CID) {
Steve Naroffd40910b2008-12-01 20:33:01 +0000674 SourceLocation startLoc = PID->getLocStart();
675 InsertText(startLoc, "// ", 3);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000676 const char *startBuf = SM->getCharacterData(startLoc);
677 assert((*startBuf == '@') && "bogus @synthesize location");
678 const char *semiBuf = strchr(startBuf, ';');
679 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek8189cde2009-02-07 01:47:29 +0000680 SourceLocation onePastSemiLoc =
681 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000682
683 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
684 return; // FIXME: is this correct?
685
686 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000687 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000688 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000689 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000690
691 if (!OID)
692 return;
693
694 std::string Getr;
695 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
696 Getr += "{ ";
697 // Synthesize an explicit cast to gain access to the ivar.
Steve Naroff3539cdb2008-12-02 17:54:50 +0000698 // FIXME: deal with code generation implications for various property
699 // attributes (copy, retain, nonatomic).
700 // See objc-act.c:objc_synthesize_new_getter() for details.
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000701 Getr += "return " + getIvarAccessString(ClassDecl, OID);
702 Getr += "; }";
Steve Naroffeb0646c2008-12-02 15:48:25 +0000703 InsertText(onePastSemiLoc, Getr.c_str(), Getr.size());
Steve Naroffa0876e82008-12-02 17:36:43 +0000704
705 // Add the rewritten getter to trigger meta data generation. An alternate, and
706 // possibly cleaner approach is to hack RewriteObjCMethodsMetaData() to deal
707 // with properties explicitly. The following addInstanceMethod() required far
708 // less code change (and actually models what the rewriter is doing).
709 if (IMD)
710 IMD->addInstanceMethod(PD->getGetterMethodDecl());
711 else
712 CID->addInstanceMethod(PD->getGetterMethodDecl());
Steve Naroffeb0646c2008-12-02 15:48:25 +0000713
714 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 Naroffa0876e82008-12-02 17:36:43 +0000729
730 // Add the rewritten setter to trigger meta data generation.
731 if (IMD)
732 IMD->addInstanceMethod(PD->getSetterMethodDecl());
733 else
734 CID->addInstanceMethod(PD->getSetterMethodDecl());
Steve Naroffd40910b2008-12-01 20:33:01 +0000735}
Chris Lattner8a12c272007-10-11 18:38:32 +0000736
Steve Naroffb29b4272008-04-14 22:03:09 +0000737void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000738 // Get the start location and compute the semi location.
739 SourceLocation startLoc = ClassDecl->getLocation();
740 const char *startBuf = SM->getCharacterData(startLoc);
741 const char *semiPtr = strchr(startBuf, ';');
742
743 // Translate to typedef's that forward reference structs with the same name
744 // as the class. As a convenience, we include the original declaration
745 // as a comment.
746 std::string typedefString;
747 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000748 typedefString.append(startBuf, semiPtr-startBuf+1);
749 typedefString += "\n";
Chris Lattner67956052009-02-20 18:04:31 +0000750 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
751 I != E; ++I) {
752 ObjCInterfaceDecl *ForwardDecl = *I;
Steve Naroff32174822007-11-09 12:50:28 +0000753 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000754 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000755 typedefString += "\n";
756 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000757 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000758 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000759 typedefString += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000760 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000761 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000762 }
763
764 // Replace the @class with typedefs corresponding to the classes.
Chris Lattneraadaf782008-01-31 19:51:04 +0000765 ReplaceText(startLoc, semiPtr-startBuf+1,
766 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000767}
768
Steve Naroffb29b4272008-04-14 22:03:09 +0000769void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000770 SourceLocation LocStart = Method->getLocStart();
771 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000772
Chris Lattner30fc9332009-02-04 01:06:56 +0000773 if (SM->getInstantiationLineNumber(LocEnd) >
774 SM->getInstantiationLineNumber(LocStart)) {
Steve Naroff94ac21e2008-10-21 13:37:27 +0000775 InsertText(LocStart, "#if 0\n", 6);
776 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000777 } else {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000778 InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000779 }
780}
781
Steve Naroff6327e0d2009-01-11 01:06:09 +0000782void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop)
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000783{
Steve Naroff6327e0d2009-01-11 01:06:09 +0000784 SourceLocation Loc = prop->getLocation();
785
786 ReplaceText(Loc, 0, "// ", 3);
787
788 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000789}
790
Steve Naroffb29b4272008-04-14 22:03:09 +0000791void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000792 SourceLocation LocStart = CatDecl->getLocStart();
793
794 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000795 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000796
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000797 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000798 E = CatDecl->instmeth_end(); I != E; ++I)
799 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000800 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000801 E = CatDecl->classmeth_end(); I != E; ++I)
802 RewriteMethodDeclaration(*I);
803
Steve Naroff423cb562007-10-30 13:30:57 +0000804 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000805 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000806}
807
Steve Naroffb29b4272008-04-14 22:03:09 +0000808void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000809 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000810
Steve Naroff752d6ef2007-10-30 16:42:30 +0000811 SourceLocation LocStart = PDecl->getLocStart();
812
813 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000814 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000815
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000816 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000817 E = PDecl->instmeth_end(); I != E; ++I)
818 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000819 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000820 E = PDecl->classmeth_end(); I != E; ++I)
821 RewriteMethodDeclaration(*I);
822
Steve Naroff752d6ef2007-10-30 16:42:30 +0000823 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000824 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattneraadaf782008-01-31 19:51:04 +0000825 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000826
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000827 // Must comment out @optional/@required
828 const char *startBuf = SM->getCharacterData(LocStart);
829 const char *endBuf = SM->getCharacterData(LocEnd);
830 for (const char *p = startBuf; p < endBuf; p++) {
831 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
832 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000833 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000834 ReplaceText(OptionalLoc, strlen("@optional"),
835 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000836
837 }
838 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
839 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000840 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000841 ReplaceText(OptionalLoc, strlen("@required"),
842 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000843
844 }
845 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000846}
847
Steve Naroffb29b4272008-04-14 22:03:09 +0000848void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000849 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000850 if (LocStart.isInvalid())
851 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000852 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000853 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000854}
855
Steve Naroffb29b4272008-04-14 22:03:09 +0000856void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000857 std::string &ResultStr) {
Steve Naroffced80a82008-10-30 12:09:33 +0000858 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroff76e429d2008-07-16 14:40:40 +0000859 const FunctionType *FPRetType = 0;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000860 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000861 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000862 ResultStr += "id";
Steve Narofff4312dc2008-12-11 19:29:16 +0000863 else if (OMD->getResultType()->isFunctionPointerType() ||
864 OMD->getResultType()->isBlockPointerType()) {
Steve Naroff76e429d2008-07-16 14:40:40 +0000865 // needs special handling, since pointer-to-functions have special
866 // syntax (where a decaration models use).
867 QualType retType = OMD->getResultType();
Steve Narofff4312dc2008-12-11 19:29:16 +0000868 QualType PointeeTy;
869 if (const PointerType* PT = retType->getAsPointerType())
870 PointeeTy = PT->getPointeeType();
871 else if (const BlockPointerType *BPT = retType->getAsBlockPointerType())
872 PointeeTy = BPT->getPointeeType();
873 if ((FPRetType = PointeeTy->getAsFunctionType())) {
874 ResultStr += FPRetType->getResultType().getAsString();
875 ResultStr += "(*";
Steve Naroff76e429d2008-07-16 14:40:40 +0000876 }
877 } else
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000878 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000879 ResultStr += " ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000880
881 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000882 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000883
Douglas Gregorf8d49f62009-01-09 17:18:27 +0000884 if (OMD->isInstanceMethod())
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000885 NameStr += "_I_";
886 else
887 NameStr += "_C_";
888
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000889 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000890 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000891
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000892 if (ObjCCategoryImplDecl *CID =
Steve Naroff3e0a5402009-01-08 19:41:02 +0000893 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000894 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000895 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000896 }
Steve Naroff563b8282008-04-04 22:23:44 +0000897 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +0000898 {
899 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000900 int len = selString.size();
901 for (int i = 0; i < len; i++)
902 if (selString[i] == ':')
903 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000904 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000905 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000906 // Remember this name for metadata emission
907 MethodInternalNames[OMD] = NameStr;
908 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000909
910 // Rewrite arguments
911 ResultStr += "(";
912
913 // invisible arguments
Douglas Gregorf8d49f62009-01-09 17:18:27 +0000914 if (OMD->isInstanceMethod()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000915 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000916 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +0000917 if (!LangOpts.Microsoft) {
918 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
919 ResultStr += "struct ";
920 }
921 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000922 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000923 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000924 }
925 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000926 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000927
928 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000929 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000930 ResultStr += " _cmd";
931
932 // Method arguments.
Chris Lattner58cce3b2008-03-16 01:07:14 +0000933 for (unsigned i = 0; i < OMD->getNumParams(); i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000934 ParmVarDecl *PDecl = OMD->getParamDecl(i);
935 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +0000936 if (PDecl->getType()->isObjCQualifiedIdType()) {
937 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000938 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +0000939 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000940 std::string Name = PDecl->getNameAsString();
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000941 if (isTopLevelBlockPointerType(PDecl->getType())) {
Steve Naroffc8ad87b2008-10-30 14:45:29 +0000942 // Make sure we convert "t (^)(...)" to "t (*)(...)".
943 const BlockPointerType *BPT = PDecl->getType()->getAsBlockPointerType();
944 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name);
945 } else
946 PDecl->getType().getAsStringInternal(Name);
Steve Naroff543409e2008-04-18 21:13:19 +0000947 ResultStr += Name;
948 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000949 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +0000950 if (OMD->isVariadic())
951 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000952 ResultStr += ") ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000953
Steve Naroff76e429d2008-07-16 14:40:40 +0000954 if (FPRetType) {
955 ResultStr += ")"; // close the precedence "scope" for "*".
956
957 // Now, emit the argument types (if any).
958 if (const FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(FPRetType)) {
959 ResultStr += "(";
960 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
961 if (i) ResultStr += ", ";
962 std::string ParamStr = FT->getArgType(i).getAsString();
963 ResultStr += ParamStr;
964 }
965 if (FT->isVariadic()) {
966 if (FT->getNumArgs()) ResultStr += ", ";
967 ResultStr += "...";
968 }
969 ResultStr += ")";
970 } else {
971 ResultStr += "()";
972 }
973 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000974}
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000975void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000976 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
977 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000978
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000979 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000980 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000981 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000982 InsertText(CID->getLocStart(), "// ", 3);
Steve Narofface66252008-11-13 20:07:04 +0000983
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000984 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000985 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
986 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000987 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000988 ObjCMethodDecl *OMD = *I;
989 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000990 SourceLocation LocStart = OMD->getLocStart();
991 SourceLocation LocEnd = OMD->getBody()->getLocStart();
992
993 const char *startBuf = SM->getCharacterData(LocStart);
994 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000995 ReplaceText(LocStart, endBuf-startBuf,
996 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000997 }
998
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000999 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +00001000 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1001 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001002 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001003 ObjCMethodDecl *OMD = *I;
1004 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001005 SourceLocation LocStart = OMD->getLocStart();
1006 SourceLocation LocEnd = OMD->getBody()->getLocStart();
1007
1008 const char *startBuf = SM->getCharacterData(LocStart);
1009 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +00001010 ReplaceText(LocStart, endBuf-startBuf,
1011 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001012 }
Steve Naroffd40910b2008-12-01 20:33:01 +00001013 for (ObjCCategoryImplDecl::propimpl_iterator
1014 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1015 E = IMD ? IMD->propimpl_end() : CID->propimpl_end(); I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +00001016 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001017 }
1018
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001019 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001020 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001021 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001022 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001023}
1024
Steve Naroffb29b4272008-04-14 22:03:09 +00001025void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001026 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001027 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001028 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001029 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001030 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001031 ResultStr += "\n";
1032 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001033 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001034 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001035 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001036 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001037 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001038 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001039 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001040 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001041 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Narofff908a872007-10-30 02:23:23 +00001042
Steve Naroff6327e0d2009-01-11 01:06:09 +00001043 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
1044 E = ClassDecl->prop_end(); I != E; ++I)
1045 RewriteProperty(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001046 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001047 E = ClassDecl->instmeth_end(); I != E; ++I)
1048 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001049 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001050 E = ClassDecl->classmeth_end(); I != E; ++I)
1051 RewriteMethodDeclaration(*I);
1052
Steve Naroff2feac5e2007-10-30 03:43:13 +00001053 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +00001054 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +00001055}
1056
Steve Naroffb619d952008-12-09 12:56:34 +00001057Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1058 SourceRange SrcRange) {
Steve Naroffc77a6362008-12-04 16:24:46 +00001059 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1060 // This allows us to reuse all the fun and games in SynthMessageExpr().
1061 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1062 ObjCMessageExpr *MsgExpr;
1063 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1064 llvm::SmallVector<Expr *, 1> ExprVec;
1065 ExprVec.push_back(newStmt);
1066
Steve Naroff8599e7a2008-12-08 16:43:47 +00001067 Stmt *Receiver = PropRefExpr->getBase();
1068 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1069 if (PRE && PropGetters[PRE]) {
1070 // This allows us to handle chain/nested property getters.
1071 Receiver = PropGetters[PRE];
1072 }
Ted Kremenek8189cde2009-02-07 01:47:29 +00001073 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
Steve Naroffc77a6362008-12-04 16:24:46 +00001074 PDecl->getSetterName(), PDecl->getType(),
1075 PDecl->getSetterMethodDecl(),
1076 SourceLocation(), SourceLocation(),
1077 &ExprVec[0], 1);
1078 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
1079
1080 // Now do the actual rewrite.
Steve Naroffb619d952008-12-09 12:56:34 +00001081 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffe58ee0c2008-12-10 14:53:27 +00001082 //delete BinOp;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001083 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1084 // to things that stay around.
1085 Context->Deallocate(MsgExpr);
Steve Naroffc77a6362008-12-04 16:24:46 +00001086 return ReplacingStmt;
Steve Naroff15f081d2008-12-03 00:56:33 +00001087}
1088
Steve Naroffc77a6362008-12-04 16:24:46 +00001089Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Naroff15f081d2008-12-03 00:56:33 +00001090 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1091 // This allows us to reuse all the fun and games in SynthMessageExpr().
1092 ObjCMessageExpr *MsgExpr;
1093 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1094
Steve Naroff8599e7a2008-12-08 16:43:47 +00001095 Stmt *Receiver = PropRefExpr->getBase();
1096
1097 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1098 if (PRE && PropGetters[PRE]) {
1099 // This allows us to handle chain/nested property getters.
1100 Receiver = PropGetters[PRE];
1101 }
Ted Kremenek8189cde2009-02-07 01:47:29 +00001102 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
Steve Naroff15f081d2008-12-03 00:56:33 +00001103 PDecl->getGetterName(), PDecl->getType(),
1104 PDecl->getGetterMethodDecl(),
1105 SourceLocation(), SourceLocation(),
1106 0, 0);
1107
Steve Naroff4c3580e2008-12-04 23:50:32 +00001108 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001109
1110 if (!PropParentMap)
1111 PropParentMap = new ParentMap(CurrentBody);
1112
1113 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1114 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1115 // We stash away the ReplacingStmt since actually doing the
1116 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1117 PropGetters[PropRefExpr] = ReplacingStmt;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001118 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1119 // to things that stay around.
1120 Context->Deallocate(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001121 return PropRefExpr; // return the original...
1122 } else {
1123 ReplaceStmt(PropRefExpr, ReplacingStmt);
Ted Kremenek8189cde2009-02-07 01:47:29 +00001124 // delete PropRefExpr; elsewhere...
1125 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1126 // to things that stay around.
1127 Context->Deallocate(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001128 return ReplacingStmt;
1129 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001130}
1131
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001132Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
1133 SourceLocation OrigStart) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001134 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff54055232008-10-27 17:20:55 +00001135 if (CurMethodDef) {
Steve Naroff05b8c782008-03-12 00:25:36 +00001136 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001137 ObjCInterfaceType *iFaceDecl =
1138 dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Narofff0757612008-05-08 17:52:16 +00001139 // lookup which class implements the instance variable.
1140 ObjCInterfaceDecl *clsDeclared = 0;
1141 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
1142 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1143
1144 // Synthesize an explicit cast to gain access to the ivar.
1145 std::string RecName = clsDeclared->getIdentifier()->getName();
1146 RecName += "_IMPL";
1147 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001148 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001149 SourceLocation(), II);
Steve Narofff0757612008-05-08 17:52:16 +00001150 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1151 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Ted Kremenek8189cde2009-02-07 01:47:29 +00001152 CastExpr *castExpr = new (Context) CStyleCastExpr(castT, IV->getBase(),
1153 castT,SourceLocation(),
1154 SourceLocation());
Steve Narofff0757612008-05-08 17:52:16 +00001155 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001156 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1157 IV->getBase()->getLocEnd(),
1158 castExpr);
Steve Narofff0757612008-05-08 17:52:16 +00001159 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +00001160 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001161 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1162 IV->getLocation(),
1163 D->getType());
Steve Narofff0757612008-05-08 17:52:16 +00001164 ReplaceStmt(IV, ME);
Steve Naroff4c3580e2008-12-04 23:50:32 +00001165 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Narofff0757612008-05-08 17:52:16 +00001166 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001167 }
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001168
1169 ReplaceStmt(IV->getBase(), PE);
1170 // Cannot delete IV->getBase(), since PE points to it.
1171 // Replace the old base with the cast. This is important when doing
1172 // embedded rewrites. For example, [newInv->_container addObject:0].
1173 IV->setBase(PE);
1174 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001175 }
Steve Naroff84472a82008-04-18 21:55:08 +00001176 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001177 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
1178
1179 // Explicit ivar refs need to have a cast inserted.
1180 // FIXME: consider sharing some of this code with the code above.
1181 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Narofff0757612008-05-08 17:52:16 +00001182 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001183 // lookup which class implements the instance variable.
1184 ObjCInterfaceDecl *clsDeclared = 0;
Steve Narofff0757612008-05-08 17:52:16 +00001185 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001186 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1187
1188 // Synthesize an explicit cast to gain access to the ivar.
1189 std::string RecName = clsDeclared->getIdentifier()->getName();
1190 RecName += "_IMPL";
1191 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001192 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001193 SourceLocation(), II);
Steve Naroff9f525972008-05-06 23:20:07 +00001194 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1195 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Ted Kremenek8189cde2009-02-07 01:47:29 +00001196 CastExpr *castExpr = new (Context) CStyleCastExpr(castT, IV->getBase(),
1197 castT, SourceLocation(),
1198 SourceLocation());
Steve Naroff9f525972008-05-06 23:20:07 +00001199 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001200 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner8d366162008-05-28 16:38:23 +00001201 IV->getBase()->getLocEnd(), castExpr);
Steve Naroff9f525972008-05-06 23:20:07 +00001202 ReplaceStmt(IV->getBase(), PE);
1203 // Cannot delete IV->getBase(), since PE points to it.
1204 // Replace the old base with the cast. This is important when doing
1205 // embedded rewrites. For example, [newInv->_container addObject:0].
1206 IV->setBase(PE);
1207 return IV;
1208 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001209 }
Steve Naroff84472a82008-04-18 21:55:08 +00001210 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +00001211}
1212
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001213/// SynthCountByEnumWithState - To print:
1214/// ((unsigned int (*)
1215/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1216/// (void *)objc_msgSend)((id)l_collection,
1217/// sel_registerName(
1218/// "countByEnumeratingWithState:objects:count:"),
1219/// &enumState,
1220/// (id *)items, (unsigned int)16)
1221///
Steve Naroffb29b4272008-04-14 22:03:09 +00001222void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001223 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1224 "id *, unsigned int))(void *)objc_msgSend)";
1225 buf += "\n\t\t";
1226 buf += "((id)l_collection,\n\t\t";
1227 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1228 buf += "\n\t\t";
1229 buf += "&enumState, "
1230 "(id *)items, (unsigned int)16)";
1231}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001232
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001233/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1234/// statement to exit to its outer synthesized loop.
1235///
Steve Naroffb29b4272008-04-14 22:03:09 +00001236Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001237 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1238 return S;
1239 // replace break with goto __break_label
1240 std::string buf;
1241
1242 SourceLocation startLoc = S->getLocStart();
1243 buf = "goto __break_label_";
1244 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001245 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001246
1247 return 0;
1248}
1249
1250/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1251/// statement to continue with its inner synthesized loop.
1252///
Steve Naroffb29b4272008-04-14 22:03:09 +00001253Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001254 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1255 return S;
1256 // replace continue with goto __continue_label
1257 std::string buf;
1258
1259 SourceLocation startLoc = S->getLocStart();
1260 buf = "goto __continue_label_";
1261 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001262 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001263
1264 return 0;
1265}
1266
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001267/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001268/// It rewrites:
1269/// for ( type elem in collection) { stmts; }
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001270
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001271/// Into:
1272/// {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001273/// type elem;
1274/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001275/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001276/// id l_collection = (id)collection;
1277/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1278/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001279/// if (limit) {
1280/// unsigned long startMutations = *enumState.mutationsPtr;
1281/// do {
1282/// unsigned long counter = 0;
1283/// do {
1284/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001285/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001286/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001287/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001288/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001289/// } while (counter < limit);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001290/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1291/// objects:items count:16]);
1292/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001293/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001294/// }
1295/// else
1296/// elem = nil;
1297/// }
1298///
Steve Naroffb29b4272008-04-14 22:03:09 +00001299Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001300 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001301 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1302 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1303 "ObjCForCollectionStmt Statement stack mismatch");
1304 assert(!ObjCBcLabelNo.empty() &&
1305 "ObjCForCollectionStmt - Label No stack empty");
1306
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001307 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001308 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001309 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001310 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001311 std::string buf;
1312 buf = "\n{\n\t";
1313 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1314 // type elem;
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001315 NamedDecl* D = cast<NamedDecl>(DS->getSolitaryDecl());
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001316 QualType ElementType = cast<ValueDecl>(D)->getType();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001317 elementTypeAsString = ElementType.getAsString();
1318 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001319 buf += " ";
Chris Lattner8ec03f52008-11-24 03:54:41 +00001320 elementName = D->getNameAsCString();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001321 buf += elementName;
1322 buf += ";\n\t";
1323 }
Chris Lattner06767512008-04-08 05:52:18 +00001324 else {
1325 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner8ec03f52008-11-24 03:54:41 +00001326 elementName = DR->getDecl()->getNameAsCString();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001327 elementTypeAsString
1328 = cast<ValueDecl>(DR->getDecl())->getType().getAsString();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001329 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001330
1331 // struct __objcFastEnumerationState enumState = { 0 };
1332 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1333 // id items[16];
1334 buf += "id items[16];\n\t";
1335 // id l_collection = (id)
1336 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001337 // Find start location of 'collection' the hard way!
1338 const char *startCollectionBuf = startBuf;
1339 startCollectionBuf += 3; // skip 'for'
1340 startCollectionBuf = strchr(startCollectionBuf, '(');
1341 startCollectionBuf++; // skip '('
1342 // find 'in' and skip it.
1343 while (*startCollectionBuf != ' ' ||
1344 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1345 (*(startCollectionBuf+3) != ' ' &&
1346 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1347 startCollectionBuf++;
1348 startCollectionBuf += 3;
1349
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001350 // Replace: "for (type element in" with string constructed thus far.
Chris Lattneraadaf782008-01-31 19:51:04 +00001351 ReplaceText(startLoc, startCollectionBuf - startBuf,
1352 buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001353 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001354 SourceLocation rightParenLoc = S->getRParenLoc();
1355 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1356 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001357 buf = ";\n\t";
1358
1359 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1360 // objects:items count:16];
1361 // which is synthesized into:
1362 // unsigned int limit =
1363 // ((unsigned int (*)
1364 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1365 // (void *)objc_msgSend)((id)l_collection,
1366 // sel_registerName(
1367 // "countByEnumeratingWithState:objects:count:"),
1368 // (struct __objcFastEnumerationState *)&state,
1369 // (id *)items, (unsigned int)16);
1370 buf += "unsigned long limit =\n\t\t";
1371 SynthCountByEnumWithState(buf);
1372 buf += ";\n\t";
1373 /// if (limit) {
1374 /// unsigned long startMutations = *enumState.mutationsPtr;
1375 /// do {
1376 /// unsigned long counter = 0;
1377 /// do {
1378 /// if (startMutations != *enumState.mutationsPtr)
1379 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001380 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001381 buf += "if (limit) {\n\t";
1382 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1383 buf += "do {\n\t\t";
1384 buf += "unsigned long counter = 0;\n\t\t";
1385 buf += "do {\n\t\t\t";
1386 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1387 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1388 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001389 buf += " = (";
1390 buf += elementTypeAsString;
1391 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001392 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattneraadaf782008-01-31 19:51:04 +00001393 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001394
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001395 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001396 /// } while (counter < limit);
1397 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1398 /// objects:items count:16]);
1399 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001400 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001401 /// }
1402 /// else
1403 /// elem = nil;
1404 /// }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001405 ///
1406 buf = ";\n\t";
1407 buf += "__continue_label_";
1408 buf += utostr(ObjCBcLabelNo.back());
1409 buf += ": ;";
1410 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001411 buf += "} while (counter < limit);\n\t";
1412 buf += "} while (limit = ";
1413 SynthCountByEnumWithState(buf);
1414 buf += ");\n\t";
1415 buf += elementName;
Steve Naroff5605fdf2008-12-17 14:24:39 +00001416 buf += " = ((id)0);\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001417 buf += "__break_label_";
1418 buf += utostr(ObjCBcLabelNo.back());
1419 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001420 buf += "}\n\t";
1421 buf += "else\n\t\t";
1422 buf += elementName;
Steve Naroff5605fdf2008-12-17 14:24:39 +00001423 buf += " = ((id)0);\n";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001424 buf += "}\n";
Steve Naroff600e4e82008-07-21 18:26:02 +00001425
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001426 // Insert all these *after* the statement body.
Steve Naroff600e4e82008-07-21 18:26:02 +00001427 if (isa<CompoundStmt>(S->getBody())) {
1428 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1429 InsertText(endBodyLoc, buf.c_str(), buf.size());
1430 } else {
1431 /* Need to treat single statements specially. For example:
1432 *
1433 * for (A *a in b) if (stuff()) break;
1434 * for (A *a in b) xxxyy;
1435 *
1436 * The following code simply scans ahead to the semi to find the actual end.
1437 */
1438 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1439 const char *semiBuf = strchr(stmtBuf, ';');
1440 assert(semiBuf && "Can't find ';'");
1441 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1442 InsertText(endBodyLoc, buf.c_str(), buf.size());
1443 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001444 Stmts.pop_back();
1445 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001446 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001447}
1448
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001449/// RewriteObjCSynchronizedStmt -
1450/// This routine rewrites @synchronized(expr) stmt;
1451/// into:
1452/// objc_sync_enter(expr);
1453/// @try stmt @finally { objc_sync_exit(expr); }
1454///
Steve Naroffb29b4272008-04-14 22:03:09 +00001455Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001456 // Get the start location and compute the semi location.
1457 SourceLocation startLoc = S->getLocStart();
1458 const char *startBuf = SM->getCharacterData(startLoc);
1459
1460 assert((*startBuf == '@') && "bogus @synchronized location");
1461
1462 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001463 buf = "objc_sync_enter((id)";
1464 const char *lparenBuf = startBuf;
1465 while (*lparenBuf != '(') lparenBuf++;
1466 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Steve Naroffc7089f12008-08-19 13:04:19 +00001467 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1468 // the sync expression is typically a message expression that's already
1469 // been rewritten! (which implies the SourceLocation's are invalid).
1470 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001471 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001472 while (*endBuf != ')') endBuf--;
1473 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001474 buf = ");\n";
1475 // declare a new scope with two variables, _stack and _rethrow.
1476 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1477 buf += "int buf[18/*32-bit i386*/];\n";
1478 buf += "char *pointers[4];} _stack;\n";
1479 buf += "id volatile _rethrow = 0;\n";
1480 buf += "objc_exception_try_enter(&_stack);\n";
1481 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00001482 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001483 startLoc = S->getSynchBody()->getLocEnd();
1484 startBuf = SM->getCharacterData(startLoc);
1485
Steve Naroffc7089f12008-08-19 13:04:19 +00001486 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001487 SourceLocation lastCurlyLoc = startLoc;
1488 buf = "}\nelse {\n";
1489 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1490 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb2a39452008-07-16 19:47:39 +00001491 buf += " objc_sync_exit(";
Ted Kremenek8189cde2009-02-07 01:47:29 +00001492 Expr *syncExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
1493 S->getSynchExpr(),
1494 Context->getObjCIdType(),
1495 SourceLocation(),
1496 SourceLocation());
Ted Kremeneka95d3752008-09-13 05:16:45 +00001497 std::string syncExprBufS;
1498 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Steve Naroff3498cc92008-08-21 13:03:03 +00001499 syncExpr->printPretty(syncExprBuf);
Steve Naroffb2a39452008-07-16 19:47:39 +00001500 buf += syncExprBuf.str();
1501 buf += ");\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001502 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1503 buf += "}\n";
1504 buf += "}";
1505
Chris Lattneraadaf782008-01-31 19:51:04 +00001506 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001507 return 0;
1508}
1509
Steve Naroff8c565152008-12-05 17:03:39 +00001510void RewriteObjC::WarnAboutReturnGotoContinueOrBreakStmts(Stmt *S) {
1511 // Perform a bottom up traversal of all children.
1512 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1513 CI != E; ++CI)
1514 if (*CI)
1515 WarnAboutReturnGotoContinueOrBreakStmts(*CI);
1516
1517 if (isa<ReturnStmt>(S) || isa<ContinueStmt>(S) ||
1518 isa<BreakStmt>(S) || isa<GotoStmt>(S)) {
1519 Diags.Report(Context->getFullLoc(S->getLocStart()),
1520 TryFinallyContainsReturnDiag);
1521 }
1522 return;
1523}
1524
Steve Naroffb29b4272008-04-14 22:03:09 +00001525Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001526 // Get the start location and compute the semi location.
1527 SourceLocation startLoc = S->getLocStart();
1528 const char *startBuf = SM->getCharacterData(startLoc);
1529
1530 assert((*startBuf == '@') && "bogus @try location");
1531
1532 std::string buf;
1533 // declare a new scope with two variables, _stack and _rethrow.
1534 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1535 buf += "int buf[18/*32-bit i386*/];\n";
1536 buf += "char *pointers[4];} _stack;\n";
1537 buf += "id volatile _rethrow = 0;\n";
1538 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001539 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001540
Chris Lattneraadaf782008-01-31 19:51:04 +00001541 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001542
1543 startLoc = S->getTryBody()->getLocEnd();
1544 startBuf = SM->getCharacterData(startLoc);
1545
1546 assert((*startBuf == '}') && "bogus @try block");
Steve Naroffc9ba1722008-07-16 15:31:30 +00001547
Steve Naroff75730982007-11-07 04:08:17 +00001548 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffc9ba1722008-07-16 15:31:30 +00001549 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1550 if (catchList) {
1551 startLoc = startLoc.getFileLocWithOffset(1);
1552 buf = " /* @catch begin */ else {\n";
1553 buf += " id _caught = objc_exception_extract(&_stack);\n";
1554 buf += " objc_exception_try_enter (&_stack);\n";
1555 buf += " if (_setjmp(_stack.buf))\n";
1556 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1557 buf += " else { /* @catch continue */";
1558
1559 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001560 } else { /* no catch list */
1561 buf = "}\nelse {\n";
1562 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1563 buf += "}";
1564 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffc9ba1722008-07-16 15:31:30 +00001565 }
Steve Naroff75730982007-11-07 04:08:17 +00001566 bool sawIdTypedCatch = false;
1567 Stmt *lastCatchBody = 0;
Steve Naroff75730982007-11-07 04:08:17 +00001568 while (catchList) {
1569 Stmt *catchStmt = catchList->getCatchParamStmt();
1570
1571 if (catchList == S->getCatchStmts())
1572 buf = "if ("; // we are generating code for the first catch clause
1573 else
1574 buf = "else if (";
1575 startLoc = catchList->getLocStart();
1576 startBuf = SM->getCharacterData(startLoc);
1577
1578 assert((*startBuf == '@') && "bogus @catch location");
1579
1580 const char *lParenLoc = strchr(startBuf, '(');
1581
Steve Naroffbe4b3332008-02-01 22:08:12 +00001582 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001583 // Now rewrite the body...
1584 lastCatchBody = catchList->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001585 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1586 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner06767512008-04-08 05:52:18 +00001587 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1588 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001589 assert((*bodyBuf == '{') && "bogus @catch body location");
1590
1591 buf += "1) { id _tmp = _caught;";
1592 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1593 buf.c_str(), buf.size());
1594 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Ted Kremenek50a25e22008-10-06 22:39:38 +00001595 QualType t = dyn_cast<ValueDecl>(declStmt->getSolitaryDecl())->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001596 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001597 buf += "1) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001598 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001599 sawIdTypedCatch = true;
1600 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001601 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroff75730982007-11-07 04:08:17 +00001602
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001603 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001604 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001605 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001606 buf += cls->getDecl()->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001607 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001608 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001609 }
1610 }
1611 // Now rewrite the body...
1612 lastCatchBody = catchList->getCatchBody();
1613 SourceLocation rParenLoc = catchList->getRParenLoc();
1614 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1615 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1616 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1617 assert((*rParenBuf == ')') && "bogus @catch paren location");
1618 assert((*bodyBuf == '{') && "bogus @catch body location");
1619
1620 buf = " = _caught;";
1621 // Here we replace ") {" with "= _caught;" (which initializes and
1622 // declares the @catch parameter).
Chris Lattneraadaf782008-01-31 19:51:04 +00001623 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001624 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001625 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001626 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001627 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001628 catchList = catchList->getNextCatchStmt();
1629 }
1630 // Complete the catch list...
1631 if (lastCatchBody) {
1632 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001633 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1634 "bogus @catch body location");
Steve Naroff75730982007-11-07 04:08:17 +00001635
Steve Naroff378f47a2008-09-11 15:29:03 +00001636 // Insert the last (implicit) else clause *before* the right curly brace.
1637 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1638 buf = "} /* last catch end */\n";
1639 buf += "else {\n";
1640 buf += " _rethrow = _caught;\n";
1641 buf += " objc_exception_try_exit(&_stack);\n";
1642 buf += "} } /* @catch end */\n";
1643 if (!S->getFinallyStmt())
1644 buf += "}\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001645 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001646
1647 // Set lastCurlyLoc
1648 lastCurlyLoc = lastCatchBody->getLocEnd();
1649 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001650 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001651 startLoc = finalStmt->getLocStart();
1652 startBuf = SM->getCharacterData(startLoc);
1653 assert((*startBuf == '@') && "bogus @finally start");
1654
1655 buf = "/* @finally */";
Chris Lattneraadaf782008-01-31 19:51:04 +00001656 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001657
1658 Stmt *body = finalStmt->getFinallyBody();
1659 SourceLocation startLoc = body->getLocStart();
1660 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001661 assert(*SM->getCharacterData(startLoc) == '{' &&
1662 "bogus @finally body location");
1663 assert(*SM->getCharacterData(endLoc) == '}' &&
1664 "bogus @finally body location");
Steve Naroff75730982007-11-07 04:08:17 +00001665
1666 startLoc = startLoc.getFileLocWithOffset(1);
1667 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001668 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001669 endLoc = endLoc.getFileLocWithOffset(-1);
1670 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001671 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001672
1673 // Set lastCurlyLoc
1674 lastCurlyLoc = body->getLocEnd();
Steve Naroff8c565152008-12-05 17:03:39 +00001675
1676 // Now check for any return/continue/go statements within the @try.
1677 WarnAboutReturnGotoContinueOrBreakStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00001678 } else { /* no finally clause - make sure we synthesize an implicit one */
1679 buf = "{ /* implicit finally clause */\n";
1680 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1681 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1682 buf += "}";
1683 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001684 }
1685 // Now emit the final closing curly brace...
1686 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1687 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001688 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001689 return 0;
1690}
1691
Steve Naroffb29b4272008-04-14 22:03:09 +00001692Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001693 return 0;
1694}
1695
Steve Naroffb29b4272008-04-14 22:03:09 +00001696Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001697 return 0;
1698}
1699
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001700// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff2bd03922007-11-07 15:32:26 +00001701// the throw expression is typically a message expression that's already
1702// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001703Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001704 // Get the start location and compute the semi location.
1705 SourceLocation startLoc = S->getLocStart();
1706 const char *startBuf = SM->getCharacterData(startLoc);
1707
1708 assert((*startBuf == '@') && "bogus @throw location");
1709
1710 std::string buf;
1711 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001712 if (S->getThrowExpr())
1713 buf = "objc_exception_throw(";
1714 else // add an implicit argument
1715 buf = "objc_exception_throw(_caught";
Steve Naroff4ba0acb2008-07-25 15:41:30 +00001716
1717 // handle "@ throw" correctly.
1718 const char *wBuf = strchr(startBuf, 'w');
1719 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1720 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
1721
Steve Naroff2bd03922007-11-07 15:32:26 +00001722 const char *semiBuf = strchr(startBuf, ';');
1723 assert((*semiBuf == ';') && "@throw: can't find ';'");
1724 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1725 buf = ");";
Chris Lattneraadaf782008-01-31 19:51:04 +00001726 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001727 return 0;
1728}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001729
Steve Naroffb29b4272008-04-14 22:03:09 +00001730Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001731 // Create a new string expression.
1732 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001733 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001734 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattner2085fd62009-02-18 06:40:38 +00001735 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
1736 StrEncoding.length(), false,StrType,
1737 SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001738 ReplaceStmt(Exp, Replacement);
Chris Lattnere365c502007-11-30 22:25:36 +00001739
Chris Lattner07506182007-11-30 22:53:43 +00001740 // Replace this subexpr in the parent.
Steve Naroff4c3580e2008-12-04 23:50:32 +00001741 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00001742 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001743}
1744
Steve Naroffb29b4272008-04-14 22:03:09 +00001745Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff1a937642008-12-22 22:16:07 +00001746 if (!SelGetUidFunctionDecl)
1747 SynthSelGetUidFunctionDecl();
Steve Naroffb42f8412007-11-05 14:50:49 +00001748 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1749 // Create a call to sel_registerName("selName").
1750 llvm::SmallVector<Expr*, 8> SelExprs;
1751 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner2085fd62009-02-18 06:40:38 +00001752 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00001753 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00001754 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00001755 false, argType, SourceLocation()));
Steve Naroffb42f8412007-11-05 14:50:49 +00001756 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1757 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001758 ReplaceStmt(Exp, SelExp);
Steve Naroff4c3580e2008-12-04 23:50:32 +00001759 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00001760 return SelExp;
1761}
1762
Steve Naroffb29b4272008-04-14 22:03:09 +00001763CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff934f2762007-10-24 22:48:43 +00001764 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001765 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001766 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +00001767
1768 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001769 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +00001770
1771 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001772 QualType pToFunc = Context->getPointerType(msgSendType);
Ted Kremenek8189cde2009-02-07 01:47:29 +00001773 ImplicitCastExpr *ICE = new (Context) ImplicitCastExpr(pToFunc, DRE,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001774 /*isLvalue=*/false);
Steve Naroffebf2b562007-10-23 23:50:29 +00001775
1776 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +00001777
Ted Kremenek668bf912009-02-09 20:51:47 +00001778 return new (Context) CallExpr(*Context, ICE, args, nargs, FT->getResultType(),
1779 SourceLocation());
Steve Naroff934f2762007-10-24 22:48:43 +00001780}
1781
Steve Naroffd5255f52007-11-01 13:24:47 +00001782static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1783 const char *&startRef, const char *&endRef) {
1784 while (startBuf < endBuf) {
1785 if (*startBuf == '<')
1786 startRef = startBuf; // mark the start.
1787 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001788 if (startRef && *startRef == '<') {
1789 endRef = startBuf; // mark the end.
1790 return true;
1791 }
1792 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001793 }
1794 startBuf++;
1795 }
1796 return false;
1797}
1798
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001799static void scanToNextArgument(const char *&argRef) {
1800 int angle = 0;
1801 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1802 if (*argRef == '<')
1803 angle++;
1804 else if (*argRef == '>')
1805 angle--;
1806 argRef++;
1807 }
1808 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1809}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001810
Steve Naroffb29b4272008-04-14 22:03:09 +00001811bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001812
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001813 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001814 return true;
1815
Steve Naroffd5255f52007-11-01 13:24:47 +00001816 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +00001817 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001818 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff9165ad32007-10-31 04:38:33 +00001819 return true; // we have "Class <Protocol> *".
1820 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001821 return false;
1822}
1823
Steve Naroff4f95b752008-07-29 18:15:38 +00001824void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1825 QualType Type = E->getType();
1826 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00001827 SourceLocation Loc, EndLoc;
1828
1829 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
1830 Loc = ECE->getLParenLoc();
1831 EndLoc = ECE->getRParenLoc();
1832 } else {
1833 Loc = E->getLocStart();
1834 EndLoc = E->getLocEnd();
1835 }
1836 // This will defend against trying to rewrite synthesized expressions.
1837 if (Loc.isInvalid() || EndLoc.isInvalid())
1838 return;
1839
Steve Naroff4f95b752008-07-29 18:15:38 +00001840 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00001841 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00001842 const char *startRef = 0, *endRef = 0;
1843 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1844 // Get the locations of the startRef, endRef.
1845 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1846 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1847 // Comment out the protocol references.
1848 InsertText(LessLoc, "/*", 2);
1849 InsertText(GreaterLoc, "*/", 2);
1850 }
1851 }
1852}
1853
Steve Naroffb29b4272008-04-14 22:03:09 +00001854void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001855 SourceLocation Loc;
1856 QualType Type;
1857 const FunctionTypeProto *proto = 0;
1858 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1859 Loc = VD->getLocation();
1860 Type = VD->getType();
1861 }
1862 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1863 Loc = FD->getLocation();
1864 // Check for ObjC 'id' and class types that have been adorned with protocol
1865 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1866 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1867 assert(funcType && "missing function type");
1868 proto = dyn_cast<FunctionTypeProto>(funcType);
1869 if (!proto)
1870 return;
1871 Type = proto->getResultType();
1872 }
1873 else
1874 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001875
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001876 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001877 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001878
1879 const char *endBuf = SM->getCharacterData(Loc);
1880 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00001881 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001882 startBuf--; // scan backward (from the decl location) for return type.
1883 const char *startRef = 0, *endRef = 0;
1884 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1885 // Get the locations of the startRef, endRef.
1886 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1887 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1888 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001889 InsertText(LessLoc, "/*", 2);
1890 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001891 }
1892 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001893 if (!proto)
1894 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001895 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001896 const char *startBuf = SM->getCharacterData(Loc);
1897 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001898 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1899 if (needToScanForQualifiers(proto->getArgType(i))) {
1900 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001901
Steve Naroffd5255f52007-11-01 13:24:47 +00001902 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001903 // scan forward (from the decl location) for argument types.
1904 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001905 const char *startRef = 0, *endRef = 0;
1906 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1907 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001908 SourceLocation LessLoc =
1909 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1910 SourceLocation GreaterLoc =
1911 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001912 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001913 InsertText(LessLoc, "/*", 2);
1914 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001915 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001916 startBuf = ++endBuf;
1917 }
1918 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00001919 // If the function name is derived from a macro expansion, then the
1920 // argument buffer will not follow the name. Need to speak with Chris.
1921 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001922 startBuf++; // scan forward (from the decl location) for argument types.
1923 startBuf++;
1924 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001925 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001926}
1927
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001928// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00001929void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001930 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1931 llvm::SmallVector<QualType, 16> ArgTys;
1932 ArgTys.push_back(Context->getPointerType(
1933 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001934 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001935 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001936 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001937 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001938 SourceLocation(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001939 SelGetUidIdent, getFuncType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001940 FunctionDecl::Extern, false);
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001941}
1942
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001943// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
Steve Naroffb29b4272008-04-14 22:03:09 +00001944void RewriteObjC::SynthGetProtocolFunctionDecl() {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001945 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1946 llvm::SmallVector<QualType, 16> ArgTys;
1947 ArgTys.push_back(Context->getPointerType(
1948 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001949 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001950 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001951 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001952 GetProtocolFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001953 SourceLocation(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001954 SelGetProtoIdent, getFuncType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001955 FunctionDecl::Extern, false);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001956}
1957
Steve Naroffb29b4272008-04-14 22:03:09 +00001958void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001959 // declared in <objc/objc.h>
Douglas Gregor51efe562009-01-09 01:47:02 +00001960 if (FD->getIdentifier() &&
1961 strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001962 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001963 return;
1964 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001965 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001966}
1967
Steve Naroffc0a123c2008-03-11 17:37:02 +00001968// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00001969void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00001970 if (SuperContructorFunctionDecl)
1971 return;
Steve Naroff46a98a72008-12-23 20:11:22 +00001972 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroffc0a123c2008-03-11 17:37:02 +00001973 llvm::SmallVector<QualType, 16> ArgTys;
1974 QualType argT = Context->getObjCIdType();
1975 assert(!argT.isNull() && "Can't find 'id' type");
1976 ArgTys.push_back(argT);
1977 ArgTys.push_back(argT);
1978 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1979 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001980 false, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00001981 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00001982 SourceLocation(),
Steve Naroffc0a123c2008-03-11 17:37:02 +00001983 msgSendIdent, msgSendType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001984 FunctionDecl::Extern, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00001985}
1986
Steve Naroff09b266e2007-10-30 23:14:51 +00001987// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00001988void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00001989 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1990 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001991 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001992 assert(!argT.isNull() && "Can't find 'id' type");
1993 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001994 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001995 assert(!argT.isNull() && "Can't find 'SEL' type");
1996 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001997 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001998 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00001999 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002000 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002001 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002002 msgSendIdent, msgSendType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002003 FunctionDecl::Extern, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002004}
2005
Steve Naroff874e2322007-11-15 10:28:18 +00002006// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002007void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00002008 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2009 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002010 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002011 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002012 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002013 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2014 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2015 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002016 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002017 assert(!argT.isNull() && "Can't find 'SEL' type");
2018 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002019 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00002020 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002021 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002022 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002023 SourceLocation(),
Steve Naroff874e2322007-11-15 10:28:18 +00002024 msgSendIdent, msgSendType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002025 FunctionDecl::Extern, false);
Steve Naroff874e2322007-11-15 10:28:18 +00002026}
2027
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002028// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002029void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002030 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2031 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002032 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002033 assert(!argT.isNull() && "Can't find 'id' type");
2034 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002035 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002036 assert(!argT.isNull() && "Can't find 'SEL' type");
2037 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002038 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002039 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002040 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002041 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002042 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002043 msgSendIdent, msgSendType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002044 FunctionDecl::Extern, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002045}
2046
2047// SynthMsgSendSuperStretFunctionDecl -
2048// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002049void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002050 IdentifierInfo *msgSendIdent =
2051 &Context->Idents.get("objc_msgSendSuper_stret");
2052 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002053 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002054 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002055 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002056 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2057 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2058 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002059 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002060 assert(!argT.isNull() && "Can't find 'SEL' type");
2061 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002062 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002063 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002064 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002065 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnera98e58d2008-03-15 21:24:04 +00002066 SourceLocation(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002067 msgSendIdent, msgSendType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002068 FunctionDecl::Extern, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002069}
2070
Steve Naroff1284db82008-05-08 22:02:18 +00002071// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002072void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002073 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2074 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002075 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002076 assert(!argT.isNull() && "Can't find 'id' type");
2077 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002078 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002079 assert(!argT.isNull() && "Can't find 'SEL' type");
2080 ArgTys.push_back(argT);
Steve Naroff1284db82008-05-08 22:02:18 +00002081 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002082 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002083 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002084 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002085 SourceLocation(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002086 msgSendIdent, msgSendType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002087 FunctionDecl::Extern, false);
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002088}
2089
Steve Naroff09b266e2007-10-30 23:14:51 +00002090// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002091void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002092 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2093 llvm::SmallVector<QualType, 16> ArgTys;
2094 ArgTys.push_back(Context->getPointerType(
2095 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002096 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002097 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002098 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002099 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002100 SourceLocation(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002101 getClassIdent, getClassType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002102 FunctionDecl::Extern, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002103}
2104
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002105// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002106void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002107 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2108 llvm::SmallVector<QualType, 16> ArgTys;
2109 ArgTys.push_back(Context->getPointerType(
2110 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002111 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002112 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002113 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002114 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002115 SourceLocation(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002116 getClassIdent, getClassType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002117 FunctionDecl::Extern, false);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002118}
2119
Steve Naroffb29b4272008-04-14 22:03:09 +00002120Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002121 QualType strType = getConstantStringStructType();
2122
2123 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002124
2125 std::string tmpName = InFileName;
2126 unsigned i;
2127 for (i=0; i < tmpName.length(); i++) {
2128 char c = tmpName.at(i);
2129 // replace any non alphanumeric characters with '_'.
2130 if (!isalpha(c) && (c < '0' || c > '9'))
2131 tmpName[i] = '_';
2132 }
2133 S += tmpName;
2134 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002135 S += utostr(NumObjCStringLiterals++);
2136
Steve Naroffba92b2e2008-03-27 22:29:16 +00002137 Preamble += "static __NSConstantStringImpl " + S;
2138 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2139 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002140 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002141 std::string prettyBufS;
2142 llvm::raw_string_ostream prettyBuf(prettyBufS);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002143 Exp->getString()->printPretty(prettyBuf);
Steve Naroffba92b2e2008-03-27 22:29:16 +00002144 Preamble += prettyBuf.str();
2145 Preamble += ",";
Steve Naroff3652c2d2008-03-15 01:36:04 +00002146 // The minus 2 removes the begin/end double quotes.
Steve Naroffba92b2e2008-03-27 22:29:16 +00002147 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002148
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002149 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Steve Naroff248a7532008-04-15 22:42:06 +00002150 &Context->Idents.get(S.c_str()), strType,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002151 VarDecl::Static);
Ted Kremenek8189cde2009-02-07 01:47:29 +00002152 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
2153 Expr *Unop = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002154 Context->getPointerType(DRE->getType()),
2155 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002156 // cast to NSConstantString *
Ted Kremenek8189cde2009-02-07 01:47:29 +00002157 CastExpr *cast = new (Context) CStyleCastExpr(Exp->getType(), Unop,
Steve Naroffb2f9e512008-11-03 23:29:32 +00002158 Exp->getType(), SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002159 ReplaceStmt(Exp, cast);
Steve Naroff4c3580e2008-12-04 23:50:32 +00002160 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002161 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002162}
2163
Steve Naroffb29b4272008-04-14 22:03:09 +00002164ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002165 // check if we are sending a message to 'super'
Douglas Gregorf8d49f62009-01-09 17:18:27 +00002166 if (!CurMethodDef || !CurMethodDef->isInstanceMethod()) return 0;
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002167
Douglas Gregorcd9b46e2008-11-04 14:56:14 +00002168 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
2169 const PointerType *PT = Super->getType()->getAsPointerType();
Chris Lattner0d17f6f2008-06-21 18:04:54 +00002170 assert(PT);
2171 ObjCInterfaceType *IT = cast<ObjCInterfaceType>(PT->getPointeeType());
2172 return IT->getDecl();
2173 }
2174 return 0;
Steve Naroff874e2322007-11-15 10:28:18 +00002175}
2176
2177// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002178QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002179 if (!SuperStructDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002180 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002181 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002182 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002183 QualType FieldTypes[2];
2184
2185 // struct objc_object *receiver;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002186 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002187 // struct objc_class *super;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002188 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor44b43212008-12-11 16:49:14 +00002189
Steve Naroff874e2322007-11-15 10:28:18 +00002190 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002191 for (unsigned i = 0; i < 2; ++i) {
Douglas Gregor482b77d2009-01-12 23:27:07 +00002192 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00002193 SourceLocation(), 0,
2194 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002195 /*Mutable=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002196 }
Steve Naroff874e2322007-11-15 10:28:18 +00002197
Douglas Gregor44b43212008-12-11 16:49:14 +00002198 SuperStructDecl->completeDefinition(*Context);
Steve Naroff874e2322007-11-15 10:28:18 +00002199 }
2200 return Context->getTagDeclType(SuperStructDecl);
2201}
2202
Steve Naroffb29b4272008-04-14 22:03:09 +00002203QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002204 if (!ConstantStringDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002205 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002206 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002207 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002208 QualType FieldTypes[4];
2209
2210 // struct objc_object *receiver;
2211 FieldTypes[0] = Context->getObjCIdType();
2212 // int flags;
2213 FieldTypes[1] = Context->IntTy;
2214 // char *str;
2215 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2216 // long length;
2217 FieldTypes[3] = Context->LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002218
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002219 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002220 for (unsigned i = 0; i < 4; ++i) {
Douglas Gregor482b77d2009-01-12 23:27:07 +00002221 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
Douglas Gregor44b43212008-12-11 16:49:14 +00002222 ConstantStringDecl,
2223 SourceLocation(), 0,
2224 FieldTypes[i],
2225 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002226 /*Mutable=*/true));
Douglas Gregor44b43212008-12-11 16:49:14 +00002227 }
2228
2229 ConstantStringDecl->completeDefinition(*Context);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002230 }
2231 return Context->getTagDeclType(ConstantStringDecl);
2232}
2233
Steve Naroffb29b4272008-04-14 22:03:09 +00002234Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002235 if (!SelGetUidFunctionDecl)
2236 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002237 if (!MsgSendFunctionDecl)
2238 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002239 if (!MsgSendSuperFunctionDecl)
2240 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002241 if (!MsgSendStretFunctionDecl)
2242 SynthMsgSendStretFunctionDecl();
2243 if (!MsgSendSuperStretFunctionDecl)
2244 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002245 if (!MsgSendFpretFunctionDecl)
2246 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002247 if (!GetClassFunctionDecl)
2248 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002249 if (!GetMetaClassFunctionDecl)
2250 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002251
Steve Naroff874e2322007-11-15 10:28:18 +00002252 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002253 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2254 // May need to use objc_msgSend_stret() as well.
2255 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002256 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002257 QualType resultType = mDecl->getResultType();
Chris Lattner8b51fd72008-07-26 22:36:27 +00002258 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002259 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002260 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002261 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002262 }
Steve Naroff874e2322007-11-15 10:28:18 +00002263
Steve Naroff934f2762007-10-24 22:48:43 +00002264 // Synthesize a call to objc_msgSend().
2265 llvm::SmallVector<Expr*, 8> MsgExprs;
2266 IdentifierInfo *clsName = Exp->getClassName();
2267
2268 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2269 if (clsName) { // class message.
Steve Narofffc93d522008-07-24 19:44:33 +00002270 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2271 // the 'super' idiom within a class method.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002272 if (!strcmp(clsName->getName(), "super")) {
2273 MsgSendFlavor = MsgSendSuperFunctionDecl;
2274 if (MsgSendStretFlavor)
2275 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2276 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2277
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002278 ObjCInterfaceDecl *SuperDecl =
Steve Naroff54055232008-10-27 17:20:55 +00002279 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002280
2281 llvm::SmallVector<Expr*, 4> InitExprs;
2282
2283 // set the receiver to self, the first argument to all methods.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002284 InitExprs.push_back(new (Context) DeclRefExpr(
Steve Naroff54055232008-10-27 17:20:55 +00002285 CurMethodDef->getSelfDecl(),
Chris Lattner41110242008-06-17 18:05:57 +00002286 Context->getObjCIdType(),
2287 SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002288 llvm::SmallVector<Expr*, 8> ClsExprs;
2289 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner2085fd62009-02-18 06:40:38 +00002290 ClsExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002291 SuperDecl->getIdentifier()->getName(),
2292 SuperDecl->getIdentifier()->getLength(),
Chris Lattner726e1682009-02-18 05:49:11 +00002293 false, argType, SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002294 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2295 &ClsExprs[0],
2296 ClsExprs.size());
2297 // To turn off a warning, type-cast to 'id'
Douglas Gregor49badde2008-10-27 19:41:14 +00002298 InitExprs.push_back( // set 'super class', using objc_getClass().
Ted Kremenek8189cde2009-02-07 01:47:29 +00002299 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002300 Cls, Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002301 SourceLocation(), SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002302 // struct objc_super
2303 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00002304 Expr *SuperRep;
Steve Naroffc0a123c2008-03-11 17:37:02 +00002305
Steve Naroff23f41272008-03-11 18:14:26 +00002306 if (LangOpts.Microsoft) {
2307 SynthSuperContructorFunctionDecl();
2308 // Simulate a contructor call...
Ted Kremenek8189cde2009-02-07 01:47:29 +00002309 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff23f41272008-03-11 18:14:26 +00002310 superType, SourceLocation());
Ted Kremenek668bf912009-02-09 20:51:47 +00002311 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2312 InitExprs.size(),
2313 superType, SourceLocation());
Steve Naroff46a98a72008-12-23 20:11:22 +00002314 // The code for super is a little tricky to prevent collision with
2315 // the structure definition in the header. The rewriter has it's own
2316 // internal definition (__rw_objc_super) that is uses. This is why
2317 // we need the cast below. For example:
2318 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2319 //
Ted Kremenek8189cde2009-02-07 01:47:29 +00002320 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Steve Naroff46a98a72008-12-23 20:11:22 +00002321 Context->getPointerType(SuperRep->getType()),
2322 SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00002323 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
Steve Naroff46a98a72008-12-23 20:11:22 +00002324 SuperRep, Context->getPointerType(superType),
2325 SourceLocation(), SourceLocation());
Steve Naroff23f41272008-03-11 18:14:26 +00002326 } else {
2327 // (struct objc_super) { <exprs from above> }
Ted Kremenek8189cde2009-02-07 01:47:29 +00002328 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
Steve Naroff23f41272008-03-11 18:14:26 +00002329 &InitExprs[0], InitExprs.size(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002330 SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00002331 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE,
Chris Lattner418f6c72008-10-26 23:43:26 +00002332 false);
Steve Naroff46a98a72008-12-23 20:11:22 +00002333 // struct objc_super *
Ted Kremenek8189cde2009-02-07 01:47:29 +00002334 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Steve Naroff46a98a72008-12-23 20:11:22 +00002335 Context->getPointerType(SuperRep->getType()),
2336 SourceLocation());
Steve Naroff23f41272008-03-11 18:14:26 +00002337 }
Steve Naroff46a98a72008-12-23 20:11:22 +00002338 MsgExprs.push_back(SuperRep);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002339 } else {
2340 llvm::SmallVector<Expr*, 8> ClsExprs;
2341 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner2085fd62009-02-18 06:40:38 +00002342 ClsExprs.push_back(StringLiteral::Create(*Context,
2343 clsName->getName(),
2344 clsName->getLength(),
2345 false, argType,
2346 SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002347 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2348 &ClsExprs[0],
2349 ClsExprs.size());
2350 MsgExprs.push_back(Cls);
2351 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002352 } else { // instance message.
2353 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00002354
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002355 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00002356 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002357 if (MsgSendStretFlavor)
2358 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00002359 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2360
2361 llvm::SmallVector<Expr*, 4> InitExprs;
2362
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002363 InitExprs.push_back(
Ted Kremenek8189cde2009-02-07 01:47:29 +00002364 new (Context) CStyleCastExpr(Context->getObjCIdType(),
2365 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Narofff616ebb2008-07-16 22:35:27 +00002366 Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002367 SourceLocation()),
2368 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002369 SourceLocation(), SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00002370
2371 llvm::SmallVector<Expr*, 8> ClsExprs;
2372 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner2085fd62009-02-18 06:40:38 +00002373 ClsExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002374 SuperDecl->getIdentifier()->getName(),
2375 SuperDecl->getIdentifier()->getLength(),
Chris Lattner726e1682009-02-18 05:49:11 +00002376 false, argType, SourceLocation()));
Steve Naroff874e2322007-11-15 10:28:18 +00002377 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002378 &ClsExprs[0],
2379 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00002380 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002381 InitExprs.push_back(
Douglas Gregor49badde2008-10-27 19:41:14 +00002382 // set 'super class', using objc_getClass().
Ted Kremenek8189cde2009-02-07 01:47:29 +00002383 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002384 Cls, Context->getObjCIdType(), SourceLocation(), SourceLocation()));
Steve Naroff874e2322007-11-15 10:28:18 +00002385 // struct objc_super
2386 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00002387 Expr *SuperRep;
2388
2389 if (LangOpts.Microsoft) {
2390 SynthSuperContructorFunctionDecl();
2391 // Simulate a contructor call...
Ted Kremenek8189cde2009-02-07 01:47:29 +00002392 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroffc0a123c2008-03-11 17:37:02 +00002393 superType, SourceLocation());
Ted Kremenek668bf912009-02-09 20:51:47 +00002394 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2395 InitExprs.size(),
2396 superType, SourceLocation());
Steve Naroff46a98a72008-12-23 20:11:22 +00002397 // The code for super is a little tricky to prevent collision with
2398 // the structure definition in the header. The rewriter has it's own
2399 // internal definition (__rw_objc_super) that is uses. This is why
2400 // we need the cast below. For example:
2401 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2402 //
Ted Kremenek8189cde2009-02-07 01:47:29 +00002403 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Steve Naroff46a98a72008-12-23 20:11:22 +00002404 Context->getPointerType(SuperRep->getType()),
2405 SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00002406 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
Steve Naroff46a98a72008-12-23 20:11:22 +00002407 SuperRep, Context->getPointerType(superType),
2408 SourceLocation(), SourceLocation());
Steve Naroffc0a123c2008-03-11 17:37:02 +00002409 } else {
2410 // (struct objc_super) { <exprs from above> }
Ted Kremenek8189cde2009-02-07 01:47:29 +00002411 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
Steve Naroffc0a123c2008-03-11 17:37:02 +00002412 &InitExprs[0], InitExprs.size(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002413 SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00002414 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002415 }
Steve Naroff46a98a72008-12-23 20:11:22 +00002416 MsgExprs.push_back(SuperRep);
Steve Naroff874e2322007-11-15 10:28:18 +00002417 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002418 // Remove all type-casts because it may contain objc-style types; e.g.
2419 // Foo<Proto> *.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002420 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002421 recExpr = CE->getSubExpr();
Ted Kremenek8189cde2009-02-07 01:47:29 +00002422 recExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(), recExpr,
Douglas Gregor49badde2008-10-27 19:41:14 +00002423 Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002424 SourceLocation(), SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00002425 MsgExprs.push_back(recExpr);
2426 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002427 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00002428 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002429 llvm::SmallVector<Expr*, 8> SelExprs;
2430 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner2085fd62009-02-18 06:40:38 +00002431 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002432 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00002433 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00002434 false, argType, SourceLocation()));
Steve Naroff934f2762007-10-24 22:48:43 +00002435 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2436 &SelExprs[0], SelExprs.size());
2437 MsgExprs.push_back(SelExp);
2438
2439 // Now push any user supplied arguments.
2440 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002441 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002442 // Make all implicit casts explicit...ICE comes in handy:-)
2443 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2444 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregor49badde2008-10-27 19:41:14 +00002445 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002446 ? Context->getObjCIdType()
Douglas Gregor49badde2008-10-27 19:41:14 +00002447 : ICE->getType();
Ted Kremenek8189cde2009-02-07 01:47:29 +00002448 userExpr = new (Context) CStyleCastExpr(type, userExpr, type, SourceLocation(), SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002449 }
2450 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002451 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002452 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002453 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002454 userExpr = CE->getSubExpr();
Ted Kremenek8189cde2009-02-07 01:47:29 +00002455 userExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor49badde2008-10-27 19:41:14 +00002456 userExpr, Context->getObjCIdType(),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002457 SourceLocation(), SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002458 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00002459 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002460 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00002461 // We've transferred the ownership to MsgExprs. Null out the argument in
2462 // the original expression, since we will delete it below.
2463 Exp->setArg(i, 0);
2464 }
Steve Naroffab972d32007-11-04 22:37:50 +00002465 // Generate the funky cast.
2466 CastExpr *cast;
2467 llvm::SmallVector<QualType, 8> ArgTypes;
2468 QualType returnType;
2469
2470 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002471 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2472 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2473 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002474 ArgTypes.push_back(Context->getObjCIdType());
2475 ArgTypes.push_back(Context->getObjCSelType());
2476 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002477 // Push any user argument types.
Chris Lattner58cce3b2008-03-16 01:07:14 +00002478 for (unsigned i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002479 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
2480 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002481 : mDecl->getParamDecl(i)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00002482 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroff01f2ffa2008-12-11 21:05:33 +00002483 if (isTopLevelBlockPointerType(t)) {
Steve Naroffa206b062008-10-29 14:49:46 +00002484 const BlockPointerType *BPT = t->getAsBlockPointerType();
2485 t = Context->getPointerType(BPT->getPointeeType());
2486 }
Steve Naroff352336b2007-11-05 14:36:37 +00002487 ArgTypes.push_back(t);
2488 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002489 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
2490 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00002491 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002492 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002493 }
2494 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002495 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00002496
2497 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002498 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002499 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002500
2501 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2502 // If we don't do this cast, we get the following bizarre warning/note:
2503 // xx.m:13: warning: function called through a non-compatible type
2504 // xx.m:13: note: if this code is reached, the program will abort
Ted Kremenek8189cde2009-02-07 01:47:29 +00002505 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy), DRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002506 Context->getPointerType(Context->VoidTy),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002507 SourceLocation(), SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00002508
Steve Naroffab972d32007-11-04 22:37:50 +00002509 // Now do the "normal" pointer to function cast.
2510 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002511 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00002512 // If we don't have a method decl, force a variadic cast.
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002513 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Naroffab972d32007-11-04 22:37:50 +00002514 castType = Context->getPointerType(castType);
Ted Kremenek8189cde2009-02-07 01:47:29 +00002515 cast = new (Context) CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002516
2517 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002518 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Steve Naroffab972d32007-11-04 22:37:50 +00002519
2520 const FunctionType *FT = msgSendType->getAsFunctionType();
Ted Kremenek668bf912009-02-09 20:51:47 +00002521 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2522 MsgExprs.size(),
2523 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002524 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002525 if (MsgSendStretFlavor) {
2526 // We have the method which returns a struct/union. Must also generate
2527 // call to objc_msgSend_stret and hang both varieties on a conditional
2528 // expression which dictate which one to envoke depending on size of
2529 // method's return type.
2530
2531 // Create a reference to the objc_msgSend_stret() declaration.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002532 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002533 SourceLocation());
2534 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Ted Kremenek8189cde2009-02-07 01:47:29 +00002535 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy), STDRE,
Douglas Gregor49badde2008-10-27 19:41:14 +00002536 Context->getPointerType(Context->VoidTy),
Steve Naroffb2f9e512008-11-03 23:29:32 +00002537 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002538 // Now do the "normal" pointer to function cast.
2539 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002540 &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002541 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002542 castType = Context->getPointerType(castType);
Ted Kremenek8189cde2009-02-07 01:47:29 +00002543 cast = new (Context) CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002544
2545 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002546 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002547
2548 FT = msgSendType->getAsFunctionType();
Ted Kremenek668bf912009-02-09 20:51:47 +00002549 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2550 MsgExprs.size(),
2551 FT->getResultType(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002552
2553 // Build sizeof(returnType)
Ted Kremenek8189cde2009-02-07 01:47:29 +00002554 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true, true,
Sebastian Redl05189992008-11-11 17:56:53 +00002555 returnType.getAsOpaquePtr(),
2556 Context->getSizeType(),
2557 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002558 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2559 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2560 // For X86 it is more complicated and some kind of target specific routine
2561 // is needed to decide what to do.
Chris Lattner98be4942008-03-05 18:54:05 +00002562 unsigned IntSize =
2563 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Ted Kremenek8189cde2009-02-07 01:47:29 +00002564 IntegerLiteral *limit = new (Context) IntegerLiteral(llvm::APInt(IntSize, 8),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002565 Context->IntTy,
2566 SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00002567 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002568 BinaryOperator::LE,
2569 Context->IntTy,
2570 SourceLocation());
2571 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2572 ConditionalOperator *CondExpr =
Ted Kremenek8189cde2009-02-07 01:47:29 +00002573 new (Context) ConditionalOperator(lessThanExpr, CE, STCE, returnType);
2574 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002575 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002576 return ReplacingStmt;
2577}
2578
Steve Naroffb29b4272008-04-14 22:03:09 +00002579Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002580 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff80c28552008-10-27 20:54:44 +00002581
Steve Naroffc77a6362008-12-04 16:24:46 +00002582 //ReplacingStmt->dump();
Steve Naroff934f2762007-10-24 22:48:43 +00002583 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002584 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff934f2762007-10-24 22:48:43 +00002585
Steve Naroff4c3580e2008-12-04 23:50:32 +00002586 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002587 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002588}
2589
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002590/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2591/// call to objc_getProtocol("proto-name").
Steve Naroffb29b4272008-04-14 22:03:09 +00002592Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002593 if (!GetProtocolFunctionDecl)
2594 SynthGetProtocolFunctionDecl();
2595 // Create a call to objc_getProtocol("ProtocolName").
2596 llvm::SmallVector<Expr*, 8> ProtoExprs;
2597 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner2085fd62009-02-18 06:40:38 +00002598 ProtoExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002599 Exp->getProtocol()->getNameAsCString(),
2600 strlen(Exp->getProtocol()->getNameAsCString()),
Chris Lattner726e1682009-02-18 05:49:11 +00002601 false, argType, SourceLocation()));
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002602 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2603 &ProtoExprs[0],
2604 ProtoExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002605 ReplaceStmt(Exp, ProtoExp);
Steve Naroff4c3580e2008-12-04 23:50:32 +00002606 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002607 return ProtoExp;
2608
2609}
2610
Steve Naroffbaf58c32008-05-31 14:15:04 +00002611bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
2612 const char *endBuf) {
2613 while (startBuf < endBuf) {
2614 if (*startBuf == '#') {
2615 // Skip whitespace.
2616 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2617 ;
2618 if (!strncmp(startBuf, "if", strlen("if")) ||
2619 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2620 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2621 !strncmp(startBuf, "define", strlen("define")) ||
2622 !strncmp(startBuf, "undef", strlen("undef")) ||
2623 !strncmp(startBuf, "else", strlen("else")) ||
2624 !strncmp(startBuf, "elif", strlen("elif")) ||
2625 !strncmp(startBuf, "endif", strlen("endif")) ||
2626 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2627 !strncmp(startBuf, "include", strlen("include")) ||
2628 !strncmp(startBuf, "import", strlen("import")) ||
2629 !strncmp(startBuf, "include_next", strlen("include_next")))
2630 return true;
2631 }
2632 startBuf++;
2633 }
2634 return false;
2635}
2636
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002637/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002638/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00002639void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002640 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002641 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Chris Lattner8ec03f52008-11-24 03:54:41 +00002642 assert(CDecl->getNameAsCString() &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002643 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002644 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002645 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002646 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002647 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002648 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00002649 SourceLocation LocStart = CDecl->getLocStart();
2650 SourceLocation LocEnd = CDecl->getLocEnd();
2651
2652 const char *startBuf = SM->getCharacterData(LocStart);
2653 const char *endBuf = SM->getCharacterData(LocEnd);
Steve Naroffbaf58c32008-05-31 14:15:04 +00002654
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002655 // If no ivars and no root or if its root, directly or indirectly,
2656 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002657 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2658 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002659 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattneraadaf782008-01-31 19:51:04 +00002660 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002661 return;
2662 }
2663
2664 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002665 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002666 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002667 Result += CDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002668 if (LangOpts.Microsoft)
2669 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00002670
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002671 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002672 const char *cursor = strchr(startBuf, '{');
2673 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002674 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00002675 // If the buffer contains preprocessor directives, we do more fine-grained
2676 // rewrites. This is intended to fix code that looks like (which occurs in
2677 // NSURL.h, for example):
2678 //
2679 // #ifdef XYZ
2680 // @interface Foo : NSObject
2681 // #else
2682 // @interface FooBar : NSObject
2683 // #endif
2684 // {
2685 // int i;
2686 // }
2687 // @end
2688 //
2689 // This clause is segregated to avoid breaking the common case.
2690 if (BufferContainsPPDirectives(startBuf, cursor)) {
2691 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
2692 CDecl->getClassLoc();
2693 const char *endHeader = SM->getCharacterData(L);
2694 endHeader += Lexer::MeasureTokenLength(L, *SM);
2695
Chris Lattner3db6cae2008-07-21 18:19:38 +00002696 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00002697 // advance to the end of the referenced protocols.
2698 while (endHeader < cursor && *endHeader != '>') endHeader++;
2699 endHeader++;
2700 }
2701 // rewrite the original header
2702 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2703 } else {
2704 // rewrite the original header *without* disturbing the '{'
2705 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
2706 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002707 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002708 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002709 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002710 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002711 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00002712 Result += "_IVARS;\n";
Steve Narofffea763e82007-11-14 19:25:57 +00002713
2714 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002715 SourceLocation OnePastCurly =
2716 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2717 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002718 }
2719 cursor++; // past '{'
2720
2721 // Now comment out any visibility specifiers.
2722 while (cursor < endBuf) {
2723 if (*cursor == '@') {
2724 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002725 // Skip whitespace.
2726 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2727 /*scan*/;
2728
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002729 // FIXME: presence of @public, etc. inside comment results in
2730 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002731 if (!strncmp(cursor, "public", strlen("public")) ||
2732 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00002733 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002734 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002735 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002736 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002737 // FIXME: If there are cases where '<' is used in ivar declaration part
2738 // of user code, then scan the ivar list and use needToScanForQualifiers
2739 // for type checking.
2740 else if (*cursor == '<') {
2741 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002742 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002743 cursor = strchr(cursor, '>');
2744 cursor++;
2745 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002746 InsertText(atLoc, " */", 3);
Steve Naroffced80a82008-10-30 12:09:33 +00002747 } else if (*cursor == '^') { // rewrite block specifier.
2748 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2749 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002750 }
Steve Narofffea763e82007-11-14 19:25:57 +00002751 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002752 }
Steve Narofffea763e82007-11-14 19:25:57 +00002753 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002754 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00002755 } else { // we don't have any instance variables - insert super struct.
2756 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2757 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002758 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002759 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002760 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00002761 Result += "_IVARS;\n};\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00002762 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002763 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002764 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002765 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00002766 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002767}
2768
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002769// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002770/// class methods.
Steve Naroffb29b4272008-04-14 22:03:09 +00002771void RewriteObjC::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002772 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002773 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002774 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002775 const char *ClassName,
2776 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002777 if (MethodBegin == MethodEnd) return;
2778
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002779 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002780 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002781 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002782 SEL _cmd;
2783 char *method_types;
2784 void *_imp;
2785 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002786 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002787 Result += "\nstruct _objc_method {\n";
2788 Result += "\tSEL _cmd;\n";
2789 Result += "\tchar *method_types;\n";
2790 Result += "\tvoid *_imp;\n";
2791 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002792
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002793 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002794 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002795
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002796 // Build _objc_method_list for class's methods if needed
Steve Naroff946a6932008-03-11 00:12:29 +00002797
2798 /* struct {
2799 struct _objc_method_list *next_method;
2800 int method_count;
2801 struct _objc_method method_list[];
2802 }
2803 */
2804 Result += "\nstatic struct {\n";
2805 Result += "\tstruct _objc_method_list *next_method;\n";
2806 Result += "\tint method_count;\n";
2807 Result += "\tstruct _objc_method method_list[";
2808 Result += utostr(MethodEnd-MethodBegin);
2809 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002810 Result += prefix;
2811 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2812 Result += "_METHODS_";
2813 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002814 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002815 Result += IsInstanceMethod ? "inst" : "cls";
2816 Result += "_meth\")))= ";
2817 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002818
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002819 Result += "\t,{{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002820 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002821 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002822 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002823 Result += "\", \"";
2824 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002825 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002826 Result += MethodInternalNames[*MethodBegin];
2827 Result += "}\n";
2828 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2829 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002830 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002831 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002832 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002833 Result += "\", \"";
2834 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002835 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002836 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002837 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002838 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002839 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002840}
2841
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002842/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00002843void RewriteObjC::
2844RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
2845 const char *prefix,
2846 const char *ClassName,
2847 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002848 static bool objc_protocol_methods = false;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002849 if (Protocols.empty()) return;
2850
2851 for (unsigned i = 0; i != Protocols.size(); i++) {
2852 ObjCProtocolDecl *PDecl = Protocols[i];
2853 // Output struct protocol_methods holder of method selector and type.
2854 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
2855 /* struct protocol_methods {
2856 SEL _cmd;
2857 char *method_types;
2858 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002859 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002860 Result += "\nstruct protocol_methods {\n";
2861 Result += "\tSEL _cmd;\n";
2862 Result += "\tchar *method_types;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002863 Result += "};\n";
Steve Narofffbfe8252008-05-06 18:26:51 +00002864
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002865 objc_protocol_methods = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002866 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002867 // Do not synthesize the protocol more than once.
2868 if (ObjCSynthesizedProtocols.count(PDecl))
2869 continue;
2870
2871 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2872 unsigned NumMethods = PDecl->getNumInstanceMethods();
2873 /* struct _objc_protocol_method_list {
2874 int protocol_method_count;
2875 struct protocol_methods protocols[];
2876 }
2877 */
2878 Result += "\nstatic struct {\n";
2879 Result += "\tint protocol_method_count;\n";
2880 Result += "\tstruct protocol_methods protocols[";
2881 Result += utostr(NumMethods);
2882 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002883 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002884 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
2885 "{\n\t" + utostr(NumMethods) + "\n";
2886
2887 // Output instance methods declared in this protocol.
2888 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
2889 E = PDecl->instmeth_end(); I != E; ++I) {
2890 if (I == PDecl->instmeth_begin())
2891 Result += "\t ,{{(SEL)\"";
2892 else
2893 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002894 Result += (*I)->getSelector().getAsString().c_str();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002895 std::string MethodTypeString;
2896 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2897 Result += "\", \"";
2898 Result += MethodTypeString;
2899 Result += "\"}\n";
2900 }
2901 Result += "\t }\n};\n";
2902 }
2903
2904 // Output class methods declared in this protocol.
2905 int NumMethods = PDecl->getNumClassMethods();
2906 if (NumMethods > 0) {
2907 /* struct _objc_protocol_method_list {
2908 int protocol_method_count;
2909 struct protocol_methods protocols[];
2910 }
2911 */
2912 Result += "\nstatic struct {\n";
2913 Result += "\tint protocol_method_count;\n";
2914 Result += "\tstruct protocol_methods protocols[";
2915 Result += utostr(NumMethods);
2916 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002917 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002918 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2919 "{\n\t";
2920 Result += utostr(NumMethods);
2921 Result += "\n";
2922
2923 // Output instance methods declared in this protocol.
2924 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
2925 E = PDecl->classmeth_end(); I != E; ++I) {
2926 if (I == PDecl->classmeth_begin())
2927 Result += "\t ,{{(SEL)\"";
2928 else
2929 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00002930 Result += (*I)->getSelector().getAsString().c_str();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002931 std::string MethodTypeString;
2932 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2933 Result += "\", \"";
2934 Result += MethodTypeString;
2935 Result += "\"}\n";
2936 }
2937 Result += "\t }\n};\n";
2938 }
2939
2940 // Output:
2941 /* struct _objc_protocol {
2942 // Objective-C 1.0 extensions
2943 struct _objc_protocol_extension *isa;
2944 char *protocol_name;
2945 struct _objc_protocol **protocol_list;
2946 struct _objc_protocol_method_list *instance_methods;
2947 struct _objc_protocol_method_list *class_methods;
2948 };
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002949 */
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002950 static bool objc_protocol = false;
2951 if (!objc_protocol) {
2952 Result += "\nstruct _objc_protocol {\n";
2953 Result += "\tstruct _objc_protocol_extension *isa;\n";
2954 Result += "\tchar *protocol_name;\n";
2955 Result += "\tstruct _objc_protocol **protocol_list;\n";
2956 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2957 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2958 Result += "};\n";
2959
2960 objc_protocol = true;
2961 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002962
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002963 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002964 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002965 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
2966 "{\n\t0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002967 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002968 Result += "\", 0, ";
2969 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2970 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002971 Result += PDecl->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002972 Result += ", ";
2973 }
2974 else
2975 Result += "0, ";
2976 if (PDecl->getNumClassMethods() > 0) {
2977 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002978 Result += PDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002979 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002980 }
Chris Lattner9d0aaa12008-07-21 21:33:21 +00002981 else
2982 Result += "0\n";
2983 Result += "};\n";
2984
2985 // Mark this protocol as having been generated.
2986 if (!ObjCSynthesizedProtocols.insert(PDecl))
2987 assert(false && "protocol already synthesized");
2988 }
2989 // Output the top lovel protocol meta-data for the class.
2990 /* struct _objc_protocol_list {
2991 struct _objc_protocol_list *next;
2992 int protocol_count;
2993 struct _objc_protocol *class_protocols[];
2994 }
2995 */
2996 Result += "\nstatic struct {\n";
2997 Result += "\tstruct _objc_protocol_list *next;\n";
2998 Result += "\tint protocol_count;\n";
2999 Result += "\tstruct _objc_protocol *class_protocols[";
3000 Result += utostr(Protocols.size());
3001 Result += "];\n} _OBJC_";
3002 Result += prefix;
3003 Result += "_PROTOCOLS_";
3004 Result += ClassName;
3005 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3006 "{\n\t0, ";
3007 Result += utostr(Protocols.size());
3008 Result += "\n";
3009
3010 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003011 Result += Protocols[0]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003012 Result += " \n";
3013
3014 for (unsigned i = 1; i != Protocols.size(); i++) {
3015 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003016 Result += Protocols[i]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003017 Result += "\n";
3018 }
3019 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003020}
3021
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003022/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003023/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00003024void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003025 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003026 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003027 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003028 ObjCCategoryDecl *CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003029 for (CDecl = ClassDecl->getCategoryList(); CDecl;
3030 CDecl = CDecl->getNextClassCategory())
3031 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3032 break;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003033
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003034 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00003035 FullCategoryName += '_';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003036 FullCategoryName += IDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00003037
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003038 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003039 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003040 true, "CATEGORY_", FullCategoryName.c_str(),
3041 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003042
3043 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003044 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003045 false, "CATEGORY_", FullCategoryName.c_str(),
3046 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003047
3048 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00003049 // Null CDecl is case of a category implementation with no category interface
3050 if (CDecl)
Chris Lattner780f3292008-07-21 21:32:27 +00003051 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Chris Lattnereb44eee2007-12-23 01:40:15 +00003052 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003053
3054 /* struct _objc_category {
3055 char *category_name;
3056 char *class_name;
3057 struct _objc_method_list *instance_methods;
3058 struct _objc_method_list *class_methods;
3059 struct _objc_protocol_list *protocols;
3060 // Objective-C 1.0 extensions
3061 uint32_t size; // sizeof (struct _objc_category)
3062 struct _objc_property_list *instance_properties; // category's own
3063 // @property decl.
3064 };
3065 */
3066
3067 static bool objc_category = false;
3068 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003069 Result += "\nstruct _objc_category {\n";
3070 Result += "\tchar *category_name;\n";
3071 Result += "\tchar *class_name;\n";
3072 Result += "\tstruct _objc_method_list *instance_methods;\n";
3073 Result += "\tstruct _objc_method_list *class_methods;\n";
3074 Result += "\tstruct _objc_protocol_list *protocols;\n";
3075 Result += "\tunsigned int size;\n";
3076 Result += "\tstruct _objc_property_list *instance_properties;\n";
3077 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003078 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003079 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003080 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3081 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003082 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003083 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003084 Result += "\"\n\t, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003085 Result += ClassDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003086 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003087
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003088 if (IDecl->getNumInstanceMethods() > 0) {
3089 Result += "\t, (struct _objc_method_list *)"
3090 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3091 Result += FullCategoryName;
3092 Result += "\n";
3093 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003094 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003095 Result += "\t, 0\n";
3096 if (IDecl->getNumClassMethods() > 0) {
3097 Result += "\t, (struct _objc_method_list *)"
3098 "&_OBJC_CATEGORY_CLASS_METHODS_";
3099 Result += FullCategoryName;
3100 Result += "\n";
3101 }
3102 else
3103 Result += "\t, 0\n";
3104
Chris Lattner780f3292008-07-21 21:32:27 +00003105 if (CDecl && !CDecl->getReferencedProtocols().empty()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003106 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
3107 Result += FullCategoryName;
3108 Result += "\n";
3109 }
3110 else
3111 Result += "\t, 0\n";
3112 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003113}
3114
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003115/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3116/// ivar offset.
Steve Naroffb29b4272008-04-14 22:03:09 +00003117void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003118 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003119 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00003120 if (ivar->isBitField()) {
3121 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3122 // place all bitfields at offset 0.
3123 Result += "0";
3124 } else {
3125 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003126 Result += IDecl->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003127 if (LangOpts.Microsoft)
3128 Result += "_IMPL";
3129 Result += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003130 Result += ivar->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003131 Result += ")";
3132 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003133}
3134
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003135//===----------------------------------------------------------------------===//
3136// Meta Data Emission
3137//===----------------------------------------------------------------------===//
3138
Steve Naroffb29b4272008-04-14 22:03:09 +00003139void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003140 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003141 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003142
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003143 // Explictly declared @interface's are already synthesized.
3144 if (CDecl->ImplicitInterfaceDecl()) {
3145 // FIXME: Implementation of a class with no @interface (legacy) doese not
3146 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003147 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003148 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003149
Chris Lattnerbe6df082007-12-12 07:56:42 +00003150 // Build _objc_ivar_list metadata for classes ivars if needed
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003151 unsigned NumIvars = !IDecl->ivar_empty()
3152 ? IDecl->ivar_size()
3153 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003154 if (NumIvars > 0) {
3155 static bool objc_ivar = false;
3156 if (!objc_ivar) {
3157 /* struct _objc_ivar {
3158 char *ivar_name;
3159 char *ivar_type;
3160 int ivar_offset;
3161 };
3162 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003163 Result += "\nstruct _objc_ivar {\n";
3164 Result += "\tchar *ivar_name;\n";
3165 Result += "\tchar *ivar_type;\n";
3166 Result += "\tint ivar_offset;\n";
3167 Result += "};\n";
3168
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003169 objc_ivar = true;
3170 }
3171
Steve Naroff946a6932008-03-11 00:12:29 +00003172 /* struct {
3173 int ivar_count;
3174 struct _objc_ivar ivar_list[nIvars];
3175 };
3176 */
3177 Result += "\nstatic struct {\n";
3178 Result += "\tint ivar_count;\n";
3179 Result += "\tstruct _objc_ivar ivar_list[";
3180 Result += utostr(NumIvars);
3181 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003182 Result += IDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003183 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003184 "{\n\t";
3185 Result += utostr(NumIvars);
3186 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003187
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003188 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003189 if (!IDecl->ivar_empty()) {
Chris Lattnerbe6df082007-12-12 07:56:42 +00003190 IVI = IDecl->ivar_begin();
3191 IVE = IDecl->ivar_end();
3192 } else {
3193 IVI = CDecl->ivar_begin();
3194 IVE = CDecl->ivar_end();
3195 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003196 Result += "\t,{{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003197 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003198 Result += "\", \"";
3199 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003200 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003201 Result += StrEncoding;
3202 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003203 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003204 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003205 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003206 Result += "\t ,{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003207 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003208 Result += "\", \"";
3209 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00003210 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003211 Result += StrEncoding;
3212 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003213 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003214 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003215 }
3216
3217 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003218 }
3219
3220 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003221 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003222 true, "", IDecl->getNameAsCString(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003223
3224 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003225 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003226 false, "", IDecl->getNameAsCString(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003227
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003228 // Protocols referenced in class declaration?
Chris Lattner780f3292008-07-21 21:32:27 +00003229 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003230 "CLASS", CDecl->getNameAsCString(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003231
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003232
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003233 // Declaration of class/meta-class metadata
3234 /* struct _objc_class {
3235 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003236 const char *super_class_name;
3237 char *name;
3238 long version;
3239 long info;
3240 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003241 struct _objc_ivar_list *ivars;
3242 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003243 struct objc_cache *cache;
3244 struct objc_protocol_list *protocols;
3245 const char *ivar_layout;
3246 struct _objc_class_ext *ext;
3247 };
3248 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003249 static bool objc_class = false;
3250 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003251 Result += "\nstruct _objc_class {\n";
3252 Result += "\tstruct _objc_class *isa;\n";
3253 Result += "\tconst char *super_class_name;\n";
3254 Result += "\tchar *name;\n";
3255 Result += "\tlong version;\n";
3256 Result += "\tlong info;\n";
3257 Result += "\tlong instance_size;\n";
3258 Result += "\tstruct _objc_ivar_list *ivars;\n";
3259 Result += "\tstruct _objc_method_list *methods;\n";
3260 Result += "\tstruct objc_cache *cache;\n";
3261 Result += "\tstruct _objc_protocol_list *protocols;\n";
3262 Result += "\tconst char *ivar_layout;\n";
3263 Result += "\tstruct _objc_class_ext *ext;\n";
3264 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003265 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003266 }
3267
3268 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003269 ObjCInterfaceDecl *RootClass = 0;
3270 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003271 while (SuperClass) {
3272 RootClass = SuperClass;
3273 SuperClass = SuperClass->getSuperClass();
3274 }
3275 SuperClass = CDecl->getSuperClass();
3276
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003277 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003278 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003279 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003280 "{\n\t(struct _objc_class *)\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003281 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003282 Result += "\"";
3283
3284 if (SuperClass) {
3285 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003286 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003287 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003288 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003289 Result += "\"";
3290 }
3291 else {
3292 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003293 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003294 Result += "\"";
3295 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003296 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003297 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003298 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffb26d7132007-12-05 21:49:40 +00003299 if (IDecl->getNumClassMethods() > 0) {
Steve Naroff23f41272008-03-11 18:14:26 +00003300 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003301 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003302 Result += "\n";
3303 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003304 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003305 Result += ", 0\n";
Chris Lattner3db6cae2008-07-21 18:19:38 +00003306 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003307 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003308 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003309 Result += ",0,0\n";
3310 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003311 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003312 Result += "\t,0,0,0,0\n";
3313 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003314
3315 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003316 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003317 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003318 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003319 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003320 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003321 if (SuperClass) {
3322 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003323 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003324 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003325 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003326 Result += "\"";
3327 }
3328 else {
3329 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003330 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003331 Result += "\"";
3332 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003333 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003334 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003335 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003336 Result += ",0";
3337 else {
3338 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003339 Result += ",sizeof(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003340 Result += CDecl->getNameAsString();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003341 if (LangOpts.Microsoft)
3342 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003343 Result += ")";
3344 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003345 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00003346 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003347 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003348 Result += "\n\t";
3349 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003350 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003351 Result += ",0";
3352 if (IDecl->getNumInstanceMethods() > 0) {
Steve Naroff946a6932008-03-11 00:12:29 +00003353 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003354 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003355 Result += ", 0\n\t";
3356 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003357 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003358 Result += ",0,0";
Chris Lattner3db6cae2008-07-21 18:19:38 +00003359 if (!CDecl->getReferencedProtocols().empty()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003360 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003361 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003362 Result += ", 0,0\n";
3363 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003364 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003365 Result += ",0,0,0\n";
3366 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003367}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003368
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003369/// RewriteImplementations - This routine rewrites all method implementations
3370/// and emits meta-data.
3371
Steve Narofface66252008-11-13 20:07:04 +00003372void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003373 int ClsDefCount = ClassImplementation.size();
3374 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003375
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003376 // Rewrite implemented methods
3377 for (int i = 0; i < ClsDefCount; i++)
3378 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003379
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003380 for (int i = 0; i < CatDefCount; i++)
3381 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00003382}
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003383
Steve Narofface66252008-11-13 20:07:04 +00003384void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3385 int ClsDefCount = ClassImplementation.size();
3386 int CatDefCount = CategoryImplementation.size();
3387
Steve Naroff5df5b762008-05-07 21:23:49 +00003388 // This is needed for determining instance variable offsets.
Steve Naroffa11440b2008-08-05 18:47:23 +00003389 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003390 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003391 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003392 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003393
3394 // For each implemented category, write out all its meta data.
3395 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003396 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003397
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003398 // Write objc_symtab metadata
3399 /*
3400 struct _objc_symtab
3401 {
3402 long sel_ref_cnt;
3403 SEL *refs;
3404 short cls_def_cnt;
3405 short cat_def_cnt;
3406 void *defs[cls_def_cnt + cat_def_cnt];
3407 };
3408 */
3409
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003410 Result += "\nstruct _objc_symtab {\n";
3411 Result += "\tlong sel_ref_cnt;\n";
3412 Result += "\tSEL *refs;\n";
3413 Result += "\tshort cls_def_cnt;\n";
3414 Result += "\tshort cat_def_cnt;\n";
3415 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3416 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003417
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003418 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00003419 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003420 Result += "\t0, 0, " + utostr(ClsDefCount)
3421 + ", " + utostr(CatDefCount) + "\n";
3422 for (int i = 0; i < ClsDefCount; i++) {
3423 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003424 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003425 Result += "\n";
3426 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003427
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003428 for (int i = 0; i < CatDefCount; i++) {
3429 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003430 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003431 Result += "_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003432 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003433 Result += "\n";
3434 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003435
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003436 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003437
3438 // Write objc_module metadata
3439
3440 /*
3441 struct _objc_module {
3442 long version;
3443 long size;
3444 const char *name;
3445 struct _objc_symtab *symtab;
3446 }
3447 */
3448
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003449 Result += "\nstruct _objc_module {\n";
3450 Result += "\tlong version;\n";
3451 Result += "\tlong size;\n";
3452 Result += "\tconst char *name;\n";
3453 Result += "\tstruct _objc_symtab *symtab;\n";
3454 Result += "};\n\n";
3455 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00003456 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003457 Result += "\t" + utostr(OBJC_ABI_VERSION) +
3458 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003459 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003460
3461 if (LangOpts.Microsoft) {
3462 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00003463 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003464 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3465 Result += "&_OBJC_MODULES;\n";
3466 Result += "#pragma data_seg(pop)\n\n";
3467 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003468}
Chris Lattner311ff022007-10-16 22:36:42 +00003469
Steve Naroff54055232008-10-27 17:20:55 +00003470std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3471 const char *funcName,
3472 std::string Tag) {
3473 const FunctionType *AFT = CE->getFunctionType();
3474 QualType RT = AFT->getResultType();
3475 std::string StructRef = "struct " + Tag;
3476 std::string S = "static " + RT.getAsString() + " __" +
3477 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003478
Steve Naroff54055232008-10-27 17:20:55 +00003479 BlockDecl *BD = CE->getBlockDecl();
3480
3481 if (isa<FunctionTypeNoProto>(AFT)) {
Steve Naroffdf8570d2009-02-02 17:19:26 +00003482 // No user-supplied arguments. Still need to pass in a pointer to the
3483 // block (to reference imported block decl refs).
3484 S += "(" + StructRef + " *__cself)";
Steve Naroff54055232008-10-27 17:20:55 +00003485 } else if (BD->param_empty()) {
3486 S += "(" + StructRef + " *__cself)";
3487 } else {
3488 const FunctionTypeProto *FT = cast<FunctionTypeProto>(AFT);
3489 assert(FT && "SynthesizeBlockFunc: No function proto");
3490 S += '(';
3491 // first add the implicit argument.
3492 S += StructRef + " *__cself, ";
3493 std::string ParamStr;
3494 for (BlockDecl::param_iterator AI = BD->param_begin(),
3495 E = BD->param_end(); AI != E; ++AI) {
3496 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003497 ParamStr = (*AI)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003498 (*AI)->getType().getAsStringInternal(ParamStr);
3499 S += ParamStr;
3500 }
3501 if (FT->isVariadic()) {
3502 if (!BD->param_empty()) S += ", ";
3503 S += "...";
3504 }
3505 S += ')';
3506 }
3507 S += " {\n";
3508
3509 // Create local declarations to avoid rewriting all closure decl ref exprs.
3510 // First, emit a declaration for all "by ref" decls.
3511 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3512 E = BlockByRefDecls.end(); I != E; ++I) {
3513 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003514 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003515 Context->getPointerType((*I)->getType()).getAsStringInternal(Name);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003516 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Steve Naroff54055232008-10-27 17:20:55 +00003517 }
3518 // Next, emit a declaration for all "by copy" declarations.
3519 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3520 E = BlockByCopyDecls.end(); I != E; ++I) {
3521 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003522 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003523 // Handle nested closure invocation. For example:
3524 //
3525 // void (^myImportedClosure)(void);
3526 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3527 //
3528 // void (^anotherClosure)(void);
3529 // anotherClosure = ^(void) {
3530 // myImportedClosure(); // import and invoke the closure
3531 // };
3532 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003533 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00003534 S += "struct __block_impl *";
3535 else
3536 (*I)->getType().getAsStringInternal(Name);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003537 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff54055232008-10-27 17:20:55 +00003538 }
3539 std::string RewrittenStr = RewrittenBlockExprs[CE];
3540 const char *cstr = RewrittenStr.c_str();
3541 while (*cstr++ != '{') ;
3542 S += cstr;
3543 S += "\n";
3544 return S;
3545}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003546
Steve Naroff54055232008-10-27 17:20:55 +00003547std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3548 const char *funcName,
3549 std::string Tag) {
3550 std::string StructRef = "struct " + Tag;
3551 std::string S = "static void __";
3552
3553 S += funcName;
3554 S += "_block_copy_" + utostr(i);
3555 S += "(" + StructRef;
3556 S += "*dst, " + StructRef;
3557 S += "*src) {";
3558 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3559 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00003560 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003561 S += (*I)->getNameAsString();
Steve Naroff47a24222008-12-11 20:51:38 +00003562 S += ", (void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003563 S += (*I)->getNameAsString();
Steve Naroff5bc60d02008-12-16 15:50:30 +00003564 S += ", 3/*BLOCK_FIELD_IS_OBJECT*/);}";
Steve Naroff54055232008-10-27 17:20:55 +00003565 }
3566 S += "\nstatic void __";
3567 S += funcName;
3568 S += "_block_dispose_" + utostr(i);
3569 S += "(" + StructRef;
3570 S += "*src) {";
3571 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3572 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00003573 S += "_Block_object_dispose((void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003574 S += (*I)->getNameAsString();
Steve Naroff5bc60d02008-12-16 15:50:30 +00003575 S += ", 3/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00003576 }
3577 S += "}\n";
3578 return S;
3579}
3580
3581std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3582 bool hasCopyDisposeHelpers) {
Steve Naroffced80a82008-10-30 12:09:33 +00003583 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00003584 std::string Constructor = " " + Tag;
3585
3586 S += " {\n struct __block_impl impl;\n";
3587
3588 if (hasCopyDisposeHelpers)
3589 S += " void *copy;\n void *dispose;\n";
3590
3591 Constructor += "(void *fp";
3592
3593 if (hasCopyDisposeHelpers)
3594 Constructor += ", void *copyHelp, void *disposeHelp";
3595
3596 if (BlockDeclRefs.size()) {
3597 // Output all "by copy" declarations.
3598 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3599 E = BlockByCopyDecls.end(); I != E; ++I) {
3600 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003601 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003602 std::string ArgName = "_" + FieldName;
3603 // Handle nested closure invocation. For example:
3604 //
3605 // void (^myImportedBlock)(void);
3606 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3607 //
3608 // void (^anotherBlock)(void);
3609 // anotherBlock = ^(void) {
3610 // myImportedBlock(); // import and invoke the closure
3611 // };
3612 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003613 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00003614 S += "struct __block_impl *";
3615 Constructor += ", void *" + ArgName;
3616 } else {
3617 (*I)->getType().getAsStringInternal(FieldName);
3618 (*I)->getType().getAsStringInternal(ArgName);
3619 Constructor += ", " + ArgName;
3620 }
3621 S += FieldName + ";\n";
3622 }
3623 // Output all "by ref" declarations.
3624 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3625 E = BlockByRefDecls.end(); I != E; ++I) {
3626 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003627 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003628 std::string ArgName = "_" + FieldName;
3629 // Handle nested closure invocation. For example:
3630 //
3631 // void (^myImportedBlock)(void);
3632 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3633 //
3634 // void (^anotherBlock)(void);
3635 // anotherBlock = ^(void) {
3636 // myImportedBlock(); // import and invoke the closure
3637 // };
3638 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003639 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00003640 S += "struct __block_impl *";
3641 Constructor += ", void *" + ArgName;
3642 } else {
3643 Context->getPointerType((*I)->getType()).getAsStringInternal(FieldName);
3644 Context->getPointerType((*I)->getType()).getAsStringInternal(ArgName);
3645 Constructor += ", " + ArgName;
3646 }
3647 S += FieldName + "; // by ref\n";
3648 }
3649 // Finish writing the constructor.
3650 // FIXME: handle NSConcreteGlobalBlock.
3651 Constructor += ", int flags=0) {\n";
3652 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3653 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3654
3655 if (hasCopyDisposeHelpers)
3656 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3657
3658 // Initialize all "by copy" arguments.
3659 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3660 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003661 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003662 Constructor += " ";
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003663 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00003664 Constructor += Name + " = (struct __block_impl *)_";
3665 else
3666 Constructor += Name + " = _";
3667 Constructor += Name + ";\n";
3668 }
3669 // Initialize all "by ref" arguments.
3670 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3671 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003672 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003673 Constructor += " ";
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003674 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00003675 Constructor += Name + " = (struct __block_impl *)_";
3676 else
3677 Constructor += Name + " = _";
3678 Constructor += Name + ";\n";
3679 }
3680 } else {
3681 // Finish writing the constructor.
3682 // FIXME: handle NSConcreteGlobalBlock.
3683 Constructor += ", int flags=0) {\n";
3684 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3685 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3686 if (hasCopyDisposeHelpers)
3687 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3688 }
3689 Constructor += " ";
3690 Constructor += "}\n";
3691 S += Constructor;
3692 S += "};\n";
3693 return S;
3694}
3695
3696void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3697 const char *FunName) {
3698 // Insert closures that were part of the function.
3699 for (unsigned i = 0; i < Blocks.size(); i++) {
3700
3701 CollectBlockDeclRefInfo(Blocks[i]);
3702
3703 std::string Tag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
3704
3705 std::string CI = SynthesizeBlockImpl(Blocks[i], Tag,
3706 ImportedBlockDecls.size() > 0);
3707
3708 InsertText(FunLocStart, CI.c_str(), CI.size());
3709
3710 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, Tag);
3711
3712 InsertText(FunLocStart, CF.c_str(), CF.size());
3713
3714 if (ImportedBlockDecls.size()) {
3715 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, Tag);
3716 InsertText(FunLocStart, HF.c_str(), HF.size());
3717 }
3718
3719 BlockDeclRefs.clear();
3720 BlockByRefDecls.clear();
3721 BlockByCopyDecls.clear();
3722 BlockCallExprs.clear();
3723 ImportedBlockDecls.clear();
3724 }
3725 Blocks.clear();
3726 RewrittenBlockExprs.clear();
3727}
3728
3729void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3730 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner8ec03f52008-11-24 03:54:41 +00003731 const char *FuncName = FD->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003732
3733 SynthesizeBlockLiterals(FunLocStart, FuncName);
3734}
3735
3736void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00003737 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3738 //SourceLocation FunLocStart = MD->getLocStart();
3739 // FIXME: This hack works around a bug in Rewrite.InsertText().
3740 SourceLocation FunLocStart = MD->getLocStart().getFileLocWithOffset(-1);
Chris Lattner077bf5e2008-11-24 03:33:13 +00003741 std::string FuncName = MD->getSelector().getAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003742 // Convert colons to underscores.
3743 std::string::size_type loc = 0;
3744 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3745 FuncName.replace(loc, 1, "_");
3746
3747 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
3748}
3749
3750void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
3751 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3752 CI != E; ++CI)
3753 if (*CI) {
3754 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3755 GetBlockDeclRefExprs(CBE->getBody());
3756 else
3757 GetBlockDeclRefExprs(*CI);
3758 }
3759 // Handle specific things.
3760 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
3761 // FIXME: Handle enums.
3762 if (!isa<FunctionDecl>(CDRE->getDecl()))
3763 BlockDeclRefs.push_back(CDRE);
3764 return;
3765}
3766
3767void RewriteObjC::GetBlockCallExprs(Stmt *S) {
3768 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3769 CI != E; ++CI)
3770 if (*CI) {
3771 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3772 GetBlockCallExprs(CBE->getBody());
3773 else
3774 GetBlockCallExprs(*CI);
3775 }
3776
3777 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
3778 if (CE->getCallee()->getType()->isBlockPointerType()) {
3779 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
3780 }
3781 }
3782 return;
3783}
3784
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003785Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00003786 // Navigate to relevant type information.
3787 const char *closureName = 0;
3788 const BlockPointerType *CPT = 0;
3789
3790 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003791 closureName = DRE->getDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003792 CPT = DRE->getType()->getAsBlockPointerType();
3793 } else if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003794 closureName = CDRE->getDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003795 CPT = CDRE->getType()->getAsBlockPointerType();
3796 } else if (MemberExpr *MExpr = dyn_cast<MemberExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00003797 closureName = MExpr->getMemberDecl()->getNameAsCString();
Steve Naroff54055232008-10-27 17:20:55 +00003798 CPT = MExpr->getType()->getAsBlockPointerType();
3799 } else {
3800 assert(1 && "RewriteBlockClass: Bad type");
3801 }
3802 assert(CPT && "RewriteBlockClass: Bad type");
3803 const FunctionType *FT = CPT->getPointeeType()->getAsFunctionType();
3804 assert(FT && "RewriteBlockClass: Bad type");
3805 const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(FT);
3806 // FTP will be null for closures that don't take arguments.
3807
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003808 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
3809 SourceLocation(),
3810 &Context->Idents.get("__block_impl"));
3811 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00003812
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003813 // Generate a funky cast.
3814 llvm::SmallVector<QualType, 8> ArgTypes;
3815
3816 // Push the block argument type.
3817 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00003818 if (FTP) {
3819 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003820 E = FTP->arg_type_end(); I && (I != E); ++I) {
3821 QualType t = *I;
3822 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003823 if (isTopLevelBlockPointerType(t)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003824 const BlockPointerType *BPT = t->getAsBlockPointerType();
3825 t = Context->getPointerType(BPT->getPointeeType());
3826 }
3827 ArgTypes.push_back(t);
3828 }
Steve Naroff54055232008-10-27 17:20:55 +00003829 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003830 // Now do the pointer to function cast.
3831 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
3832 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
3833
3834 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Steve Naroff54055232008-10-27 17:20:55 +00003835
Ted Kremenek8189cde2009-02-07 01:47:29 +00003836 CastExpr *BlkCast = new (Context) CStyleCastExpr(PtrBlock, Exp->getCallee(),
3837 PtrBlock, SourceLocation(),
3838 SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003839 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003840 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3841 BlkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003842 //PE->dump();
Steve Naroff54055232008-10-27 17:20:55 +00003843
Douglas Gregor44b43212008-12-11 16:49:14 +00003844 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
3845 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003846 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek8189cde2009-02-07 01:47:29 +00003847 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
3848 FD->getType());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003849
Ted Kremenek8189cde2009-02-07 01:47:29 +00003850 CastExpr *FunkCast = new (Context) CStyleCastExpr(PtrToFuncCastType, ME,
3851 PtrToFuncCastType,
3852 SourceLocation(),
3853 SourceLocation());
3854 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003855
3856 llvm::SmallVector<Expr*, 8> BlkExprs;
3857 // Add the implicit argument.
3858 BlkExprs.push_back(BlkCast);
3859 // Add the user arguments.
Steve Naroff54055232008-10-27 17:20:55 +00003860 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3861 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003862 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00003863 }
Ted Kremenek668bf912009-02-09 20:51:47 +00003864 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
3865 BlkExprs.size(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00003866 Exp->getType(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003867 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00003868}
3869
3870void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003871 Stmt *BlockCall = SynthesizeBlockCall(Exp);
3872 ReplaceStmt(Exp, BlockCall);
Steve Naroff54055232008-10-27 17:20:55 +00003873}
3874
3875void RewriteObjC::RewriteBlockDeclRefExpr(BlockDeclRefExpr *BDRE) {
3876 // FIXME: Add more elaborate code generation required by the ABI.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003877 Expr *DerefExpr = new (Context) UnaryOperator(BDRE, UnaryOperator::Deref,
Steve Naroffdf8570d2009-02-02 17:19:26 +00003878 Context->getPointerType(BDRE->getType()),
3879 SourceLocation());
3880 // Need parens to enforce precedence.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003881 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), DerefExpr);
Steve Naroffdf8570d2009-02-02 17:19:26 +00003882 ReplaceStmt(BDRE, PE);
Steve Naroff54055232008-10-27 17:20:55 +00003883}
3884
Steve Naroffb2f9e512008-11-03 23:29:32 +00003885void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3886 SourceLocation LocStart = CE->getLParenLoc();
3887 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00003888
3889 // Need to avoid trying to rewrite synthesized casts.
3890 if (LocStart.isInvalid())
3891 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00003892 // Need to avoid trying to rewrite casts contained in macros.
3893 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3894 return;
Steve Narofffa15fd92008-10-28 20:29:00 +00003895
Steve Naroff54055232008-10-27 17:20:55 +00003896 const char *startBuf = SM->getCharacterData(LocStart);
3897 const char *endBuf = SM->getCharacterData(LocEnd);
3898
3899 // advance the location to startArgList.
3900 const char *argPtr = startBuf;
3901
3902 while (*argPtr++ && (argPtr < endBuf)) {
3903 switch (*argPtr) {
3904 case '^':
3905 // Replace the '^' with '*'.
3906 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
3907 ReplaceText(LocStart, 1, "*", 1);
3908 break;
3909 }
3910 }
3911 return;
3912}
3913
3914void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
3915 SourceLocation DeclLoc = FD->getLocation();
3916 unsigned parenCount = 0;
3917
3918 // We have 1 or more arguments that have closure pointers.
3919 const char *startBuf = SM->getCharacterData(DeclLoc);
3920 const char *startArgList = strchr(startBuf, '(');
3921
3922 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
3923
3924 parenCount++;
3925 // advance the location to startArgList.
3926 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
3927 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
3928
3929 const char *argPtr = startArgList;
3930
3931 while (*argPtr++ && parenCount) {
3932 switch (*argPtr) {
3933 case '^':
3934 // Replace the '^' with '*'.
3935 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
3936 ReplaceText(DeclLoc, 1, "*", 1);
3937 break;
3938 case '(':
3939 parenCount++;
3940 break;
3941 case ')':
3942 parenCount--;
3943 break;
3944 }
3945 }
3946 return;
3947}
3948
3949bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
3950 const FunctionTypeProto *FTP;
3951 const PointerType *PT = QT->getAsPointerType();
3952 if (PT) {
3953 FTP = PT->getPointeeType()->getAsFunctionTypeProto();
3954 } else {
3955 const BlockPointerType *BPT = QT->getAsBlockPointerType();
3956 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
3957 FTP = BPT->getPointeeType()->getAsFunctionTypeProto();
3958 }
3959 if (FTP) {
3960 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
3961 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003962 if (isTopLevelBlockPointerType(*I))
Steve Naroff54055232008-10-27 17:20:55 +00003963 return true;
3964 }
3965 return false;
3966}
3967
Ted Kremenek8189cde2009-02-07 01:47:29 +00003968void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
3969 const char *&RParen) {
Steve Naroff54055232008-10-27 17:20:55 +00003970 const char *argPtr = strchr(Name, '(');
3971 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
3972
3973 LParen = argPtr; // output the start.
3974 argPtr++; // skip past the left paren.
3975 unsigned parenCount = 1;
3976
3977 while (*argPtr && parenCount) {
3978 switch (*argPtr) {
3979 case '(': parenCount++; break;
3980 case ')': parenCount--; break;
3981 default: break;
3982 }
3983 if (parenCount) argPtr++;
3984 }
3985 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
3986 RParen = argPtr; // output the end
3987}
3988
3989void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
3990 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3991 RewriteBlockPointerFunctionArgs(FD);
3992 return;
3993 }
3994 // Handle Variables and Typedefs.
3995 SourceLocation DeclLoc = ND->getLocation();
3996 QualType DeclT;
3997 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3998 DeclT = VD->getType();
3999 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4000 DeclT = TDD->getUnderlyingType();
4001 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4002 DeclT = FD->getType();
4003 else
4004 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
4005
4006 const char *startBuf = SM->getCharacterData(DeclLoc);
4007 const char *endBuf = startBuf;
4008 // scan backward (from the decl location) for the end of the previous decl.
4009 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4010 startBuf--;
4011
4012 // *startBuf != '^' if we are dealing with a pointer to function that
4013 // may take block argument types (which will be handled below).
4014 if (*startBuf == '^') {
4015 // Replace the '^' with '*', computing a negative offset.
4016 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
4017 ReplaceText(DeclLoc, 1, "*", 1);
4018 }
4019 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4020 // Replace the '^' with '*' for arguments.
4021 DeclLoc = ND->getLocation();
4022 startBuf = SM->getCharacterData(DeclLoc);
4023 const char *argListBegin, *argListEnd;
4024 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4025 while (argListBegin < argListEnd) {
4026 if (*argListBegin == '^') {
4027 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
4028 ReplaceText(CaretLoc, 1, "*", 1);
4029 }
4030 argListBegin++;
4031 }
4032 }
4033 return;
4034}
4035
4036void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
4037 // Add initializers for any closure decl refs.
4038 GetBlockDeclRefExprs(Exp->getBody());
4039 if (BlockDeclRefs.size()) {
4040 // Unique all "by copy" declarations.
4041 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4042 if (!BlockDeclRefs[i]->isByRef())
4043 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
4044 // Unique all "by ref" declarations.
4045 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4046 if (BlockDeclRefs[i]->isByRef()) {
4047 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
4048 }
4049 // Find any imported blocks...they will need special attention.
4050 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Steve Naroff47a24222008-12-11 20:51:38 +00004051 if (BlockDeclRefs[i]->getType()->isBlockPointerType()) {
Steve Naroff00072682008-11-13 17:40:07 +00004052 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff54055232008-10-27 17:20:55 +00004053 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4054 }
4055 }
4056}
4057
Steve Narofffa15fd92008-10-28 20:29:00 +00004058FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
4059 IdentifierInfo *ID = &Context->Idents.get(name);
4060 QualType FType = Context->getFunctionTypeNoProto(Context->VoidPtrTy);
4061 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004062 ID, FType, FunctionDecl::Extern, false);
Steve Narofffa15fd92008-10-28 20:29:00 +00004063}
4064
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004065Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004066 Blocks.push_back(Exp);
4067
4068 CollectBlockDeclRefInfo(Exp);
4069 std::string FuncName;
4070
4071 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00004072 FuncName = CurFunctionDef->getNameAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00004073 else if (CurMethodDef) {
Chris Lattner077bf5e2008-11-24 03:33:13 +00004074 FuncName = CurMethodDef->getSelector().getAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00004075 // Convert colons to underscores.
4076 std::string::size_type loc = 0;
4077 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4078 FuncName.replace(loc, 1, "_");
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004079 } else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004080 FuncName = std::string(GlobalVarDecl->getNameAsString());
Steve Narofffa15fd92008-10-28 20:29:00 +00004081
4082 std::string BlockNumber = utostr(Blocks.size()-1);
4083
4084 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4085 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
4086
4087 // Get a pointer to the function type so we can cast appropriately.
4088 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
4089
4090 FunctionDecl *FD;
4091 Expr *NewRep;
4092
4093 // Simulate a contructor call...
4094 FD = SynthBlockInitFunctionDecl(Tag.c_str());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004095 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004096
4097 llvm::SmallVector<Expr*, 4> InitExprs;
4098
Steve Narofffdc03722008-10-29 21:23:59 +00004099 // Initialize the block function.
Steve Narofffa15fd92008-10-28 20:29:00 +00004100 FD = SynthBlockInitFunctionDecl(Func.c_str());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004101 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
4102 SourceLocation());
4103 CastExpr *castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy, Arg,
4104 Context->VoidPtrTy, SourceLocation(),
4105 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004106 InitExprs.push_back(castExpr);
Steve Narofffa15fd92008-10-28 20:29:00 +00004107
4108 if (ImportedBlockDecls.size()) {
4109 std::string Buf = "__" + FuncName + "_block_copy_" + BlockNumber;
Steve Narofffdc03722008-10-29 21:23:59 +00004110 FD = SynthBlockInitFunctionDecl(Buf.c_str());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004111 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4112 castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy, Arg,
4113 Context->VoidPtrTy, SourceLocation(),
4114 SourceLocation());
Steve Narofffdc03722008-10-29 21:23:59 +00004115 InitExprs.push_back(castExpr);
4116
Steve Narofffa15fd92008-10-28 20:29:00 +00004117 Buf = "__" + FuncName + "_block_dispose_" + BlockNumber;
Steve Narofffdc03722008-10-29 21:23:59 +00004118 FD = SynthBlockInitFunctionDecl(Buf.c_str());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004119 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4120 castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy, Arg,
4121 Context->VoidPtrTy, SourceLocation(),
4122 SourceLocation());
Steve Narofffdc03722008-10-29 21:23:59 +00004123 InitExprs.push_back(castExpr);
Steve Narofffa15fd92008-10-28 20:29:00 +00004124 }
4125 // Add initializers for any closure decl refs.
4126 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00004127 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00004128 // Output all "by copy" declarations.
4129 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4130 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004131 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00004132 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner8ec03f52008-11-24 03:54:41 +00004133 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004134 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004135 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004136 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004137 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4138 Exp = new (Context) CStyleCastExpr(Context->VoidPtrTy, Arg,
4139 Context->VoidPtrTy, SourceLocation(),
4140 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004141 } else {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004142 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004143 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004144 }
Steve Narofffdc03722008-10-29 21:23:59 +00004145 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004146 }
4147 // Output all "by ref" declarations.
4148 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4149 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004150 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004151 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4152 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf,
Steve Narofffdc03722008-10-29 21:23:59 +00004153 Context->getPointerType(Exp->getType()),
4154 SourceLocation());
Steve Naroff707b0fe2008-11-14 21:36:12 +00004155 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004156 }
4157 }
Ted Kremenek668bf912009-02-09 20:51:47 +00004158 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4159 FType, SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004160 NewRep = new (Context) UnaryOperator(NewRep, UnaryOperator::AddrOf,
Steve Narofffa15fd92008-10-28 20:29:00 +00004161 Context->getPointerType(NewRep->getType()),
4162 SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004163 NewRep = new (Context) CStyleCastExpr(FType, NewRep, FType, SourceLocation(),
4164 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004165 BlockDeclRefs.clear();
4166 BlockByRefDecls.clear();
4167 BlockByCopyDecls.clear();
4168 ImportedBlockDecls.clear();
4169 return NewRep;
4170}
4171
4172//===----------------------------------------------------------------------===//
4173// Function Body / Expression rewriting
4174//===----------------------------------------------------------------------===//
4175
Steve Naroffc77a6362008-12-04 16:24:46 +00004176// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
4177// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
4178// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
4179// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
4180// Since the rewriter isn't capable of rewriting rewritten code, it's important
4181// we get this right.
4182void RewriteObjC::CollectPropertySetters(Stmt *S) {
4183 // Perform a bottom up traversal of all children.
4184 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4185 CI != E; ++CI)
4186 if (*CI)
4187 CollectPropertySetters(*CI);
4188
4189 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
4190 if (BinOp->isAssignmentOp()) {
4191 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
4192 PropSetters[PRE] = BinOp;
4193 }
4194 }
4195}
4196
Steve Narofffa15fd92008-10-28 20:29:00 +00004197Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
4198 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4199 isa<DoStmt>(S) || isa<ForStmt>(S))
4200 Stmts.push_back(S);
4201 else if (isa<ObjCForCollectionStmt>(S)) {
4202 Stmts.push_back(S);
4203 ObjCBcLabelNo.push_back(++BcLabelCount);
4204 }
4205
4206 SourceRange OrigStmtRange = S->getSourceRange();
4207
4208 // Perform a bottom up rewrite of all children.
4209 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4210 CI != E; ++CI)
4211 if (*CI) {
4212 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
4213 if (newStmt)
4214 *CI = newStmt;
4215 }
4216
4217 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4218 // Rewrite the block body in place.
4219 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
4220
4221 // Now we snarf the rewritten text and stash it away for later use.
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004222 std::string Str = Rewrite.getRewritenText(BE->getSourceRange());
4223 RewrittenBlockExprs[BE] = Str;
Steve Narofffa15fd92008-10-28 20:29:00 +00004224
4225 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
4226 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004227 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00004228 return blockTranscribed;
4229 }
4230 // Handle specific things.
4231 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4232 return RewriteAtEncode(AtEncode);
4233
4234 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
4235 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
4236
Steve Naroffc77a6362008-12-04 16:24:46 +00004237 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
4238 BinaryOperator *BinOp = PropSetters[PropRefExpr];
4239 if (BinOp) {
4240 // Because the rewriter doesn't allow us to rewrite rewritten code,
4241 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroffb619d952008-12-09 12:56:34 +00004242 DisableReplaceStmt = true;
4243 // Save the source range. Even if we disable the replacement, the
4244 // rewritten node will have been inserted into the tree. If the synthesized
4245 // node is at the 'end', the rewriter will fail. Consider this:
4246 // self.errorHandler = handler ? handler :
4247 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
4248 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroffc77a6362008-12-04 16:24:46 +00004249 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroffb619d952008-12-09 12:56:34 +00004250 DisableReplaceStmt = false;
Steve Naroff4c3580e2008-12-04 23:50:32 +00004251 //
4252 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
4253 // we changed the RHS of BinOp, the rewriter would fail (since it needs
4254 // to see the original expression). Consider this example:
4255 //
4256 // Foo *obj1, *obj2;
4257 //
4258 // obj1.i = [obj2 rrrr];
4259 //
4260 // 'BinOp' for the previous expression looks like:
4261 //
4262 // (BinaryOperator 0x231ccf0 'int' '='
4263 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
4264 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
4265 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
4266 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
4267 //
4268 // 'newStmt' represents the rewritten message expression. For example:
4269 //
4270 // (CallExpr 0x231d300 'id':'struct objc_object *'
4271 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
4272 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
4273 // (CStyleCastExpr 0x231d220 'void *'
4274 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
4275 //
4276 // Note that 'newStmt' is passed to RewritePropertySetter so that it
4277 // can be used as the setter argument. ReplaceStmt() will still 'see'
4278 // the original RHS (since we haven't altered BinOp).
4279 //
4280 // This implies the Rewrite* routines can no longer delete the original
4281 // node. As a result, we now leak the original AST nodes.
4282 //
Steve Naroffb619d952008-12-09 12:56:34 +00004283 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroffc77a6362008-12-04 16:24:46 +00004284 } else {
4285 return RewritePropertyGetter(PropRefExpr);
Steve Naroff15f081d2008-12-03 00:56:33 +00004286 }
4287 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004288 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4289 return RewriteAtSelector(AtSelector);
4290
4291 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4292 return RewriteObjCStringLiteral(AtString);
4293
4294 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00004295#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00004296 // Before we rewrite it, put the original message expression in a comment.
4297 SourceLocation startLoc = MessExpr->getLocStart();
4298 SourceLocation endLoc = MessExpr->getLocEnd();
4299
4300 const char *startBuf = SM->getCharacterData(startLoc);
4301 const char *endBuf = SM->getCharacterData(endLoc);
4302
4303 std::string messString;
4304 messString += "// ";
4305 messString.append(startBuf, endBuf-startBuf+1);
4306 messString += "\n";
4307
4308 // FIXME: Missing definition of
4309 // InsertText(clang::SourceLocation, char const*, unsigned int).
4310 // InsertText(startLoc, messString.c_str(), messString.size());
4311 // Tried this, but it didn't work either...
4312 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00004313#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00004314 return RewriteMessageExpr(MessExpr);
4315 }
4316
4317 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4318 return RewriteObjCTryStmt(StmtTry);
4319
4320 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4321 return RewriteObjCSynchronizedStmt(StmtTry);
4322
4323 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4324 return RewriteObjCThrowStmt(StmtThrow);
4325
4326 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4327 return RewriteObjCProtocolExpr(ProtocolExp);
4328
4329 if (ObjCForCollectionStmt *StmtForCollection =
4330 dyn_cast<ObjCForCollectionStmt>(S))
4331 return RewriteObjCForCollectionStmt(StmtForCollection,
4332 OrigStmtRange.getEnd());
4333 if (BreakStmt *StmtBreakStmt =
4334 dyn_cast<BreakStmt>(S))
4335 return RewriteBreakStmt(StmtBreakStmt);
4336 if (ContinueStmt *StmtContinueStmt =
4337 dyn_cast<ContinueStmt>(S))
4338 return RewriteContinueStmt(StmtContinueStmt);
4339
4340 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
4341 // and cast exprs.
4342 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4343 // FIXME: What we're doing here is modifying the type-specifier that
4344 // precedes the first Decl. In the future the DeclGroup should have
4345 // a separate type-specifier that we can rewrite.
4346 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
4347
4348 // Blocks rewrite rules.
4349 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4350 DI != DE; ++DI) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004351 Decl *SD = *DI;
Steve Narofffa15fd92008-10-28 20:29:00 +00004352 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004353 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004354 RewriteBlockPointerDecl(ND);
4355 else if (ND->getType()->isFunctionPointerType())
4356 CheckFunctionPointerDecl(ND->getType(), ND);
4357 }
4358 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004359 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004360 RewriteBlockPointerDecl(TD);
4361 else if (TD->getUnderlyingType()->isFunctionPointerType())
4362 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4363 }
4364 }
4365 }
4366
4367 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4368 RewriteObjCQualifiedInterfaceTypes(CE);
4369
4370 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4371 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4372 assert(!Stmts.empty() && "Statement stack is empty");
4373 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4374 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
4375 && "Statement stack mismatch");
4376 Stmts.pop_back();
4377 }
4378 // Handle blocks rewriting.
4379 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4380 if (BDRE->isByRef())
4381 RewriteBlockDeclRefExpr(BDRE);
4382 }
4383 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004384 if (CE->getCallee()->getType()->isBlockPointerType()) {
4385 Stmt *BlockCall = SynthesizeBlockCall(CE);
4386 ReplaceStmt(S, BlockCall);
4387 return BlockCall;
4388 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004389 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00004390 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004391 RewriteCastExpr(CE);
4392 }
4393#if 0
4394 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00004395 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004396 // Get the new text.
4397 std::string SStr;
4398 llvm::raw_string_ostream Buf(SStr);
4399 Replacement->printPretty(Buf);
4400 const std::string &Str = Buf.str();
4401
4402 printf("CAST = %s\n", &Str[0]);
4403 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4404 delete S;
4405 return Replacement;
4406 }
4407#endif
4408 // Return this stmt unmodified.
4409 return S;
4410}
4411
4412/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4413/// main file of the input.
4414void RewriteObjC::HandleDeclInMainFile(Decl *D) {
4415 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffcb735302008-12-17 00:20:22 +00004416 if (FD->isOverloadedOperator())
4417 return;
4418
Steve Narofffa15fd92008-10-28 20:29:00 +00004419 // Since function prototypes don't have ParmDecl's, we check the function
4420 // prototype. This enables us to rewrite function declarations and
4421 // definitions using the same code.
4422 RewriteBlocksInFunctionTypeProto(FD->getType(), FD);
4423
4424 if (Stmt *Body = FD->getBody()) {
4425 CurFunctionDef = FD;
Steve Naroffc77a6362008-12-04 16:24:46 +00004426 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00004427 CurrentBody = Body;
Steve Narofffa15fd92008-10-28 20:29:00 +00004428 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff8599e7a2008-12-08 16:43:47 +00004429 CurrentBody = 0;
4430 if (PropParentMap) {
4431 delete PropParentMap;
4432 PropParentMap = 0;
4433 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004434 // This synthesizes and inserts the block "impl" struct, invoke function,
4435 // and any copy/dispose helper functions.
4436 InsertBlockLiteralsWithinFunction(FD);
4437 CurFunctionDef = 0;
4438 }
4439 return;
4440 }
4441 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4442 if (Stmt *Body = MD->getBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004443 CurMethodDef = MD;
Steve Naroffc77a6362008-12-04 16:24:46 +00004444 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00004445 CurrentBody = Body;
Steve Narofffa15fd92008-10-28 20:29:00 +00004446 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff8599e7a2008-12-08 16:43:47 +00004447 CurrentBody = 0;
4448 if (PropParentMap) {
4449 delete PropParentMap;
4450 PropParentMap = 0;
4451 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004452 InsertBlockLiteralsWithinMethod(MD);
4453 CurMethodDef = 0;
4454 }
4455 }
4456 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
4457 ClassImplementation.push_back(CI);
4458 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
4459 CategoryImplementation.push_back(CI);
4460 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
4461 RewriteForwardClassDecl(CD);
4462 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4463 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004464 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004465 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004466 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004467 CheckFunctionPointerDecl(VD->getType(), VD);
4468 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00004469 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004470 RewriteCastExpr(CE);
4471 }
4472 }
4473 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004474 if (VD->getInit()) {
4475 GlobalVarDecl = VD;
Steve Naroffc77a6362008-12-04 16:24:46 +00004476 CollectPropertySetters(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00004477 CurrentBody = VD->getInit();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004478 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00004479 CurrentBody = 0;
4480 if (PropParentMap) {
4481 delete PropParentMap;
4482 PropParentMap = 0;
4483 }
Douglas Gregor2e1cd422008-11-17 14:58:09 +00004484 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00004485 VD->getNameAsCString());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004486 GlobalVarDecl = 0;
4487
4488 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00004489 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004490 RewriteCastExpr(CE);
4491 }
4492 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004493 return;
4494 }
4495 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004496 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004497 RewriteBlockPointerDecl(TD);
4498 else if (TD->getUnderlyingType()->isFunctionPointerType())
4499 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4500 return;
4501 }
4502 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
4503 if (RD->isDefinition()) {
Douglas Gregora4c46df2008-12-11 17:59:21 +00004504 for (RecordDecl::field_iterator i = RD->field_begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00004505 e = RD->field_end(); i != e; ++i) {
4506 FieldDecl *FD = *i;
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004507 if (isTopLevelBlockPointerType(FD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004508 RewriteBlockPointerDecl(FD);
4509 }
4510 }
4511 return;
4512 }
4513 // Nothing yet.
4514}
4515
4516void RewriteObjC::HandleTranslationUnit(TranslationUnit& TU) {
4517 // Get the top-level buffer that this corresponds to.
4518
4519 // Rewrite tabs if we care.
4520 //RewriteTabs();
4521
4522 if (Diags.hasErrorOccurred())
4523 return;
4524
4525 // Create the output file.
4526
4527 llvm::OwningPtr<llvm::raw_ostream> OwnedStream;
4528 llvm::raw_ostream *OutFile;
4529 if (OutFileName == "-") {
4530 OutFile = &llvm::outs();
4531 } else if (!OutFileName.empty()) {
4532 std::string Err;
Steve Naroff62c26322009-02-03 20:39:18 +00004533 OutFile = new llvm::raw_fd_ostream(OutFileName.c_str(),
4534 // set binary mode (critical for Windoze)
4535 true,
4536 Err);
Steve Narofffa15fd92008-10-28 20:29:00 +00004537 OwnedStream.reset(OutFile);
4538 } else if (InFileName == "-") {
4539 OutFile = &llvm::outs();
4540 } else {
4541 llvm::sys::Path Path(InFileName);
4542 Path.eraseSuffix();
4543 Path.appendSuffix("cpp");
4544 std::string Err;
Steve Naroff62c26322009-02-03 20:39:18 +00004545 OutFile = new llvm::raw_fd_ostream(Path.toString().c_str(),
4546 // set binary mode (critical for Windoze)
4547 true,
4548 Err);
Steve Narofffa15fd92008-10-28 20:29:00 +00004549 OwnedStream.reset(OutFile);
4550 }
4551
4552 RewriteInclude();
4553
Chris Lattner2b2453a2009-01-17 06:22:33 +00004554 InsertText(SM->getLocForStartOfFile(MainFileID),
Steve Narofffa15fd92008-10-28 20:29:00 +00004555 Preamble.c_str(), Preamble.size(), false);
4556
Steve Naroff0aab7962008-11-14 14:10:01 +00004557 if (ClassImplementation.size() || CategoryImplementation.size())
4558 RewriteImplementations();
Steve Narofffa15fd92008-10-28 20:29:00 +00004559
4560 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
4561 // we are done.
4562 if (const RewriteBuffer *RewriteBuf =
4563 Rewrite.getRewriteBufferFor(MainFileID)) {
4564 //printf("Changed:\n");
4565 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4566 } else {
4567 fprintf(stderr, "No changes\n");
4568 }
Steve Narofface66252008-11-13 20:07:04 +00004569
Steve Naroff0aab7962008-11-14 14:10:01 +00004570 if (ClassImplementation.size() || CategoryImplementation.size()) {
4571 // Rewrite Objective-c meta data*
4572 std::string ResultStr;
4573 SynthesizeMetaDataIntoBuffer(ResultStr);
4574 // Emit metadata.
4575 *OutFile << ResultStr;
4576 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004577 OutFile->flush();
4578}
4579