blob: 26b32478b89203dee2cb180b6583a9ce282ae8bf [file] [log] [blame]
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
Chris Lattnere99c8322007-10-11 00:43:27 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-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 Lattnere99c8322007-10-11 00:43:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
Eli Friedman9f30fc32009-05-18 22:50:54 +000014#include "clang/Frontend/ASTConsumers.h"
Chris Lattner16a0de42007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattnere99c8322007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Steve Naroff1042ff32008-12-08 16:43:47 +000018#include "clang/AST/ParentMap.h"
Chris Lattner16a0de42007-10-11 18:38:32 +000019#include "clang/Basic/SourceManager.h"
Steve Naroffdb1ab1c2007-10-23 23:50:29 +000020#include "clang/Basic/IdentifierTable.h"
Chris Lattner4431a1b2007-11-30 22:53:43 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattnerf3a59a12007-12-02 01:13:47 +000022#include "clang/Lex/Lexer.h"
Benjamin Kramer89b422c2009-08-23 12:08:50 +000023#include "llvm/Support/MemoryBuffer.h"
24#include "llvm/Support/raw_ostream.h"
Chris Lattner211f8b82007-10-25 17:07:24 +000025#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian99e96b02007-10-26 19:46:17 +000026#include "llvm/ADT/SmallPtrSet.h"
Ted Kremenek2d470fc2008-09-13 05:16:45 +000027#include "llvm/ADT/OwningPtr.h"
Fariborz Jahaniane3891582010-01-05 18:04:40 +000028#include "llvm/ADT/DenseSet.h"
Chris Lattnere99c8322007-10-11 00:43:27 +000029using namespace clang;
Chris Lattner211f8b82007-10-25 17:07:24 +000030using llvm::utostr;
Chris Lattnere99c8322007-10-11 00:43:27 +000031
Chris Lattnere99c8322007-10-11 00:43:27 +000032namespace {
Steve Naroff1dc53ef2008-04-14 22:03:09 +000033 class RewriteObjC : public ASTConsumer {
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +000034 enum {
35 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
36 block, ... */
37 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
38 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
39 __block variable */
40 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
41 helpers */
42 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
43 support routines */
44 BLOCK_BYREF_CURRENT_MAX = 256
45 };
46
47 enum {
48 BLOCK_NEEDS_FREE = (1 << 24),
49 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
50 BLOCK_HAS_CXX_OBJ = (1 << 26),
51 BLOCK_IS_GC = (1 << 27),
52 BLOCK_IS_GLOBAL = (1 << 28),
53 BLOCK_HAS_DESCRIPTOR = (1 << 29)
54 };
55
Chris Lattner0bd1c972007-10-16 21:07:07 +000056 Rewriter Rewrite;
Chris Lattnere9c810c2007-11-30 22:25:36 +000057 Diagnostic &Diags;
Steve Naroff945a3b12008-03-10 20:43:59 +000058 const LangOptions &LangOpts;
Steve Naroff7b3579b2008-01-30 19:17:43 +000059 unsigned RewriteFailedDiag;
Steve Naroff6d6da252008-12-05 17:03:39 +000060 unsigned TryFinallyContainsReturnDiag;
Mike Stump11289f42009-09-09 15:08:12 +000061
Chris Lattnerc6d91c02007-10-17 22:35:30 +000062 ASTContext *Context;
Chris Lattnere99c8322007-10-11 00:43:27 +000063 SourceManager *SM;
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +000064 TranslationUnitDecl *TUDecl;
Chris Lattnerd32480d2009-01-17 06:22:33 +000065 FileID MainFileID;
Chris Lattnerf3a59a12007-12-02 01:13:47 +000066 const char *MainFileStart, *MainFileEnd;
Chris Lattner0bd1c972007-10-16 21:07:07 +000067 SourceLocation LastIncLoc;
Mike Stump11289f42009-09-09 15:08:12 +000068
Ted Kremenek1b0ea822008-01-07 19:49:32 +000069 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
70 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
71 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Naroff13e74872008-05-06 18:26:51 +000072 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremenek1b0ea822008-01-07 19:49:32 +000073 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
74 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +000075 llvm::SmallVector<Stmt *, 32> Stmts;
76 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroffd9803712009-04-29 16:37:50 +000077 // Remember all the @protocol(<expr>) expressions.
78 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Fariborz Jahaniane3891582010-01-05 18:04:40 +000079
80 llvm::DenseSet<uint64_t> CopyDestroyCache;
81
Steve Naroffce8e8862008-03-15 00:55:56 +000082 unsigned NumObjCStringLiterals;
Mike Stump11289f42009-09-09 15:08:12 +000083
Steve Naroffdb1ab1c2007-10-23 23:50:29 +000084 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff7fa2f042007-11-15 10:28:18 +000085 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +000086 FunctionDecl *MsgSendStretFunctionDecl;
87 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanian4f76f222007-12-03 21:26:48 +000088 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +000089 FunctionDecl *GetClassFunctionDecl;
Steve Naroffb2f8ff12007-12-07 03:50:46 +000090 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff574440f2007-10-24 22:48:43 +000091 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff265a6b92007-11-08 14:30:50 +000092 FunctionDecl *CFStringFunctionDecl;
Steve Naroff17978c42008-03-11 17:37:02 +000093 FunctionDecl *SuperContructorFunctionDecl;
Mike Stump11289f42009-09-09 15:08:12 +000094
Steve Naroffa397efd2007-11-03 11:27:19 +000095 // ObjC string constant support.
Steve Naroff08899ff2008-04-15 22:42:06 +000096 VarDecl *ConstantStringClassReference;
Steve Naroffa397efd2007-11-03 11:27:19 +000097 RecordDecl *NSStringRecord;
Mike Stump11289f42009-09-09 15:08:12 +000098
Fariborz Jahanian19d42bf2008-01-16 00:09:11 +000099 // ObjC foreach break/continue generation support.
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +0000100 int BcLabelCount;
Mike Stump11289f42009-09-09 15:08:12 +0000101
Steve Naroff7fa2f042007-11-15 10:28:18 +0000102 // Needed for super.
Steve Naroff677ab3a2008-10-27 17:20:55 +0000103 ObjCMethodDecl *CurMethodDef;
Steve Naroff7fa2f042007-11-15 10:28:18 +0000104 RecordDecl *SuperStructDecl;
Steve Naroffce8e8862008-03-15 00:55:56 +0000105 RecordDecl *ConstantStringDecl;
Mike Stump11289f42009-09-09 15:08:12 +0000106
Steve Naroffd9803712009-04-29 16:37:50 +0000107 TypeDecl *ProtocolTypeDecl;
108 QualType getProtocolType();
Mike Stump11289f42009-09-09 15:08:12 +0000109
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000110 // Needed for header files being rewritten
111 bool IsHeader;
Mike Stump11289f42009-09-09 15:08:12 +0000112
Steve Narofff9e7c902008-03-28 22:26:09 +0000113 std::string InFileName;
Eli Friedman94cf21e2009-05-18 22:20:00 +0000114 llvm::raw_ostream* OutFile;
Eli Friedmanf22439a2009-05-18 22:39:16 +0000115
116 bool SilenceRewriteMacroWarning;
Fariborz Jahanianbc6811c2010-01-07 22:51:18 +0000117 bool objc_impl_method;
Eli Friedmanf22439a2009-05-18 22:39:16 +0000118
Steve Naroff00a31762008-03-27 22:29:16 +0000119 std::string Preamble;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000120
121 // Block expressions.
122 llvm::SmallVector<BlockExpr *, 32> Blocks;
Fariborz Jahanian8652be02010-02-24 22:48:18 +0000123 llvm::SmallVector<int, 32> InnerDeclRefsCount;
124 llvm::SmallVector<BlockDeclRefExpr *, 32> InnerDeclRefs;
125
Steve Naroff677ab3a2008-10-27 17:20:55 +0000126 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
127 llvm::DenseMap<BlockDeclRefExpr *, CallExpr *> BlockCallExprs;
Mike Stump11289f42009-09-09 15:08:12 +0000128
Steve Naroff677ab3a2008-10-27 17:20:55 +0000129 // Block related declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +0000130 llvm::SmallVector<ValueDecl *, 8> BlockByCopyDecls;
131 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
132 llvm::SmallVector<ValueDecl *, 8> BlockByRefDecls;
133 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +0000134 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000135 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
136
137 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
138
Steve Naroff4588d0f2008-12-04 16:24:46 +0000139 // This maps a property to it's assignment statement.
140 llvm::DenseMap<ObjCPropertyRefExpr *, BinaryOperator *> PropSetters;
Steve Naroff1042ff32008-12-08 16:43:47 +0000141 // This maps a property to it's synthesied message expression.
142 // This allows us to rewrite chained getters (e.g. o.a.b.c).
143 llvm::DenseMap<ObjCPropertyRefExpr *, Stmt *> PropGetters;
Mike Stump11289f42009-09-09 15:08:12 +0000144
Steve Naroff22216db2008-12-04 23:50:32 +0000145 // This maps an original source AST to it's rewritten form. This allows
146 // us to avoid rewriting the same node twice (which is very uncommon).
147 // This is needed to support some of the exotic property rewriting.
148 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Narofff326f402008-12-03 00:56:33 +0000149
Steve Naroff677ab3a2008-10-27 17:20:55 +0000150 FunctionDecl *CurFunctionDef;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000151 FunctionDecl *CurFunctionDeclToDeclareForBlock;
Steve Naroffd8907b72008-10-29 18:15:37 +0000152 VarDecl *GlobalVarDecl;
Mike Stump11289f42009-09-09 15:08:12 +0000153
Steve Naroff08628db2008-12-09 12:56:34 +0000154 bool DisableReplaceStmt;
Mike Stump11289f42009-09-09 15:08:12 +0000155
Fariborz Jahanian93191af2007-10-18 19:23:00 +0000156 static const int OBJC_ABI_VERSION =7 ;
Chris Lattnere99c8322007-10-11 00:43:27 +0000157 public:
Ted Kremenek380df932008-05-31 20:11:04 +0000158 virtual void Initialize(ASTContext &context);
159
Chris Lattner3c799d72007-10-24 17:06:59 +0000160 // Top Level Driver code.
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000161 virtual void HandleTopLevelDecl(DeclGroupRef D) {
162 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I)
163 HandleTopLevelSingleDecl(*I);
164 }
165 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000166 void HandleDeclInMainFile(Decl *D);
Eli Friedman94cf21e2009-05-18 22:20:00 +0000167 RewriteObjC(std::string inFile, llvm::raw_ostream *OS,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000168 Diagnostic &D, const LangOptions &LOpts,
169 bool silenceMacroWarn);
Ted Kremenek6231e7e2008-08-08 04:15:52 +0000170
171 ~RewriteObjC() {}
Mike Stump11289f42009-09-09 15:08:12 +0000172
Chris Lattnercf169832009-03-28 04:11:33 +0000173 virtual void HandleTranslationUnit(ASTContext &C);
Mike Stump11289f42009-09-09 15:08:12 +0000174
Fariborz Jahaniana7e1dcd2010-02-05 16:43:40 +0000175 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff22216db2008-12-04 23:50:32 +0000176 Stmt *ReplacingStmt = ReplacedNodes[Old];
Mike Stump11289f42009-09-09 15:08:12 +0000177
Steve Naroff22216db2008-12-04 23:50:32 +0000178 if (ReplacingStmt)
179 return; // We can't rewrite the same node twice.
Chris Lattner2e0d2602008-01-31 19:37:57 +0000180
Steve Naroff08628db2008-12-09 12:56:34 +0000181 if (DisableReplaceStmt)
182 return; // Used when rewriting the assignment of a property setter.
183
Steve Naroff22216db2008-12-04 23:50:32 +0000184 // If replacement succeeded or warning disabled return with no warning.
Fariborz Jahaniana7e1dcd2010-02-05 16:43:40 +0000185 if (!Rewrite.ReplaceStmt(Old, New)) {
Steve Naroff22216db2008-12-04 23:50:32 +0000186 ReplacedNodes[Old] = New;
187 return;
188 }
189 if (SilenceRewriteMacroWarning)
190 return;
Chris Lattner8488c822008-11-18 07:04:44 +0000191 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
192 << Old->getSourceRange();
Chris Lattner2e0d2602008-01-31 19:37:57 +0000193 }
Steve Naroff08628db2008-12-09 12:56:34 +0000194
195 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
196 // Measaure the old text.
197 int Size = Rewrite.getRangeSize(SrcRange);
198 if (Size == -1) {
199 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
200 << Old->getSourceRange();
201 return;
202 }
203 // Get the new text.
204 std::string SStr;
205 llvm::raw_string_ostream S(SStr);
Chris Lattnerc61089a2009-06-30 01:26:17 +0000206 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
Steve Naroff08628db2008-12-09 12:56:34 +0000207 const std::string &Str = S.str();
208
209 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbardec484a2009-08-19 19:10:30 +0000210 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroff08628db2008-12-09 12:56:34 +0000211 ReplacedNodes[Old] = New;
212 return;
213 }
214 if (SilenceRewriteMacroWarning)
215 return;
216 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
217 << Old->getSourceRange();
218 }
219
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000220 void InsertText(SourceLocation Loc, llvm::StringRef Str,
Steve Naroff00a31762008-03-27 22:29:16 +0000221 bool InsertAfter = true) {
Chris Lattner9cc55f52008-01-31 19:51:04 +0000222 // If insertion succeeded or warning disabled return with no warning.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000223 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
Chris Lattner1780a852008-01-31 19:42:41 +0000224 SilenceRewriteMacroWarning)
225 return;
Mike Stump11289f42009-09-09 15:08:12 +0000226
Chris Lattner1780a852008-01-31 19:42:41 +0000227 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
228 }
Mike Stump11289f42009-09-09 15:08:12 +0000229
Chris Lattner9cc55f52008-01-31 19:51:04 +0000230 void RemoveText(SourceLocation Loc, unsigned StrLen) {
231 // If removal succeeded or warning disabled return with no warning.
232 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
233 return;
Mike Stump11289f42009-09-09 15:08:12 +0000234
Chris Lattner9cc55f52008-01-31 19:51:04 +0000235 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
236 }
Chris Lattner3c799d72007-10-24 17:06:59 +0000237
Chris Lattner9cc55f52008-01-31 19:51:04 +0000238 void ReplaceText(SourceLocation Start, unsigned OrigLength,
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000239 llvm::StringRef Str) {
Chris Lattner9cc55f52008-01-31 19:51:04 +0000240 // If removal succeeded or warning disabled return with no warning.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000241 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
Chris Lattner9cc55f52008-01-31 19:51:04 +0000242 SilenceRewriteMacroWarning)
243 return;
Mike Stump11289f42009-09-09 15:08:12 +0000244
Chris Lattner9cc55f52008-01-31 19:51:04 +0000245 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
246 }
Mike Stump11289f42009-09-09 15:08:12 +0000247
Chris Lattner3c799d72007-10-24 17:06:59 +0000248 // Syntactic Rewriting.
Steve Narofff36987c2007-11-04 22:37:50 +0000249 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian80258362008-01-19 00:30:35 +0000250 void RewriteInclude();
Chris Lattner3c799d72007-10-24 17:06:59 +0000251 void RewriteTabs();
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000252 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffc038b3a2008-12-02 17:36:43 +0000253 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
254 ObjCImplementationDecl *IMD,
255 ObjCCategoryImplDecl *CID);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000256 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000257 void RewriteImplementationDecl(Decl *Dcl);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000258 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000259 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
260 const FunctionType *&FPRetType);
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +0000261 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
262 ValueDecl *VD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000263 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
264 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
265 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
266 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000267 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000268 void RewriteFunctionDecl(FunctionDecl *FD);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000269 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000270 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +0000271 void RewriteTypeOfDecl(VarDecl *VD);
Steve Naroff873bd842008-07-29 18:15:38 +0000272 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroff50d42052007-11-01 13:24:47 +0000273 bool needToScanForQualifiers(QualType T);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000274 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff7fa2f042007-11-15 10:28:18 +0000275 QualType getSuperStructType();
Steve Naroffce8e8862008-03-15 00:55:56 +0000276 QualType getConstantStringStructType();
Steve Naroffcd92aeb2008-05-31 14:15:04 +0000277 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Mike Stump11289f42009-09-09 15:08:12 +0000278
Chris Lattner3c799d72007-10-24 17:06:59 +0000279 // Expression Rewriting.
Steve Naroff20113382007-11-09 15:20:18 +0000280 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroff4588d0f2008-12-04 16:24:46 +0000281 void CollectPropertySetters(Stmt *S);
Mike Stump11289f42009-09-09 15:08:12 +0000282
Steve Naroff1042ff32008-12-08 16:43:47 +0000283 Stmt *CurrentBody;
284 ParentMap *PropParentMap; // created lazily.
Mike Stump11289f42009-09-09 15:08:12 +0000285
Chris Lattner69534692007-10-24 16:57:36 +0000286 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Fariborz Jahanian80fadb52010-02-05 01:35:00 +0000287 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart,
288 bool &replaced);
289 Stmt *RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced);
Steve Naroff4588d0f2008-12-04 16:24:46 +0000290 Stmt *RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr);
Mike Stump11289f42009-09-09 15:08:12 +0000291 Stmt *RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroff08628db2008-12-09 12:56:34 +0000292 SourceRange SrcRange);
Steve Naroffe4f9b232007-11-05 14:50:49 +0000293 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner69534692007-10-24 16:57:36 +0000294 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffa397efd2007-11-03 11:27:19 +0000295 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian33c0e812007-12-07 18:47:10 +0000296 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffec60b432009-12-05 21:43:12 +0000297 void WarnAboutReturnGotoStmts(Stmt *S);
298 void HasReturnStmts(Stmt *S, bool &hasReturns);
299 void RewriteTryReturnStmts(Stmt *S);
300 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000301 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian284011b2008-01-29 22:59:37 +0000302 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000303 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
304 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
305 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattnera779d692008-01-31 05:10:40 +0000306 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
307 SourceLocation OrigEnd);
Mike Stump11289f42009-09-09 15:08:12 +0000308 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +0000309 Expr **args, unsigned nargs,
310 SourceLocation StartLoc=SourceLocation(),
311 SourceLocation EndLoc=SourceLocation());
312 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
313 SourceLocation StartLoc=SourceLocation(),
314 SourceLocation EndLoc=SourceLocation());
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +0000315 Stmt *RewriteBreakStmt(BreakStmt *S);
316 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian965a8962008-01-08 22:06:28 +0000317 void SynthCountByEnumWithState(std::string &buf);
Mike Stump11289f42009-09-09 15:08:12 +0000318
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000319 void SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +0000320 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +0000321 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +0000322 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +0000323 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000324 void SynthGetClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +0000325 void SynthGetMetaClassFunctionDecl();
Fariborz Jahanian31e18502007-12-04 21:47:40 +0000326 void SynthSelGetUidFunctionDecl();
Steve Naroff17978c42008-03-11 17:37:02 +0000327 void SynthSuperContructorFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000328
Chris Lattner3c799d72007-10-24 17:06:59 +0000329 // Metadata emission.
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000330 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +0000331 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000332
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000333 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +0000334 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000335
Douglas Gregor29bd76f2009-04-23 01:02:12 +0000336 template<typename MethodIterator>
337 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
338 MethodIterator MethodEnd,
Fariborz Jahanian3df412a2007-10-25 00:14:44 +0000339 bool IsInstanceMethod,
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +0000340 const char *prefix,
Chris Lattner211f8b82007-10-25 17:07:24 +0000341 const char *ClassName,
342 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000343
Steve Naroffd9803712009-04-29 16:37:50 +0000344 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
345 const char *prefix,
346 const char *ClassName,
347 std::string &Result);
348 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
Mike Stump11289f42009-09-09 15:08:12 +0000349 const char *prefix,
Steve Naroffd9803712009-04-29 16:37:50 +0000350 const char *ClassName,
351 std::string &Result);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000352 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +0000353 std::string &Result);
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000354 void SynthesizeIvarOffsetComputation(ObjCContainerDecl *IDecl,
Mike Stump11289f42009-09-09 15:08:12 +0000355 ObjCIvarDecl *ivar,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +0000356 std::string &Result);
Steve Narofff8cfd162008-11-13 20:07:04 +0000357 void RewriteImplementations();
358 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000359
Steve Naroff677ab3a2008-10-27 17:20:55 +0000360 // Block rewriting.
Mike Stump11289f42009-09-09 15:08:12 +0000361 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000362 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
Mike Stump11289f42009-09-09 15:08:12 +0000363
Steve Naroff677ab3a2008-10-27 17:20:55 +0000364 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
365 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
Mike Stump11289f42009-09-09 15:08:12 +0000366
367 // Block specific rewrite rules.
Steve Naroff677ab3a2008-10-27 17:20:55 +0000368 void RewriteBlockCall(CallExpr *Exp);
369 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian02e07732009-12-23 02:07:37 +0000370 void RewriteByRefVar(VarDecl *VD);
Fariborz Jahaniane3891582010-01-05 18:04:40 +0000371 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +0000372 Stmt *RewriteBlockDeclRefExpr(Expr *VD);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000373 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Mike Stump11289f42009-09-09 15:08:12 +0000374
375 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Steve Naroff677ab3a2008-10-27 17:20:55 +0000376 const char *funcName, std::string Tag);
Mike Stump11289f42009-09-09 15:08:12 +0000377 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Steve Naroff677ab3a2008-10-27 17:20:55 +0000378 const char *funcName, std::string Tag);
Steve Naroff30484702009-12-06 21:14:13 +0000379 std::string SynthesizeBlockImpl(BlockExpr *CE,
380 std::string Tag, std::string Desc);
381 std::string SynthesizeBlockDescriptor(std::string DescTag,
382 std::string ImplTag,
383 int i, const char *funcName,
384 unsigned hasCopy);
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +0000385 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000386 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000387 const char *FunName);
Steve Naroffe70a52a2009-12-05 15:55:59 +0000388 void RewriteRecordBody(RecordDecl *RD);
Mike Stump11289f42009-09-09 15:08:12 +0000389
Steve Naroff677ab3a2008-10-27 17:20:55 +0000390 void CollectBlockDeclRefInfo(BlockExpr *Exp);
391 void GetBlockCallExprs(Stmt *S);
392 void GetBlockDeclRefExprs(Stmt *S);
Fariborz Jahanian8652be02010-02-24 22:48:18 +0000393 void GetInnerBlockDeclRefExprs(Stmt *S,
394 llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
395 llvm::SmallPtrSet<ValueDecl *, 8> &InnerBlockValueDecls);
Mike Stump11289f42009-09-09 15:08:12 +0000396
Steve Naroff677ab3a2008-10-27 17:20:55 +0000397 // We avoid calling Type::isBlockPointerType(), since it operates on the
398 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek5a201952009-02-07 01:47:29 +0000399 bool isTopLevelBlockPointerType(QualType T) {
400 return isa<BlockPointerType>(T);
401 }
Mike Stump11289f42009-09-09 15:08:12 +0000402
Steve Naroff677ab3a2008-10-27 17:20:55 +0000403 // FIXME: This predicate seems like it would be useful to add to ASTContext.
404 bool isObjCType(QualType T) {
405 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
406 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000407
Steve Naroff677ab3a2008-10-27 17:20:55 +0000408 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000409
Steve Naroff677ab3a2008-10-27 17:20:55 +0000410 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
411 OCT == Context->getCanonicalType(Context->getObjCClassType()))
412 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000413
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000414 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump11289f42009-09-09 15:08:12 +0000415 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Narofffb4330f2009-06-17 22:40:22 +0000416 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff677ab3a2008-10-27 17:20:55 +0000417 return true;
418 }
419 return false;
420 }
421 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Ted Kremenek5a201952009-02-07 01:47:29 +0000422 void GetExtentOfArgList(const char *Name, const char *&LParen,
423 const char *&RParen);
Steve Naroffc989a7b2008-11-03 23:29:32 +0000424 void RewriteCastExpr(CStyleCastExpr *CE);
Mike Stump11289f42009-09-09 15:08:12 +0000425
Steve Narofff4b992a2008-10-28 20:29:00 +0000426 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Fariborz Jahanian8652be02010-02-24 22:48:18 +0000427 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
428 const llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs);
Mike Stump11289f42009-09-09 15:08:12 +0000429
Steve Naroffd9803712009-04-29 16:37:50 +0000430 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump11289f42009-09-09 15:08:12 +0000431 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroffd9803712009-04-29 16:37:50 +0000432 if (From[i] == '"')
433 To += "\\\"";
434 else
435 To += From[i];
436 }
437 }
Chris Lattnere99c8322007-10-11 00:43:27 +0000438 };
John McCall97513962010-01-15 18:39:57 +0000439
440 // Helper function: create a CStyleCastExpr with trivial type source info.
441 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
442 CastExpr::CastKind Kind, Expr *E) {
443 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
444 return new (Ctx) CStyleCastExpr(Ty, Kind, E, TInfo,
445 SourceLocation(), SourceLocation());
446 }
Chris Lattnere99c8322007-10-11 00:43:27 +0000447}
448
Mike Stump11289f42009-09-09 15:08:12 +0000449void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
450 NamedDecl *D) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000451 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000452 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +0000453 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +0000454 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff677ab3a2008-10-27 17:20:55 +0000455 // All the args are checked/rewritten. Don't call twice!
456 RewriteBlockPointerDecl(D);
457 break;
458 }
459 }
460}
461
462void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000463 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +0000464 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000465 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000466}
467
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000468static bool IsHeaderFile(const std::string &Filename) {
469 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump11289f42009-09-09 15:08:12 +0000470
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000471 if (DotPos == std::string::npos) {
472 // no file extension
Mike Stump11289f42009-09-09 15:08:12 +0000473 return false;
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000474 }
Mike Stump11289f42009-09-09 15:08:12 +0000475
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000476 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
477 // C header: .h
478 // C++ header: .hh or .H;
479 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump11289f42009-09-09 15:08:12 +0000480}
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000481
Eli Friedman94cf21e2009-05-18 22:20:00 +0000482RewriteObjC::RewriteObjC(std::string inFile, llvm::raw_ostream* OS,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000483 Diagnostic &D, const LangOptions &LOpts,
484 bool silenceMacroWarn)
485 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
486 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Narofff9e7c902008-03-28 22:26:09 +0000487 IsHeader = IsHeaderFile(inFile);
Mike Stump11289f42009-09-09 15:08:12 +0000488 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Steve Narofff9e7c902008-03-28 22:26:09 +0000489 "rewriting sub-expression within a macro (may not be correct)");
Mike Stump11289f42009-09-09 15:08:12 +0000490 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek5a201952009-02-07 01:47:29 +0000491 "rewriter doesn't support user-specified control flow semantics "
492 "for @try/@finally (code may not execute properly)");
Steve Narofff9e7c902008-03-28 22:26:09 +0000493}
494
Eli Friedmana63ab2d2009-05-18 22:29:17 +0000495ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
496 llvm::raw_ostream* OS,
Mike Stump11289f42009-09-09 15:08:12 +0000497 Diagnostic &Diags,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000498 const LangOptions &LOpts,
499 bool SilenceRewriteMacroWarning) {
500 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere9c810c2007-11-30 22:25:36 +0000501}
Chris Lattnere99c8322007-10-11 00:43:27 +0000502
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000503void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner187f6262008-01-31 19:38:44 +0000504 Context = &context;
505 SM = &Context->getSourceManager();
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +0000506 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner187f6262008-01-31 19:38:44 +0000507 MsgSendFunctionDecl = 0;
508 MsgSendSuperFunctionDecl = 0;
509 MsgSendStretFunctionDecl = 0;
510 MsgSendSuperStretFunctionDecl = 0;
511 MsgSendFpretFunctionDecl = 0;
512 GetClassFunctionDecl = 0;
513 GetMetaClassFunctionDecl = 0;
514 SelGetUidFunctionDecl = 0;
515 CFStringFunctionDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000516 ConstantStringClassReference = 0;
517 NSStringRecord = 0;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000518 CurMethodDef = 0;
519 CurFunctionDef = 0;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000520 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000521 GlobalVarDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000522 SuperStructDecl = 0;
Steve Naroffd9803712009-04-29 16:37:50 +0000523 ProtocolTypeDecl = 0;
Steve Naroff60a9ef62008-03-27 22:59:54 +0000524 ConstantStringDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000525 BcLabelCount = 0;
Steve Naroff17978c42008-03-11 17:37:02 +0000526 SuperContructorFunctionDecl = 0;
Steve Naroffce8e8862008-03-15 00:55:56 +0000527 NumObjCStringLiterals = 0;
Steve Narofff1ab6002008-12-08 20:01:41 +0000528 PropParentMap = 0;
529 CurrentBody = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000530 DisableReplaceStmt = false;
Fariborz Jahanianbc6811c2010-01-07 22:51:18 +0000531 objc_impl_method = false;
Mike Stump11289f42009-09-09 15:08:12 +0000532
Chris Lattner187f6262008-01-31 19:38:44 +0000533 // Get the ID and start/end of the main file.
534 MainFileID = SM->getMainFileID();
535 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
536 MainFileStart = MainBuf->getBufferStart();
537 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000538
Chris Lattner184e65d2009-04-14 23:22:57 +0000539 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump11289f42009-09-09 15:08:12 +0000540
Chris Lattner187f6262008-01-31 19:38:44 +0000541 // declaring objc_selector outside the parameter list removes a silly
542 // scope related warning...
Steve Naroff00a31762008-03-27 22:29:16 +0000543 if (IsHeader)
Steve Narofffcc6fd52009-02-03 20:39:18 +0000544 Preamble = "#pragma once\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000545 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff6ab6dc72008-12-23 20:11:22 +0000546 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroff00a31762008-03-27 22:29:16 +0000547 Preamble += "struct objc_object *superClass; ";
Steve Naroff17978c42008-03-11 17:37:02 +0000548 if (LangOpts.Microsoft) {
549 // Add a constructor for creating temporary objects.
Ted Kremenek5a201952009-02-07 01:47:29 +0000550 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
551 ": ";
Steve Naroff00a31762008-03-27 22:29:16 +0000552 Preamble += "object(o), superClass(s) {} ";
Steve Naroff17978c42008-03-11 17:37:02 +0000553 }
Steve Naroff00a31762008-03-27 22:29:16 +0000554 Preamble += "};\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000555 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
556 Preamble += "typedef struct objc_object Protocol;\n";
557 Preamble += "#define _REWRITER_typedef_Protocol\n";
558 Preamble += "#endif\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000559 if (LangOpts.Microsoft) {
560 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
561 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
562 } else
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000563 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000564 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroff00a31762008-03-27 22:29:16 +0000565 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000566 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroff00a31762008-03-27 22:29:16 +0000567 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000568 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroff00a31762008-03-27 22:29:16 +0000569 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000570 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroff00a31762008-03-27 22:29:16 +0000571 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000572 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroff00a31762008-03-27 22:29:16 +0000573 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000574 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroff00a31762008-03-27 22:29:16 +0000575 Preamble += "(const char *);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000576 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroff00a31762008-03-27 22:29:16 +0000577 Preamble += "(const char *);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000578 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
579 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
580 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
581 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
582 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroffd30f8c52008-05-09 21:17:56 +0000583 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff8dd15252008-07-16 18:58:11 +0000584 // @synchronized hooks.
Steve Narofff122ff02008-12-08 17:30:33 +0000585 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
586 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
587 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000588 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
589 Preamble += "struct __objcFastEnumerationState {\n\t";
590 Preamble += "unsigned long state;\n\t";
Steve Naroff4dbab8a2008-04-04 22:58:22 +0000591 Preamble += "void **itemsPtr;\n\t";
Steve Naroff00a31762008-03-27 22:29:16 +0000592 Preamble += "unsigned long *mutationsPtr;\n\t";
593 Preamble += "unsigned long extra[5];\n};\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000594 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000595 Preamble += "#define __FASTENUMERATIONSTATE\n";
596 Preamble += "#endif\n";
597 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
598 Preamble += "struct __NSConstantStringImpl {\n";
599 Preamble += " int *isa;\n";
600 Preamble += " int flags;\n";
601 Preamble += " char *str;\n";
602 Preamble += " long length;\n";
603 Preamble += "};\n";
Steve Naroffdd514e02008-08-05 20:04:48 +0000604 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
605 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
606 Preamble += "#else\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000607 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroffdd514e02008-08-05 20:04:48 +0000608 Preamble += "#endif\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000609 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
610 Preamble += "#endif\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000611 // Blocks preamble.
612 Preamble += "#ifndef BLOCK_IMPL\n";
613 Preamble += "#define BLOCK_IMPL\n";
614 Preamble += "struct __block_impl {\n";
615 Preamble += " void *isa;\n";
616 Preamble += " int Flags;\n";
Steve Naroff30484702009-12-06 21:14:13 +0000617 Preamble += " int Reserved;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000618 Preamble += " void *FuncPtr;\n";
619 Preamble += "};\n";
Steve Naroff61d879e2008-12-16 15:50:30 +0000620 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
Steve Naroff287a2bf2009-12-06 01:52:22 +0000621 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000622 Preamble += "extern \"C\" __declspec(dllexport) "
623 "void _Block_object_assign(void *, const void *, const int);\n";
Steve Naroff2b3843d2009-12-06 01:33:56 +0000624 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
625 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
626 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
627 Preamble += "#else\n";
Steve Naroff7bf01ea2010-01-05 18:09:31 +0000628 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
629 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
Steve Naroff2b3843d2009-12-06 01:33:56 +0000630 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
631 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
632 Preamble += "#endif\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000633 Preamble += "#endif\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000634 if (LangOpts.Microsoft) {
Steve Narofff122ff02008-12-08 17:30:33 +0000635 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
636 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000637 Preamble += "#define __attribute__(X)\n";
Fariborz Jahanianf0462ff2010-01-15 22:29:39 +0000638 Preamble += "#define __weak\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000639 }
Fariborz Jahanian7fac6552010-01-05 19:21:35 +0000640 else {
Fariborz Jahanian02e07732009-12-23 02:07:37 +0000641 Preamble += "#define __block\n";
Fariborz Jahanian7fac6552010-01-05 19:21:35 +0000642 Preamble += "#define __weak\n";
643 }
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000644 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long) &((TYPE *)0)->MEMBER)\n";
Chris Lattner187f6262008-01-31 19:38:44 +0000645}
646
647
Chris Lattner3c799d72007-10-24 17:06:59 +0000648//===----------------------------------------------------------------------===//
649// Top Level Driver Code
650//===----------------------------------------------------------------------===//
651
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000652void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremenek31e7f0f2010-02-05 21:28:51 +0000653 if (Diags.hasErrorOccurred())
654 return;
655
Chris Lattner0bd1c972007-10-16 21:07:07 +0000656 // Two cases: either the decl could be in the main file, or it could be in a
657 // #included file. If the former, rewrite it now. If the later, check to see
658 // if we rewrote the #include/#import.
659 SourceLocation Loc = D->getLocation();
Chris Lattner8a425862009-01-16 07:36:28 +0000660 Loc = SM->getInstantiationLoc(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000661
Chris Lattner0bd1c972007-10-16 21:07:07 +0000662 // If this is for a builtin, ignore it.
663 if (Loc.isInvalid()) return;
664
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000665 // Look for built-in declarations that we need to refer during the rewrite.
666 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000667 RewriteFunctionDecl(FD);
Steve Naroff08899ff2008-04-15 22:42:06 +0000668 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffa397efd2007-11-03 11:27:19 +0000669 // declared in <Foundation/NSString.h>
Chris Lattner86d7d912008-11-24 03:54:41 +0000670 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroffa397efd2007-11-03 11:27:19 +0000671 ConstantStringClassReference = FVD;
672 return;
673 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000674 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroff161a92b2007-10-26 20:53:56 +0000675 RewriteInterfaceDecl(MD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000676 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000677 RewriteCategoryDecl(CD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000678 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Narofff921385f2007-10-30 16:42:30 +0000679 RewriteProtocolDecl(PD);
Mike Stump11289f42009-09-09 15:08:12 +0000680 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000681 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000682 RewriteForwardProtocolDecl(FP);
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000683 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
684 // Recurse into linkage specifications
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000685 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
686 DIEnd = LSD->decls_end();
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000687 DI != DIEnd; ++DI)
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000688 HandleTopLevelSingleDecl(*DI);
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000689 }
Chris Lattner3c799d72007-10-24 17:06:59 +0000690 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekd61ed3b2008-04-14 21:24:13 +0000691 if (SM->isFromMainFile(Loc))
Chris Lattner0bd1c972007-10-16 21:07:07 +0000692 return HandleDeclInMainFile(D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000693}
694
Chris Lattner3c799d72007-10-24 17:06:59 +0000695//===----------------------------------------------------------------------===//
696// Syntactic (non-AST) Rewriting Code
697//===----------------------------------------------------------------------===//
698
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000699void RewriteObjC::RewriteInclude() {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000700 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Fariborz Jahanian80258362008-01-19 00:30:35 +0000701 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
702 const char *MainBufStart = MainBuf.first;
703 const char *MainBufEnd = MainBuf.second;
704 size_t ImportLen = strlen("import");
Mike Stump11289f42009-09-09 15:08:12 +0000705
Fariborz Jahanian137d6932008-01-19 01:03:17 +0000706 // Loop over the whole file, looking for includes.
Fariborz Jahanian80258362008-01-19 00:30:35 +0000707 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
708 if (*BufPtr == '#') {
709 if (++BufPtr == MainBufEnd)
710 return;
711 while (*BufPtr == ' ' || *BufPtr == '\t')
712 if (++BufPtr == MainBufEnd)
713 return;
714 if (!strncmp(BufPtr, "import", ImportLen)) {
715 // replace import with include
Mike Stump11289f42009-09-09 15:08:12 +0000716 SourceLocation ImportLoc =
Fariborz Jahanian80258362008-01-19 00:30:35 +0000717 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000718 ReplaceText(ImportLoc, ImportLen, "include");
Fariborz Jahanian80258362008-01-19 00:30:35 +0000719 BufPtr += ImportLen;
720 }
721 }
722 }
Chris Lattner0bd1c972007-10-16 21:07:07 +0000723}
724
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000725void RewriteObjC::RewriteTabs() {
Chris Lattner3c799d72007-10-24 17:06:59 +0000726 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
727 const char *MainBufStart = MainBuf.first;
728 const char *MainBufEnd = MainBuf.second;
Mike Stump11289f42009-09-09 15:08:12 +0000729
Chris Lattner3c799d72007-10-24 17:06:59 +0000730 // Loop over the whole file, looking for tabs.
731 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
732 if (*BufPtr != '\t')
733 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000734
Chris Lattner3c799d72007-10-24 17:06:59 +0000735 // Okay, we found a tab. This tab will turn into at least one character,
736 // but it depends on which 'virtual column' it is in. Compute that now.
737 unsigned VCol = 0;
738 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
739 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
740 ++VCol;
Mike Stump11289f42009-09-09 15:08:12 +0000741
Chris Lattner3c799d72007-10-24 17:06:59 +0000742 // Okay, now that we know the virtual column, we know how many spaces to
743 // insert. We assume 8-character tab-stops.
744 unsigned Spaces = 8-(VCol & 7);
Mike Stump11289f42009-09-09 15:08:12 +0000745
Chris Lattner3c799d72007-10-24 17:06:59 +0000746 // Get the location of the tab.
Chris Lattnerd32480d2009-01-17 06:22:33 +0000747 SourceLocation TabLoc = SM->getLocForStartOfFile(MainFileID);
748 TabLoc = TabLoc.getFileLocWithOffset(BufPtr-MainBufStart);
Mike Stump11289f42009-09-09 15:08:12 +0000749
Chris Lattner3c799d72007-10-24 17:06:59 +0000750 // Rewrite the single tab character into a sequence of spaces.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000751 ReplaceText(TabLoc, 1, llvm::StringRef(" ", Spaces));
Chris Lattner3c799d72007-10-24 17:06:59 +0000752 }
Chris Lattner16a0de42007-10-11 18:38:32 +0000753}
754
Steve Naroff9af94912008-12-02 15:48:25 +0000755static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
756 ObjCIvarDecl *OID) {
757 std::string S;
758 S = "((struct ";
759 S += ClassDecl->getIdentifier()->getName();
760 S += "_IMPL *)self)->";
Daniel Dunbar70e7ead2009-10-18 20:26:27 +0000761 S += OID->getName();
Steve Naroff9af94912008-12-02 15:48:25 +0000762 return S;
763}
764
Steve Naroffc038b3a2008-12-02 17:36:43 +0000765void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
766 ObjCImplementationDecl *IMD,
767 ObjCCategoryImplDecl *CID) {
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000768 static bool objcGetPropertyDefined = false;
769 static bool objcSetPropertyDefined = false;
Steve Naroffe1908e32008-12-01 20:33:01 +0000770 SourceLocation startLoc = PID->getLocStart();
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000771 InsertText(startLoc, "// ");
Steve Naroff9af94912008-12-02 15:48:25 +0000772 const char *startBuf = SM->getCharacterData(startLoc);
773 assert((*startBuf == '@') && "bogus @synthesize location");
774 const char *semiBuf = strchr(startBuf, ';');
775 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek5a201952009-02-07 01:47:29 +0000776 SourceLocation onePastSemiLoc =
777 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroff9af94912008-12-02 15:48:25 +0000778
779 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
780 return; // FIXME: is this correct?
Mike Stump11289f42009-09-09 15:08:12 +0000781
Steve Naroff9af94912008-12-02 15:48:25 +0000782 // Generate the 'getter' function.
Steve Naroff9af94912008-12-02 15:48:25 +0000783 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroff9af94912008-12-02 15:48:25 +0000784 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroff9af94912008-12-02 15:48:25 +0000785 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000786
Steve Naroff003d00e2008-12-02 16:05:55 +0000787 if (!OID)
788 return;
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000789 unsigned Attributes = PD->getPropertyAttributes();
790 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
791 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
792 ObjCPropertyDecl::OBJC_PR_copy));
Steve Naroff003d00e2008-12-02 16:05:55 +0000793 std::string Getr;
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000794 if (GenGetProperty && !objcGetPropertyDefined) {
795 objcGetPropertyDefined = true;
796 // FIXME. Is this attribute correct in all cases?
797 Getr = "\nextern \"C\" __declspec(dllimport) "
798 "id objc_getProperty(id, SEL, long, bool);\n";
799 }
Steve Naroff003d00e2008-12-02 16:05:55 +0000800 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
801 Getr += "{ ";
802 // Synthesize an explicit cast to gain access to the ivar.
Steve Naroff06297042008-12-02 17:54:50 +0000803 // See objc-act.c:objc_synthesize_new_getter() for details.
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000804 if (GenGetProperty) {
805 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
806 Getr += "typedef ";
807 const FunctionType *FPRetType = 0;
808 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
809 FPRetType);
810 Getr += " _TYPE";
811 if (FPRetType) {
812 Getr += ")"; // close the precedence "scope" for "*".
813
814 // Now, emit the argument types (if any).
815 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
816 Getr += "(";
817 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
818 if (i) Getr += ", ";
819 std::string ParamStr = FT->getArgType(i).getAsString();
820 Getr += ParamStr;
821 }
822 if (FT->isVariadic()) {
823 if (FT->getNumArgs()) Getr += ", ";
824 Getr += "...";
825 }
826 Getr += ")";
827 } else
828 Getr += "()";
829 }
830 Getr += ";\n";
831 Getr += "return (_TYPE)";
832 Getr += "objc_getProperty(self, _cmd, ";
833 SynthesizeIvarOffsetComputation(ClassDecl, OID, Getr);
834 Getr += ", 1)";
835 }
836 else
837 Getr += "return " + getIvarAccessString(ClassDecl, OID);
Steve Naroff003d00e2008-12-02 16:05:55 +0000838 Getr += "; }";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000839 InsertText(onePastSemiLoc, Getr);
Steve Naroff9af94912008-12-02 15:48:25 +0000840 if (PD->isReadOnly())
841 return;
Mike Stump11289f42009-09-09 15:08:12 +0000842
Steve Naroff9af94912008-12-02 15:48:25 +0000843 // Generate the 'setter' function.
844 std::string Setr;
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000845 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
846 ObjCPropertyDecl::OBJC_PR_copy);
847 if (GenSetProperty && !objcSetPropertyDefined) {
848 objcSetPropertyDefined = true;
849 // FIXME. Is this attribute correct in all cases?
850 Setr = "\nextern \"C\" __declspec(dllimport) "
851 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
852 }
853
Steve Naroff9af94912008-12-02 15:48:25 +0000854 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroff9af94912008-12-02 15:48:25 +0000855 Setr += "{ ";
Steve Naroff003d00e2008-12-02 16:05:55 +0000856 // Synthesize an explicit cast to initialize the ivar.
Steve Narofff326f402008-12-03 00:56:33 +0000857 // See objc-act.c:objc_synthesize_new_setter() for details.
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000858 if (GenSetProperty) {
859 Setr += "objc_setProperty (self, _cmd, ";
860 SynthesizeIvarOffsetComputation(ClassDecl, OID, Setr);
861 Setr += ", (id)";
862 Setr += PD->getNameAsCString();
863 Setr += ", ";
864 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
865 Setr += "0, ";
866 else
867 Setr += "1, ";
868 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
869 Setr += "1)";
870 else
871 Setr += "0)";
872 }
873 else {
874 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
875 Setr += PD->getNameAsCString();
876 }
Steve Naroff003d00e2008-12-02 16:05:55 +0000877 Setr += "; }";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000878 InsertText(onePastSemiLoc, Setr);
Steve Naroffe1908e32008-12-01 20:33:01 +0000879}
Chris Lattner16a0de42007-10-11 18:38:32 +0000880
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000881void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattner3c799d72007-10-24 17:06:59 +0000882 // Get the start location and compute the semi location.
883 SourceLocation startLoc = ClassDecl->getLocation();
884 const char *startBuf = SM->getCharacterData(startLoc);
885 const char *semiPtr = strchr(startBuf, ';');
Mike Stump11289f42009-09-09 15:08:12 +0000886
Chris Lattner3c799d72007-10-24 17:06:59 +0000887 // Translate to typedef's that forward reference structs with the same name
888 // as the class. As a convenience, we include the original declaration
889 // as a comment.
890 std::string typedefString;
Fariborz Jahanian1c2cb6d2010-01-11 22:48:40 +0000891 typedefString += "// @class ";
892 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
893 I != E; ++I) {
894 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
895 typedefString += ForwardDecl->getNameAsString();
896 if (I+1 != E)
897 typedefString += ", ";
898 else
899 typedefString += ";\n";
900 }
901
Chris Lattner9ee23b72009-02-20 18:04:31 +0000902 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
903 I != E; ++I) {
Ted Kremenek9b124e12009-11-18 00:28:11 +0000904 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
Steve Naroff1b232132007-11-09 12:50:28 +0000905 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000906 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000907 typedefString += "\n";
908 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000909 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000910 typedefString += "\n";
Steve Naroff98eb8d12007-11-05 14:36:37 +0000911 typedefString += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000912 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000913 typedefString += ";\n#endif\n";
Steve Naroff574440f2007-10-24 22:48:43 +0000914 }
Mike Stump11289f42009-09-09 15:08:12 +0000915
Steve Naroff574440f2007-10-24 22:48:43 +0000916 // Replace the @class with typedefs corresponding to the classes.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000917 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
Chris Lattner3c799d72007-10-24 17:06:59 +0000918}
919
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000920void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahanianda8ec2b2010-01-21 17:36:00 +0000921 // When method is a synthesized one, such as a getter/setter there is
922 // nothing to rewrite.
923 if (Method->isSynthesized())
924 return;
Steve Naroff3ce37a62007-12-14 23:37:57 +0000925 SourceLocation LocStart = Method->getLocStart();
926 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000927
Chris Lattner88ea93e2009-02-04 01:06:56 +0000928 if (SM->getInstantiationLineNumber(LocEnd) >
929 SM->getInstantiationLineNumber(LocStart)) {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000930 InsertText(LocStart, "#if 0\n");
931 ReplaceText(LocEnd, 1, ";\n#endif\n");
Steve Naroff3ce37a62007-12-14 23:37:57 +0000932 } else {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000933 InsertText(LocStart, "// ");
Steve Naroff5448cf62007-10-30 13:30:57 +0000934 }
935}
936
Mike Stump11289f42009-09-09 15:08:12 +0000937void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahanianda8ec2b2010-01-21 17:36:00 +0000938 SourceLocation Loc = prop->getAtLoc();
Mike Stump11289f42009-09-09 15:08:12 +0000939
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000940 ReplaceText(Loc, 0, "// ");
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000941 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahaniane8a30162007-11-07 00:09:37 +0000942}
943
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000944void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000945 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000946
Steve Naroff5448cf62007-10-30 13:30:57 +0000947 // FIXME: handle category headers that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000948 ReplaceText(LocStart, 0, "// ");
Mike Stump11289f42009-09-09 15:08:12 +0000949
Fariborz Jahanian68ebe632010-02-10 01:15:09 +0000950 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
951 E = CatDecl->prop_end(); I != E; ++I)
952 RewriteProperty(*I);
953
Mike Stump11289f42009-09-09 15:08:12 +0000954 for (ObjCCategoryDecl::instmeth_iterator
955 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000956 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000957 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +0000958 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000959 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000960 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000961 RewriteMethodDeclaration(*I);
962
Steve Naroff5448cf62007-10-30 13:30:57 +0000963 // Lastly, comment out the @end.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000964 ReplaceText(CatDecl->getAtEndRange().getBegin(), 0, "// ");
Steve Naroff5448cf62007-10-30 13:30:57 +0000965}
966
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000967void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000968 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Mike Stump11289f42009-09-09 15:08:12 +0000969
Steve Narofff921385f2007-10-30 16:42:30 +0000970 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000971
Steve Narofff921385f2007-10-30 16:42:30 +0000972 // FIXME: handle protocol headers that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000973 ReplaceText(LocStart, 0, "// ");
Mike Stump11289f42009-09-09 15:08:12 +0000974
975 for (ObjCProtocolDecl::instmeth_iterator
976 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000977 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000978 RewriteMethodDeclaration(*I);
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000979 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000980 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000981 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000982 RewriteMethodDeclaration(*I);
983
Steve Narofff921385f2007-10-30 16:42:30 +0000984 // Lastly, comment out the @end.
Ted Kremenekc7c64312010-01-07 01:20:12 +0000985 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000986 ReplaceText(LocEnd, 0, "// ");
Steve Naroffa509f042007-11-14 15:03:57 +0000987
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000988 // Must comment out @optional/@required
989 const char *startBuf = SM->getCharacterData(LocStart);
990 const char *endBuf = SM->getCharacterData(LocEnd);
991 for (const char *p = startBuf; p < endBuf; p++) {
992 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
Steve Naroffa509f042007-11-14 15:03:57 +0000993 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000994 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
Mike Stump11289f42009-09-09 15:08:12 +0000995
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000996 }
997 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
Steve Naroffa509f042007-11-14 15:03:57 +0000998 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000999 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
Mike Stump11289f42009-09-09 15:08:12 +00001000
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +00001001 }
1002 }
Steve Narofff921385f2007-10-30 16:42:30 +00001003}
1004
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001005void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahanianda6165c2007-11-14 00:42:16 +00001006 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffc17b0562007-11-14 03:37:28 +00001007 if (LocStart.isInvalid())
1008 assert(false && "Invalid SourceLocation");
Fariborz Jahanianda6165c2007-11-14 00:42:16 +00001009 // FIXME: handle forward protocol that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001010 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanianda6165c2007-11-14 00:42:16 +00001011}
1012
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001013void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1014 const FunctionType *&FPRetType) {
1015 if (T->isObjCQualifiedIdType())
Fariborz Jahanian24cb52c2007-12-17 21:03:50 +00001016 ResultStr += "id";
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001017 else if (T->isFunctionPointerType() ||
1018 T->isBlockPointerType()) {
Steve Naroffb067bbd2008-07-16 14:40:40 +00001019 // needs special handling, since pointer-to-functions have special
1020 // syntax (where a decaration models use).
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001021 QualType retType = T;
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001022 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001023 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001024 PointeeTy = PT->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001025 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001026 PointeeTy = BPT->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00001027 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001028 ResultStr += FPRetType->getResultType().getAsString();
1029 ResultStr += "(*";
Steve Naroffb067bbd2008-07-16 14:40:40 +00001030 }
1031 } else
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001032 ResultStr += T.getAsString();
1033}
1034
1035void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
1036 std::string &ResultStr) {
1037 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1038 const FunctionType *FPRetType = 0;
1039 ResultStr += "\nstatic ";
1040 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
Fariborz Jahanian7262fca2008-01-10 01:39:52 +00001041 ResultStr += " ";
Mike Stump11289f42009-09-09 15:08:12 +00001042
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001043 // Unique method name
Fariborz Jahanian56338352007-11-13 21:02:00 +00001044 std::string NameStr;
Mike Stump11289f42009-09-09 15:08:12 +00001045
Douglas Gregorffca3a22009-01-09 17:18:27 +00001046 if (OMD->isInstanceMethod())
Fariborz Jahanian56338352007-11-13 21:02:00 +00001047 NameStr += "_I_";
1048 else
1049 NameStr += "_C_";
Mike Stump11289f42009-09-09 15:08:12 +00001050
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001051 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +00001052 NameStr += "_";
Mike Stump11289f42009-09-09 15:08:12 +00001053
1054 if (ObjCCategoryImplDecl *CID =
Steve Naroff11b387f2009-01-08 19:41:02 +00001055 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001056 NameStr += CID->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +00001057 NameStr += "_";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001058 }
Mike Stump11289f42009-09-09 15:08:12 +00001059 // Append selector names, replacing ':' with '_'
Chris Lattnere4b95692008-11-24 03:33:13 +00001060 {
1061 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001062 int len = selString.size();
1063 for (int i = 0; i < len; i++)
1064 if (selString[i] == ':')
1065 selString[i] = '_';
Fariborz Jahanian56338352007-11-13 21:02:00 +00001066 NameStr += selString;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001067 }
Fariborz Jahanian56338352007-11-13 21:02:00 +00001068 // Remember this name for metadata emission
1069 MethodInternalNames[OMD] = NameStr;
1070 ResultStr += NameStr;
Mike Stump11289f42009-09-09 15:08:12 +00001071
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001072 // Rewrite arguments
1073 ResultStr += "(";
Mike Stump11289f42009-09-09 15:08:12 +00001074
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001075 // invisible arguments
Douglas Gregorffca3a22009-01-09 17:18:27 +00001076 if (OMD->isInstanceMethod()) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001077 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001078 selfTy = Context->getPointerType(selfTy);
Steve Naroffdc5b6b22008-03-12 00:25:36 +00001079 if (!LangOpts.Microsoft) {
1080 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
1081 ResultStr += "struct ";
1082 }
1083 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001084 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +00001085 ResultStr += " *";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001086 }
1087 else
Steve Naroffd9803712009-04-29 16:37:50 +00001088 ResultStr += Context->getObjCClassType().getAsString();
Mike Stump11289f42009-09-09 15:08:12 +00001089
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001090 ResultStr += " self, ";
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001091 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001092 ResultStr += " _cmd";
Mike Stump11289f42009-09-09 15:08:12 +00001093
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001094 // Method arguments.
Chris Lattnera4997152009-02-20 18:43:26 +00001095 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1096 E = OMD->param_end(); PI != E; ++PI) {
1097 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001098 ResultStr += ", ";
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001099 if (PDecl->getType()->isObjCQualifiedIdType()) {
1100 ResultStr += "id ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001101 ResultStr += PDecl->getNameAsString();
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001102 } else {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001103 std::string Name = PDecl->getNameAsString();
Steve Naroffa5c0db82008-12-11 21:05:33 +00001104 if (isTopLevelBlockPointerType(PDecl->getType())) {
Steve Naroff44df6a22008-10-30 14:45:29 +00001105 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001106 const BlockPointerType *BPT = PDecl->getType()->getAs<BlockPointerType>();
Douglas Gregor7de59662009-05-29 20:38:28 +00001107 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name,
1108 Context->PrintingPolicy);
Steve Naroff44df6a22008-10-30 14:45:29 +00001109 } else
Douglas Gregor7de59662009-05-29 20:38:28 +00001110 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001111 ResultStr += Name;
1112 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001113 }
Fariborz Jahanianeab81cd2008-01-21 20:14:23 +00001114 if (OMD->isVariadic())
1115 ResultStr += ", ...";
Fariborz Jahanian7262fca2008-01-10 01:39:52 +00001116 ResultStr += ") ";
Mike Stump11289f42009-09-09 15:08:12 +00001117
Steve Naroffb067bbd2008-07-16 14:40:40 +00001118 if (FPRetType) {
1119 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump11289f42009-09-09 15:08:12 +00001120
Steve Naroffb067bbd2008-07-16 14:40:40 +00001121 // Now, emit the argument types (if any).
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001122 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroffb067bbd2008-07-16 14:40:40 +00001123 ResultStr += "(";
1124 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1125 if (i) ResultStr += ", ";
1126 std::string ParamStr = FT->getArgType(i).getAsString();
1127 ResultStr += ParamStr;
1128 }
1129 if (FT->isVariadic()) {
1130 if (FT->getNumArgs()) ResultStr += ", ";
1131 ResultStr += "...";
1132 }
1133 ResultStr += ")";
1134 } else {
1135 ResultStr += "()";
1136 }
1137 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001138}
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001139void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001140 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1141 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump11289f42009-09-09 15:08:12 +00001142
Fariborz Jahanian02d964b2010-02-15 21:11:41 +00001143 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
Mike Stump11289f42009-09-09 15:08:12 +00001144
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001145 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001146 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1147 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001148 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001149 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001150 ObjCMethodDecl *OMD = *I;
1151 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001152 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001153 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redla7b98a72009-04-26 20:35:05 +00001154
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001155 const char *startBuf = SM->getCharacterData(LocStart);
1156 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001157 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001158 }
Mike Stump11289f42009-09-09 15:08:12 +00001159
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001160 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001161 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1162 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001163 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001164 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001165 ObjCMethodDecl *OMD = *I;
1166 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001167 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001168 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +00001169
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001170 const char *startBuf = SM->getCharacterData(LocStart);
1171 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001172 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001173 }
Steve Naroffe1908e32008-12-01 20:33:01 +00001174 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001175 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001176 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001177 I != E; ++I) {
Steve Naroffc038b3a2008-12-02 17:36:43 +00001178 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffe1908e32008-12-01 20:33:01 +00001179 }
1180
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001181 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001182}
1183
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001184void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffc5484042007-10-30 02:23:23 +00001185 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001186 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff2f55b982007-11-01 03:35:41 +00001187 // we haven't seen a forward decl - generate a typedef.
Steve Naroff03f27672007-11-14 23:02:56 +00001188 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001189 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001190 ResultStr += "\n";
1191 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001192 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001193 ResultStr += "\n";
Steve Naroffa1e115e2008-03-10 23:16:54 +00001194 ResultStr += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001195 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001196 ResultStr += ";\n#endif\n";
Steve Naroff2f55b982007-11-01 03:35:41 +00001197 // Mark this typedef as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001198 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff2f55b982007-11-01 03:35:41 +00001199 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001200 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump11289f42009-09-09 15:08:12 +00001201
1202 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001203 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff0c0f5ba2009-01-11 01:06:09 +00001204 RewriteProperty(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001205 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001206 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001207 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001208 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001209 for (ObjCInterfaceDecl::classmeth_iterator
1210 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001211 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001212 RewriteMethodDeclaration(*I);
1213
Steve Naroff4cd61ac2007-10-30 03:43:13 +00001214 // Lastly, comment out the @end.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001215 ReplaceText(ClassDecl->getAtEndRange().getBegin(), 0, "// ");
Steve Naroff161a92b2007-10-26 20:53:56 +00001216}
1217
Steve Naroff08628db2008-12-09 12:56:34 +00001218Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1219 SourceRange SrcRange) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00001220 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1221 // This allows us to reuse all the fun and games in SynthMessageExpr().
1222 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1223 ObjCMessageExpr *MsgExpr;
1224 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1225 llvm::SmallVector<Expr *, 1> ExprVec;
1226 ExprVec.push_back(newStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001227
Steve Naroff1042ff32008-12-08 16:43:47 +00001228 Stmt *Receiver = PropRefExpr->getBase();
1229 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1230 if (PRE && PropGetters[PRE]) {
1231 // This allows us to handle chain/nested property getters.
1232 Receiver = PropGetters[PRE];
1233 }
Ted Kremenek2c809302010-02-11 22:41:21 +00001234 MsgExpr = new (Context) ObjCMessageExpr(*Context, dyn_cast<Expr>(Receiver),
Mike Stump11289f42009-09-09 15:08:12 +00001235 PDecl->getSetterName(), PDecl->getType(),
1236 PDecl->getSetterMethodDecl(),
1237 SourceLocation(), SourceLocation(),
Steve Naroff4588d0f2008-12-04 16:24:46 +00001238 &ExprVec[0], 1);
1239 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001240
Steve Naroff4588d0f2008-12-04 16:24:46 +00001241 // Now do the actual rewrite.
Steve Naroff08628db2008-12-09 12:56:34 +00001242 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffdf705772008-12-10 14:53:27 +00001243 //delete BinOp;
Ted Kremenek5a201952009-02-07 01:47:29 +00001244 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1245 // to things that stay around.
1246 Context->Deallocate(MsgExpr);
Steve Naroff4588d0f2008-12-04 16:24:46 +00001247 return ReplacingStmt;
Steve Narofff326f402008-12-03 00:56:33 +00001248}
1249
Steve Naroff4588d0f2008-12-04 16:24:46 +00001250Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Narofff326f402008-12-03 00:56:33 +00001251 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1252 // This allows us to reuse all the fun and games in SynthMessageExpr().
1253 ObjCMessageExpr *MsgExpr;
1254 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
Mike Stump11289f42009-09-09 15:08:12 +00001255
Steve Naroff1042ff32008-12-08 16:43:47 +00001256 Stmt *Receiver = PropRefExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00001257
Steve Naroff1042ff32008-12-08 16:43:47 +00001258 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1259 if (PRE && PropGetters[PRE]) {
1260 // This allows us to handle chain/nested property getters.
1261 Receiver = PropGetters[PRE];
1262 }
Ted Kremenek2c809302010-02-11 22:41:21 +00001263 MsgExpr = new (Context) ObjCMessageExpr(*Context, dyn_cast<Expr>(Receiver),
Mike Stump11289f42009-09-09 15:08:12 +00001264 PDecl->getGetterName(), PDecl->getType(),
1265 PDecl->getGetterMethodDecl(),
1266 SourceLocation(), SourceLocation(),
Steve Narofff326f402008-12-03 00:56:33 +00001267 0, 0);
1268
Steve Naroff22216db2008-12-04 23:50:32 +00001269 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001270
1271 if (!PropParentMap)
1272 PropParentMap = new ParentMap(CurrentBody);
1273
1274 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1275 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1276 // We stash away the ReplacingStmt since actually doing the
1277 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1278 PropGetters[PropRefExpr] = ReplacingStmt;
Ted Kremenek5a201952009-02-07 01:47:29 +00001279 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1280 // to things that stay around.
1281 Context->Deallocate(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001282 return PropRefExpr; // return the original...
1283 } else {
1284 ReplaceStmt(PropRefExpr, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001285 // delete PropRefExpr; elsewhere...
Ted Kremenek5a201952009-02-07 01:47:29 +00001286 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1287 // to things that stay around.
1288 Context->Deallocate(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001289 return ReplacingStmt;
1290 }
Steve Narofff326f402008-12-03 00:56:33 +00001291}
1292
Mike Stump11289f42009-09-09 15:08:12 +00001293Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001294 SourceLocation OrigStart,
1295 bool &replaced) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001296 ObjCIvarDecl *D = IV->getDecl();
Fariborz Jahanian0f3aecf2010-01-07 18:18:32 +00001297 const Expr *BaseExpr = IV->getBase();
Steve Naroff677ab3a2008-10-27 17:20:55 +00001298 if (CurMethodDef) {
Fariborz Jahanianf9e8c2b2010-01-26 18:28:51 +00001299 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001300 ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian0f3aecf2010-01-07 18:18:32 +00001301 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanianf0ed69c2010-01-26 20:37:44 +00001302 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
Steve Naroffb1c02372008-05-08 17:52:16 +00001303 // lookup which class implements the instance variable.
1304 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001305 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001306 clsDeclared);
Steve Naroffb1c02372008-05-08 17:52:16 +00001307 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001308
Steve Naroffb1c02372008-05-08 17:52:16 +00001309 // Synthesize an explicit cast to gain access to the ivar.
1310 std::string RecName = clsDeclared->getIdentifier()->getName();
1311 RecName += "_IMPL";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001312 IdentifierInfo *II = &Context->Idents.get(RecName);
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00001313 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001314 SourceLocation(), II);
Steve Naroffb1c02372008-05-08 17:52:16 +00001315 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1316 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall97513962010-01-15 18:39:57 +00001317 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
1318 CastExpr::CK_Unknown,
1319 IV->getBase());
Steve Naroffb1c02372008-05-08 17:52:16 +00001320 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001321 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1322 IV->getBase()->getLocEnd(),
1323 castExpr);
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001324 replaced = true;
Mike Stump11289f42009-09-09 15:08:12 +00001325 if (IV->isFreeIvar() &&
Steve Naroff677ab3a2008-10-27 17:20:55 +00001326 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001327 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1328 IV->getLocation(),
1329 D->getType());
Steve Naroff22216db2008-12-04 23:50:32 +00001330 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffb1c02372008-05-08 17:52:16 +00001331 return ME;
Steve Naroff05caa482007-11-15 11:33:00 +00001332 }
Fariborz Jahanian81310812010-01-28 01:41:20 +00001333 // Get the new text
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001334 // Cannot delete IV->getBase(), since PE points to it.
1335 // Replace the old base with the cast. This is important when doing
1336 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001337 IV->setBase(PE);
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001338 return IV;
Steve Naroff05caa482007-11-15 11:33:00 +00001339 }
Steve Naroff24840f62008-04-18 21:55:08 +00001340 } else { // we are outside a method.
Steve Naroff29ce4e52008-05-06 23:20:07 +00001341 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump11289f42009-09-09 15:08:12 +00001342
Steve Naroff29ce4e52008-05-06 23:20:07 +00001343 // Explicit ivar refs need to have a cast inserted.
1344 // FIXME: consider sharing some of this code with the code above.
Fariborz Jahanian12e2e862010-01-12 17:31:23 +00001345 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Fariborz Jahanian9146e442010-01-11 17:50:35 +00001346 ObjCInterfaceType *iFaceDecl =
1347 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001348 // lookup which class implements the instance variable.
1349 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001350 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001351 clsDeclared);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001352 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001353
Steve Naroff29ce4e52008-05-06 23:20:07 +00001354 // Synthesize an explicit cast to gain access to the ivar.
1355 std::string RecName = clsDeclared->getIdentifier()->getName();
1356 RecName += "_IMPL";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001357 IdentifierInfo *II = &Context->Idents.get(RecName);
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00001358 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001359 SourceLocation(), II);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001360 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1361 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall97513962010-01-15 18:39:57 +00001362 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
1363 CastExpr::CK_Unknown,
1364 IV->getBase());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001365 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001366 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner34873d22008-05-28 16:38:23 +00001367 IV->getBase()->getLocEnd(), castExpr);
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001368 replaced = true;
Steve Naroff29ce4e52008-05-06 23:20:07 +00001369 // Cannot delete IV->getBase(), since PE points to it.
1370 // Replace the old base with the cast. This is important when doing
1371 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001372 IV->setBase(PE);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001373 return IV;
1374 }
Steve Naroff05caa482007-11-15 11:33:00 +00001375 }
Steve Naroff24840f62008-04-18 21:55:08 +00001376 return IV;
Steve Narofff60782b2007-11-15 02:58:25 +00001377}
1378
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001379Stmt *RewriteObjC::RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced) {
1380 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1381 CI != E; ++CI) {
1382 if (*CI) {
1383 Stmt *newStmt = RewriteObjCNestedIvarRefExpr(*CI, replaced);
1384 if (newStmt)
1385 *CI = newStmt;
1386 }
1387 }
1388 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
1389 SourceRange OrigStmtRange = S->getSourceRange();
1390 Stmt *newStmt = RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin(),
1391 replaced);
1392 return newStmt;
Fariborz Jahanian31433382010-02-05 17:48:10 +00001393 }
1394 if (ObjCMessageExpr *MsgRefExpr = dyn_cast<ObjCMessageExpr>(S)) {
1395 Stmt *newStmt = SynthMessageExpr(MsgRefExpr);
1396 return newStmt;
1397 }
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001398 return S;
1399}
1400
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001401/// SynthCountByEnumWithState - To print:
1402/// ((unsigned int (*)
1403/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001404/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001405/// sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001406/// "countByEnumeratingWithState:objects:count:"),
1407/// &enumState,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001408/// (id *)items, (unsigned int)16)
1409///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001410void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001411 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1412 "id *, unsigned int))(void *)objc_msgSend)";
1413 buf += "\n\t\t";
1414 buf += "((id)l_collection,\n\t\t";
1415 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1416 buf += "\n\t\t";
1417 buf += "&enumState, "
1418 "(id *)items, (unsigned int)16)";
1419}
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001420
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001421/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1422/// statement to exit to its outer synthesized loop.
1423///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001424Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001425 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1426 return S;
1427 // replace break with goto __break_label
1428 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001429
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001430 SourceLocation startLoc = S->getLocStart();
1431 buf = "goto __break_label_";
1432 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001433 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001434
1435 return 0;
1436}
1437
1438/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1439/// statement to continue with its inner synthesized loop.
1440///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001441Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001442 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1443 return S;
1444 // replace continue with goto __continue_label
1445 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001446
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001447 SourceLocation startLoc = S->getLocStart();
1448 buf = "goto __continue_label_";
1449 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001450 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump11289f42009-09-09 15:08:12 +00001451
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001452 return 0;
1453}
1454
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001455/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001456/// It rewrites:
1457/// for ( type elem in collection) { stmts; }
Mike Stump11289f42009-09-09 15:08:12 +00001458
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001459/// Into:
1460/// {
Mike Stump11289f42009-09-09 15:08:12 +00001461/// type elem;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001462/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001463/// id items[16];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001464/// id l_collection = (id)collection;
Mike Stump11289f42009-09-09 15:08:12 +00001465/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001466/// objects:items count:16];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001467/// if (limit) {
1468/// unsigned long startMutations = *enumState.mutationsPtr;
1469/// do {
1470/// unsigned long counter = 0;
1471/// do {
Mike Stump11289f42009-09-09 15:08:12 +00001472/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001473/// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001474/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001475/// stmts;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001476/// __continue_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001477/// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001478/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001479/// objects:items count:16]);
1480/// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001481/// __break_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001482/// }
1483/// else
1484/// elem = nil;
1485/// }
1486///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001487Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattnera779d692008-01-31 05:10:40 +00001488 SourceLocation OrigEnd) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001489 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001490 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001491 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump11289f42009-09-09 15:08:12 +00001492 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001493 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001494
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001495 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001496 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001497 const char *elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001498 std::string elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001499 std::string buf;
1500 buf = "\n{\n\t";
1501 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1502 // type elem;
Chris Lattner529efc72009-03-28 06:33:19 +00001503 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek292b3842008-10-06 22:16:13 +00001504 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001505 if (ElementType->isObjCQualifiedIdType() ||
1506 ElementType->isObjCQualifiedInterfaceType())
1507 // Simply use 'id' for all qualified types.
1508 elementTypeAsString = "id";
1509 else
1510 elementTypeAsString = ElementType.getAsString();
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001511 buf += elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001512 buf += " ";
Chris Lattner86d7d912008-11-24 03:54:41 +00001513 elementName = D->getNameAsCString();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001514 buf += elementName;
1515 buf += ";\n\t";
1516 }
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001517 else {
1518 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner86d7d912008-11-24 03:54:41 +00001519 elementName = DR->getDecl()->getNameAsCString();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001520 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1521 if (VD->getType()->isObjCQualifiedIdType() ||
1522 VD->getType()->isObjCQualifiedInterfaceType())
1523 // Simply use 'id' for all qualified types.
1524 elementTypeAsString = "id";
1525 else
1526 elementTypeAsString = VD->getType().getAsString();
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001527 }
Mike Stump11289f42009-09-09 15:08:12 +00001528
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001529 // struct __objcFastEnumerationState enumState = { 0 };
1530 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1531 // id items[16];
1532 buf += "id items[16];\n\t";
1533 // id l_collection = (id)
1534 buf += "id l_collection = (id)";
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001535 // Find start location of 'collection' the hard way!
1536 const char *startCollectionBuf = startBuf;
1537 startCollectionBuf += 3; // skip 'for'
1538 startCollectionBuf = strchr(startCollectionBuf, '(');
1539 startCollectionBuf++; // skip '('
1540 // find 'in' and skip it.
1541 while (*startCollectionBuf != ' ' ||
1542 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1543 (*(startCollectionBuf+3) != ' ' &&
1544 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1545 startCollectionBuf++;
1546 startCollectionBuf += 3;
Mike Stump11289f42009-09-09 15:08:12 +00001547
1548 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001549 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001550 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001551 SourceLocation rightParenLoc = S->getRParenLoc();
1552 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1553 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001554 buf = ";\n\t";
Mike Stump11289f42009-09-09 15:08:12 +00001555
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001556 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1557 // objects:items count:16];
1558 // which is synthesized into:
Mike Stump11289f42009-09-09 15:08:12 +00001559 // unsigned int limit =
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001560 // ((unsigned int (*)
1561 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001562 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001563 // sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001564 // "countByEnumeratingWithState:objects:count:"),
1565 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001566 // (id *)items, (unsigned int)16);
1567 buf += "unsigned long limit =\n\t\t";
1568 SynthCountByEnumWithState(buf);
1569 buf += ";\n\t";
1570 /// if (limit) {
1571 /// unsigned long startMutations = *enumState.mutationsPtr;
1572 /// do {
1573 /// unsigned long counter = 0;
1574 /// do {
Mike Stump11289f42009-09-09 15:08:12 +00001575 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001576 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001577 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001578 buf += "if (limit) {\n\t";
1579 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1580 buf += "do {\n\t\t";
1581 buf += "unsigned long counter = 0;\n\t\t";
1582 buf += "do {\n\t\t\t";
1583 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1584 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1585 buf += elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001586 buf += " = (";
1587 buf += elementTypeAsString;
1588 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001589 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001590 ReplaceText(lparenLoc, 1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001591
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001592 /// __continue_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001593 /// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001594 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001595 /// objects:items count:16]);
1596 /// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001597 /// __break_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001598 /// }
1599 /// else
1600 /// elem = nil;
1601 /// }
Mike Stump11289f42009-09-09 15:08:12 +00001602 ///
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001603 buf = ";\n\t";
1604 buf += "__continue_label_";
1605 buf += utostr(ObjCBcLabelNo.back());
1606 buf += ": ;";
1607 buf += "\n\t\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001608 buf += "} while (counter < limit);\n\t";
1609 buf += "} while (limit = ";
1610 SynthCountByEnumWithState(buf);
1611 buf += ");\n\t";
1612 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001613 buf += " = ((";
1614 buf += elementTypeAsString;
1615 buf += ")0);\n\t";
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001616 buf += "__break_label_";
1617 buf += utostr(ObjCBcLabelNo.back());
1618 buf += ": ;\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001619 buf += "}\n\t";
1620 buf += "else\n\t\t";
1621 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001622 buf += " = ((";
1623 buf += elementTypeAsString;
1624 buf += ")0);\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001625 buf += "}\n";
Mike Stump11289f42009-09-09 15:08:12 +00001626
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001627 // Insert all these *after* the statement body.
Sebastian Redla7b98a72009-04-26 20:35:05 +00001628 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Narofff0ff8792008-07-21 18:26:02 +00001629 if (isa<CompoundStmt>(S->getBody())) {
1630 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001631 InsertText(endBodyLoc, buf);
Steve Narofff0ff8792008-07-21 18:26:02 +00001632 } else {
1633 /* Need to treat single statements specially. For example:
1634 *
1635 * for (A *a in b) if (stuff()) break;
1636 * for (A *a in b) xxxyy;
1637 *
1638 * The following code simply scans ahead to the semi to find the actual end.
1639 */
1640 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1641 const char *semiBuf = strchr(stmtBuf, ';');
1642 assert(semiBuf && "Can't find ';'");
1643 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001644 InsertText(endBodyLoc, buf);
Steve Narofff0ff8792008-07-21 18:26:02 +00001645 }
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001646 Stmts.pop_back();
1647 ObjCBcLabelNo.pop_back();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001648 return 0;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001649}
1650
Mike Stump11289f42009-09-09 15:08:12 +00001651/// RewriteObjCSynchronizedStmt -
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001652/// This routine rewrites @synchronized(expr) stmt;
1653/// into:
1654/// objc_sync_enter(expr);
1655/// @try stmt @finally { objc_sync_exit(expr); }
1656///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001657Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001658 // Get the start location and compute the semi location.
1659 SourceLocation startLoc = S->getLocStart();
1660 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001661
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001662 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump11289f42009-09-09 15:08:12 +00001663
1664 std::string buf;
Steve Naroffb2fc0522008-08-21 13:03:03 +00001665 buf = "objc_sync_enter((id)";
1666 const char *lparenBuf = startBuf;
1667 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001668 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001669 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1670 // the sync expression is typically a message expression that's already
Steve Naroffad7013b2008-08-19 13:04:19 +00001671 // been rewritten! (which implies the SourceLocation's are invalid).
1672 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001673 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffad7013b2008-08-19 13:04:19 +00001674 while (*endBuf != ')') endBuf--;
1675 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001676 buf = ");\n";
1677 // declare a new scope with two variables, _stack and _rethrow.
1678 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1679 buf += "int buf[18/*32-bit i386*/];\n";
1680 buf += "char *pointers[4];} _stack;\n";
1681 buf += "id volatile _rethrow = 0;\n";
1682 buf += "objc_exception_try_enter(&_stack);\n";
1683 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001684 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001685 startLoc = S->getSynchBody()->getLocEnd();
1686 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001687
Steve Naroffad7013b2008-08-19 13:04:19 +00001688 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001689 SourceLocation lastCurlyLoc = startLoc;
1690 buf = "}\nelse {\n";
1691 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroffd9803712009-04-29 16:37:50 +00001692 buf += "}\n";
1693 buf += "{ /* implicit finally clause */\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001694 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffec60b432009-12-05 21:43:12 +00001695
1696 std::string syncBuf;
1697 syncBuf += " objc_sync_exit(";
John McCall97513962010-01-15 18:39:57 +00001698 Expr *syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1699 CastExpr::CK_Unknown,
1700 S->getSynchExpr());
Ted Kremenek2d470fc2008-09-13 05:16:45 +00001701 std::string syncExprBufS;
1702 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00001703 syncExpr->printPretty(syncExprBuf, *Context, 0,
1704 PrintingPolicy(LangOpts));
Steve Naroffec60b432009-12-05 21:43:12 +00001705 syncBuf += syncExprBuf.str();
1706 syncBuf += ");";
1707
1708 buf += syncBuf;
1709 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001710 buf += "}\n";
1711 buf += "}";
Mike Stump11289f42009-09-09 15:08:12 +00001712
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001713 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffec60b432009-12-05 21:43:12 +00001714
1715 bool hasReturns = false;
1716 HasReturnStmts(S->getSynchBody(), hasReturns);
1717 if (hasReturns)
1718 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1719
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001720 return 0;
1721}
1722
Steve Naroffec60b432009-12-05 21:43:12 +00001723void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1724{
Steve Naroff6d6da252008-12-05 17:03:39 +00001725 // Perform a bottom up traversal of all children.
1726 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1727 CI != E; ++CI)
1728 if (*CI)
Steve Naroffec60b432009-12-05 21:43:12 +00001729 WarnAboutReturnGotoStmts(*CI);
Steve Naroff6d6da252008-12-05 17:03:39 +00001730
Steve Naroffec60b432009-12-05 21:43:12 +00001731 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump11289f42009-09-09 15:08:12 +00001732 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff6d6da252008-12-05 17:03:39 +00001733 TryFinallyContainsReturnDiag);
1734 }
1735 return;
1736}
1737
Steve Naroffec60b432009-12-05 21:43:12 +00001738void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1739{
1740 // Perform a bottom up traversal of all children.
1741 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1742 CI != E; ++CI)
1743 if (*CI)
1744 HasReturnStmts(*CI, hasReturns);
1745
1746 if (isa<ReturnStmt>(S))
1747 hasReturns = true;
1748 return;
1749}
1750
1751void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1752 // Perform a bottom up traversal of all children.
1753 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1754 CI != E; ++CI)
1755 if (*CI) {
1756 RewriteTryReturnStmts(*CI);
1757 }
1758 if (isa<ReturnStmt>(S)) {
1759 SourceLocation startLoc = S->getLocStart();
1760 const char *startBuf = SM->getCharacterData(startLoc);
1761
1762 const char *semiBuf = strchr(startBuf, ';');
1763 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1764 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1765
1766 std::string buf;
1767 buf = "{ objc_exception_try_exit(&_stack); return";
1768
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001769 ReplaceText(startLoc, 6, buf);
1770 InsertText(onePastSemiLoc, "}");
Steve Naroffec60b432009-12-05 21:43:12 +00001771 }
1772 return;
1773}
1774
1775void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1776 // Perform a bottom up traversal of all children.
1777 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1778 CI != E; ++CI)
1779 if (*CI) {
1780 RewriteSyncReturnStmts(*CI, syncExitBuf);
1781 }
1782 if (isa<ReturnStmt>(S)) {
1783 SourceLocation startLoc = S->getLocStart();
1784 const char *startBuf = SM->getCharacterData(startLoc);
1785
1786 const char *semiBuf = strchr(startBuf, ';');
1787 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1788 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1789
1790 std::string buf;
1791 buf = "{ objc_exception_try_exit(&_stack);";
1792 buf += syncExitBuf;
1793 buf += " return";
1794
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001795 ReplaceText(startLoc, 6, buf);
1796 InsertText(onePastSemiLoc, "}");
Steve Naroffec60b432009-12-05 21:43:12 +00001797 }
1798 return;
1799}
1800
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001801Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001802 // Get the start location and compute the semi location.
1803 SourceLocation startLoc = S->getLocStart();
1804 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001805
Steve Naroffbf478ec2007-11-07 04:08:17 +00001806 assert((*startBuf == '@') && "bogus @try location");
1807
1808 std::string buf;
1809 // declare a new scope with two variables, _stack and _rethrow.
1810 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1811 buf += "int buf[18/*32-bit i386*/];\n";
1812 buf += "char *pointers[4];} _stack;\n";
1813 buf += "id volatile _rethrow = 0;\n";
1814 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff16018582007-11-07 18:43:40 +00001815 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffbf478ec2007-11-07 04:08:17 +00001816
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001817 ReplaceText(startLoc, 4, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001818
Steve Naroffbf478ec2007-11-07 04:08:17 +00001819 startLoc = S->getTryBody()->getLocEnd();
1820 startBuf = SM->getCharacterData(startLoc);
1821
1822 assert((*startBuf == '}') && "bogus @try block");
Mike Stump11289f42009-09-09 15:08:12 +00001823
Steve Naroffbf478ec2007-11-07 04:08:17 +00001824 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffce2dca12008-07-16 15:31:30 +00001825 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1826 if (catchList) {
1827 startLoc = startLoc.getFileLocWithOffset(1);
1828 buf = " /* @catch begin */ else {\n";
1829 buf += " id _caught = objc_exception_extract(&_stack);\n";
1830 buf += " objc_exception_try_enter (&_stack);\n";
1831 buf += " if (_setjmp(_stack.buf))\n";
1832 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1833 buf += " else { /* @catch continue */";
Mike Stump11289f42009-09-09 15:08:12 +00001834
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001835 InsertText(startLoc, buf);
Steve Narofffac18fe2008-09-09 19:59:12 +00001836 } else { /* no catch list */
1837 buf = "}\nelse {\n";
1838 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1839 buf += "}";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001840 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffce2dca12008-07-16 15:31:30 +00001841 }
Steve Naroffbf478ec2007-11-07 04:08:17 +00001842 bool sawIdTypedCatch = false;
1843 Stmt *lastCatchBody = 0;
Steve Naroffbf478ec2007-11-07 04:08:17 +00001844 while (catchList) {
Steve Naroff371b8fb2009-03-03 19:52:17 +00001845 ParmVarDecl *catchDecl = catchList->getCatchParamDecl();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001846
Mike Stump11289f42009-09-09 15:08:12 +00001847 if (catchList == S->getCatchStmts())
Steve Naroffbf478ec2007-11-07 04:08:17 +00001848 buf = "if ("; // we are generating code for the first catch clause
1849 else
1850 buf = "else if (";
1851 startLoc = catchList->getLocStart();
1852 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001853
Steve Naroffbf478ec2007-11-07 04:08:17 +00001854 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump11289f42009-09-09 15:08:12 +00001855
Steve Naroffbf478ec2007-11-07 04:08:17 +00001856 const char *lParenLoc = strchr(startBuf, '(');
1857
Steve Naroffe6b7ffd2008-02-01 22:08:12 +00001858 if (catchList->hasEllipsis()) {
Steve Naroffedb5bc62008-02-01 20:02:07 +00001859 // Now rewrite the body...
1860 lastCatchBody = catchList->getCatchBody();
Steve Naroffedb5bc62008-02-01 20:02:07 +00001861 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1862 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001863 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1864 "bogus @catch paren location");
Steve Naroffedb5bc62008-02-01 20:02:07 +00001865 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001866
Steve Naroffedb5bc62008-02-01 20:02:07 +00001867 buf += "1) { id _tmp = _caught;";
Daniel Dunbardec484a2009-08-19 19:10:30 +00001868 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff371b8fb2009-03-03 19:52:17 +00001869 } else if (catchDecl) {
1870 QualType t = catchDecl->getType();
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001871 if (t == Context->getObjCIdType()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001872 buf += "1) { ";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001873 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroffbf478ec2007-11-07 04:08:17 +00001874 sawIdTypedCatch = true;
Fariborz Jahanian59516092010-01-12 01:22:23 +00001875 } else if (t->isObjCObjectPointerType()) {
1876 QualType InterfaceTy = t->getPointeeType();
1877 const ObjCInterfaceType *cls = // Should be a pointer to a class.
1878 InterfaceTy->getAs<ObjCInterfaceType>();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001879 if (cls) {
Steve Naroff16018582007-11-07 18:43:40 +00001880 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001881 buf += cls->getDecl()->getNameAsString();
Steve Naroff16018582007-11-07 18:43:40 +00001882 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001883 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroffbf478ec2007-11-07 04:08:17 +00001884 }
1885 }
1886 // Now rewrite the body...
1887 lastCatchBody = catchList->getCatchBody();
1888 SourceLocation rParenLoc = catchList->getRParenLoc();
1889 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1890 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1891 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1892 assert((*rParenBuf == ')') && "bogus @catch paren location");
1893 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001894
Mike Stump11289f42009-09-09 15:08:12 +00001895 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroffbf478ec2007-11-07 04:08:17 +00001896 // declares the @catch parameter).
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001897 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff371b8fb2009-03-03 19:52:17 +00001898 } else {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001899 assert(false && "@catch rewrite bug");
Steve Naroffa733c7f2007-11-07 15:32:26 +00001900 }
Steve Naroffedb5bc62008-02-01 20:02:07 +00001901 // make sure all the catch bodies get rewritten!
Steve Naroffbf478ec2007-11-07 04:08:17 +00001902 catchList = catchList->getNextCatchStmt();
1903 }
1904 // Complete the catch list...
1905 if (lastCatchBody) {
1906 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001907 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1908 "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001909
Steve Naroff4adbe312008-09-11 15:29:03 +00001910 // Insert the last (implicit) else clause *before* the right curly brace.
1911 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1912 buf = "} /* last catch end */\n";
1913 buf += "else {\n";
1914 buf += " _rethrow = _caught;\n";
1915 buf += " objc_exception_try_exit(&_stack);\n";
1916 buf += "} } /* @catch end */\n";
1917 if (!S->getFinallyStmt())
1918 buf += "}\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001919 InsertText(bodyLoc, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001920
Steve Naroffbf478ec2007-11-07 04:08:17 +00001921 // Set lastCurlyLoc
1922 lastCurlyLoc = lastCatchBody->getLocEnd();
1923 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001924 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001925 startLoc = finalStmt->getLocStart();
1926 startBuf = SM->getCharacterData(startLoc);
1927 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump11289f42009-09-09 15:08:12 +00001928
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001929 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump11289f42009-09-09 15:08:12 +00001930
Steve Naroffbf478ec2007-11-07 04:08:17 +00001931 Stmt *body = finalStmt->getFinallyBody();
1932 SourceLocation startLoc = body->getLocStart();
1933 SourceLocation endLoc = body->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001934 assert(*SM->getCharacterData(startLoc) == '{' &&
1935 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001936 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001937 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001938
Steve Naroffbf478ec2007-11-07 04:08:17 +00001939 startLoc = startLoc.getFileLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001940 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Steve Naroffbf478ec2007-11-07 04:08:17 +00001941 endLoc = endLoc.getFileLocWithOffset(-1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001942 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump11289f42009-09-09 15:08:12 +00001943
Steve Naroffbf478ec2007-11-07 04:08:17 +00001944 // Set lastCurlyLoc
1945 lastCurlyLoc = body->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00001946
Steve Naroff6d6da252008-12-05 17:03:39 +00001947 // Now check for any return/continue/go statements within the @try.
Steve Naroffec60b432009-12-05 21:43:12 +00001948 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff4adbe312008-09-11 15:29:03 +00001949 } else { /* no finally clause - make sure we synthesize an implicit one */
1950 buf = "{ /* implicit finally clause */\n";
1951 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1952 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1953 buf += "}";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001954 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffec60b432009-12-05 21:43:12 +00001955
1956 // Now check for any return/continue/go statements within the @try.
1957 // The implicit finally clause won't called if the @try contains any
1958 // jump statements.
1959 bool hasReturns = false;
1960 HasReturnStmts(S->getTryBody(), hasReturns);
1961 if (hasReturns)
1962 RewriteTryReturnStmts(S->getTryBody());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001963 }
1964 // Now emit the final closing curly brace...
1965 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001966 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001967 return 0;
1968}
1969
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001970Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001971 return 0;
1972}
1973
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001974Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001975 return 0;
1976}
1977
Mike Stump11289f42009-09-09 15:08:12 +00001978// This can't be done with ReplaceStmt(S, ThrowExpr), since
1979// the throw expression is typically a message expression that's already
Steve Naroffa733c7f2007-11-07 15:32:26 +00001980// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001981Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroffa733c7f2007-11-07 15:32:26 +00001982 // Get the start location and compute the semi location.
1983 SourceLocation startLoc = S->getLocStart();
1984 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001985
Steve Naroffa733c7f2007-11-07 15:32:26 +00001986 assert((*startBuf == '@') && "bogus @throw location");
1987
1988 std::string buf;
1989 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffc7d2df22008-01-19 00:42:38 +00001990 if (S->getThrowExpr())
1991 buf = "objc_exception_throw(";
1992 else // add an implicit argument
1993 buf = "objc_exception_throw(_caught";
Mike Stump11289f42009-09-09 15:08:12 +00001994
Steve Naroff29788342008-07-25 15:41:30 +00001995 // handle "@ throw" correctly.
1996 const char *wBuf = strchr(startBuf, 'w');
1997 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001998 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001999
Steve Naroffa733c7f2007-11-07 15:32:26 +00002000 const char *semiBuf = strchr(startBuf, ';');
2001 assert((*semiBuf == ';') && "@throw: can't find ';'");
2002 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002003 ReplaceText(semiLoc, 1, ");");
Steve Naroffa733c7f2007-11-07 15:32:26 +00002004 return 0;
2005}
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00002006
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002007Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerc6d91c02007-10-17 22:35:30 +00002008 // Create a new string expression.
2009 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlssond8499822007-10-29 05:01:08 +00002010 std::string StrEncoding;
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00002011 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002012 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
2013 StrEncoding.length(), false,StrType,
2014 SourceLocation());
Chris Lattner2e0d2602008-01-31 19:37:57 +00002015 ReplaceStmt(Exp, Replacement);
Mike Stump11289f42009-09-09 15:08:12 +00002016
Chris Lattner4431a1b2007-11-30 22:53:43 +00002017 // Replace this subexpr in the parent.
Steve Naroff22216db2008-12-04 23:50:32 +00002018 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattner69534692007-10-24 16:57:36 +00002019 return Replacement;
Chris Lattnera7c19fe2007-10-16 22:36:42 +00002020}
2021
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002022Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff2654e182008-12-22 22:16:07 +00002023 if (!SelGetUidFunctionDecl)
2024 SynthSelGetUidFunctionDecl();
Steve Naroffe4f9b232007-11-05 14:50:49 +00002025 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2026 // Create a call to sel_registerName("selName").
2027 llvm::SmallVector<Expr*, 8> SelExprs;
2028 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002029 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00002030 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00002031 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00002032 false, argType, SourceLocation()));
Steve Naroffe4f9b232007-11-05 14:50:49 +00002033 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2034 &SelExprs[0], SelExprs.size());
Chris Lattner2e0d2602008-01-31 19:37:57 +00002035 ReplaceStmt(Exp, SelExp);
Steve Naroff22216db2008-12-04 23:50:32 +00002036 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffe4f9b232007-11-05 14:50:49 +00002037 return SelExp;
2038}
2039
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002040CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002041 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2042 SourceLocation EndLoc) {
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002043 // Get the type, we will need to reference it in a couple spots.
Steve Naroff574440f2007-10-24 22:48:43 +00002044 QualType msgSendType = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002045
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002046 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek5a201952009-02-07 01:47:29 +00002047 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002048
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002049 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattner3c799d72007-10-24 17:06:59 +00002050 QualType pToFunc = Context->getPointerType(msgSendType);
Mike Stump11289f42009-09-09 15:08:12 +00002051 ImplicitCastExpr *ICE = new (Context) ImplicitCastExpr(pToFunc,
Anders Carlssona2615922009-07-31 00:48:10 +00002052 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002053 DRE,
Douglas Gregora11693b2008-11-12 17:17:38 +00002054 /*isLvalue=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00002055
John McCall9dd450b2009-09-21 23:43:11 +00002056 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00002057
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002058 CallExpr *Exp =
2059 new (Context) CallExpr(*Context, ICE, args, nargs, FT->getResultType(),
2060 EndLoc);
2061 return Exp;
Steve Naroff574440f2007-10-24 22:48:43 +00002062}
2063
Steve Naroff50d42052007-11-01 13:24:47 +00002064static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2065 const char *&startRef, const char *&endRef) {
2066 while (startBuf < endBuf) {
2067 if (*startBuf == '<')
2068 startRef = startBuf; // mark the start.
2069 if (*startBuf == '>') {
Steve Naroff1b232132007-11-09 12:50:28 +00002070 if (startRef && *startRef == '<') {
2071 endRef = startBuf; // mark the end.
2072 return true;
2073 }
2074 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00002075 }
2076 startBuf++;
2077 }
2078 return false;
2079}
2080
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002081static void scanToNextArgument(const char *&argRef) {
2082 int angle = 0;
2083 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2084 if (*argRef == '<')
2085 angle++;
2086 else if (*argRef == '>')
2087 angle--;
2088 argRef++;
2089 }
2090 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2091}
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002092
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002093bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian80c54b02010-02-03 21:29:28 +00002094 if (T->isObjCQualifiedIdType())
2095 return true;
Fariborz Jahanian06769f92010-02-02 18:35:07 +00002096 if (const PointerType *PT = T->getAs<PointerType>()) {
2097 if (PT->getPointeeType()->isObjCQualifiedIdType())
2098 return true;
2099 }
2100 if (T->isObjCObjectPointerType()) {
2101 T = T->getPointeeType();
2102 return T->isObjCQualifiedInterfaceType();
2103 }
2104 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00002105}
2106
Steve Naroff873bd842008-07-29 18:15:38 +00002107void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2108 QualType Type = E->getType();
2109 if (needToScanForQualifiers(Type)) {
Steve Naroffdbfc6932008-11-19 21:15:47 +00002110 SourceLocation Loc, EndLoc;
Mike Stump11289f42009-09-09 15:08:12 +00002111
Steve Naroffdbfc6932008-11-19 21:15:47 +00002112 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2113 Loc = ECE->getLParenLoc();
2114 EndLoc = ECE->getRParenLoc();
2115 } else {
2116 Loc = E->getLocStart();
2117 EndLoc = E->getLocEnd();
2118 }
2119 // This will defend against trying to rewrite synthesized expressions.
2120 if (Loc.isInvalid() || EndLoc.isInvalid())
2121 return;
2122
Steve Naroff873bd842008-07-29 18:15:38 +00002123 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffdbfc6932008-11-19 21:15:47 +00002124 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff873bd842008-07-29 18:15:38 +00002125 const char *startRef = 0, *endRef = 0;
2126 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2127 // Get the locations of the startRef, endRef.
2128 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
2129 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
2130 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002131 InsertText(LessLoc, "/*");
2132 InsertText(GreaterLoc, "*/");
Steve Naroff873bd842008-07-29 18:15:38 +00002133 }
2134 }
2135}
2136
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002137void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002138 SourceLocation Loc;
2139 QualType Type;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002140 const FunctionProtoType *proto = 0;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002141 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2142 Loc = VD->getLocation();
2143 Type = VD->getType();
2144 }
2145 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2146 Loc = FD->getLocation();
2147 // Check for ObjC 'id' and class types that have been adorned with protocol
2148 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall9dd450b2009-09-21 23:43:11 +00002149 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002150 assert(funcType && "missing function type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002151 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002152 if (!proto)
2153 return;
2154 Type = proto->getResultType();
2155 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00002156 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2157 Loc = FD->getLocation();
2158 Type = FD->getType();
2159 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002160 else
2161 return;
Mike Stump11289f42009-09-09 15:08:12 +00002162
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002163 if (needToScanForQualifiers(Type)) {
Steve Naroff50d42052007-11-01 13:24:47 +00002164 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002165
Steve Naroff50d42052007-11-01 13:24:47 +00002166 const char *endBuf = SM->getCharacterData(Loc);
2167 const char *startBuf = endBuf;
Steve Naroff930e0992008-05-31 05:02:17 +00002168 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroff50d42052007-11-01 13:24:47 +00002169 startBuf--; // scan backward (from the decl location) for return type.
2170 const char *startRef = 0, *endRef = 0;
2171 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2172 // Get the locations of the startRef, endRef.
2173 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2174 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2175 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002176 InsertText(LessLoc, "/*");
2177 InsertText(GreaterLoc, "*/");
Steve Naroff37e011c2007-10-31 04:38:33 +00002178 }
2179 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002180 if (!proto)
2181 return; // most likely, was a variable
Steve Naroff50d42052007-11-01 13:24:47 +00002182 // Now check arguments.
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002183 const char *startBuf = SM->getCharacterData(Loc);
2184 const char *startFuncBuf = startBuf;
Steve Naroff50d42052007-11-01 13:24:47 +00002185 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2186 if (needToScanForQualifiers(proto->getArgType(i))) {
2187 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002188
Steve Naroff50d42052007-11-01 13:24:47 +00002189 const char *endBuf = startBuf;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002190 // scan forward (from the decl location) for argument types.
2191 scanToNextArgument(endBuf);
Steve Naroff50d42052007-11-01 13:24:47 +00002192 const char *startRef = 0, *endRef = 0;
2193 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2194 // Get the locations of the startRef, endRef.
Mike Stump11289f42009-09-09 15:08:12 +00002195 SourceLocation LessLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002196 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump11289f42009-09-09 15:08:12 +00002197 SourceLocation GreaterLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002198 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroff50d42052007-11-01 13:24:47 +00002199 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002200 InsertText(LessLoc, "/*");
2201 InsertText(GreaterLoc, "*/");
Steve Naroff50d42052007-11-01 13:24:47 +00002202 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002203 startBuf = ++endBuf;
2204 }
2205 else {
Steve Naroffc884aa82008-08-06 15:58:23 +00002206 // If the function name is derived from a macro expansion, then the
2207 // argument buffer will not follow the name. Need to speak with Chris.
2208 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002209 startBuf++; // scan forward (from the decl location) for argument types.
2210 startBuf++;
2211 }
Steve Naroff50d42052007-11-01 13:24:47 +00002212 }
Steve Naroff37e011c2007-10-31 04:38:33 +00002213}
2214
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002215void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2216 QualType QT = ND->getType();
2217 const Type* TypePtr = QT->getAs<Type>();
2218 if (!isa<TypeOfExprType>(TypePtr))
2219 return;
2220 while (isa<TypeOfExprType>(TypePtr)) {
2221 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2222 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2223 TypePtr = QT->getAs<Type>();
2224 }
2225 // FIXME. This will not work for multiple declarators; as in:
2226 // __typeof__(a) b,c,d;
2227 std::string TypeAsString(QT.getAsString());
2228 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2229 const char *startBuf = SM->getCharacterData(DeclLoc);
2230 if (ND->getInit()) {
2231 std::string Name(ND->getNameAsString());
2232 TypeAsString += " " + Name + " = ";
2233 Expr *E = ND->getInit();
2234 SourceLocation startLoc;
2235 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2236 startLoc = ECE->getLParenLoc();
2237 else
2238 startLoc = E->getLocStart();
2239 startLoc = SM->getInstantiationLoc(startLoc);
2240 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002241 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002242 }
2243 else {
2244 SourceLocation X = ND->getLocEnd();
2245 X = SM->getInstantiationLoc(X);
2246 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002247 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002248 }
2249}
2250
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002251// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002252void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002253 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2254 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002255 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002256 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002257 &ArgTys[0], ArgTys.size(),
2258 false /*isVariadic*/, 0,
2259 false, false, 0, 0, false,
2260 CC_Default);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002261 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002262 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002263 SelGetUidIdent, getFuncType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002264 FunctionDecl::Extern, false);
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002265}
2266
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002267void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002268 // declared in <objc/objc.h>
Douglas Gregor1e21c192009-01-09 01:47:02 +00002269 if (FD->getIdentifier() &&
2270 strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002271 SelGetUidFunctionDecl = FD;
Steve Naroff37e011c2007-10-31 04:38:33 +00002272 return;
2273 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002274 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002275}
2276
Fariborz Jahaniana459c442010-02-12 17:52:31 +00002277static void RewriteBlockPointerType(std::string& Str, QualType Type) {
2278 std::string TypeString(Type.getAsString());
2279 const char *argPtr = TypeString.c_str();
2280 if (!strchr(argPtr, '^')) {
2281 Str += TypeString;
2282 return;
2283 }
2284 while (*argPtr) {
2285 Str += (*argPtr == '^' ? '*' : *argPtr);
2286 argPtr++;
2287 }
2288}
2289
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00002290// FIXME. Consolidate this routine with RewriteBlockPointerType.
2291static void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD) {
2292 QualType Type = VD->getType();
2293 std::string TypeString(Type.getAsString());
2294 const char *argPtr = TypeString.c_str();
2295 int paren = 0;
2296 while (*argPtr) {
2297 switch (*argPtr) {
2298 case '(':
2299 Str += *argPtr;
2300 paren++;
2301 break;
2302 case ')':
2303 Str += *argPtr;
2304 paren--;
2305 break;
2306 case '^':
2307 Str += '*';
2308 if (paren == 1)
2309 Str += VD->getNameAsString();
2310 break;
2311 default:
2312 Str += *argPtr;
2313 break;
2314 }
2315 argPtr++;
2316 }
2317}
2318
2319
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002320void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2321 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2322 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2323 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2324 if (!proto)
2325 return;
2326 QualType Type = proto->getResultType();
2327 std::string FdStr = Type.getAsString();
2328 FdStr += " ";
2329 FdStr += FD->getNameAsCString();
2330 FdStr += "(";
2331 unsigned numArgs = proto->getNumArgs();
2332 for (unsigned i = 0; i < numArgs; i++) {
2333 QualType ArgType = proto->getArgType(i);
Fariborz Jahaniana459c442010-02-12 17:52:31 +00002334 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002335 if (i+1 < numArgs)
2336 FdStr += ", ";
2337 }
2338 FdStr += ");\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002339 InsertText(FunLocStart, FdStr);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002340 CurFunctionDeclToDeclareForBlock = 0;
2341}
2342
Steve Naroff17978c42008-03-11 17:37:02 +00002343// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002344void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroff17978c42008-03-11 17:37:02 +00002345 if (SuperContructorFunctionDecl)
2346 return;
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002347 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroff17978c42008-03-11 17:37:02 +00002348 llvm::SmallVector<QualType, 16> ArgTys;
2349 QualType argT = Context->getObjCIdType();
2350 assert(!argT.isNull() && "Can't find 'id' type");
2351 ArgTys.push_back(argT);
2352 ArgTys.push_back(argT);
2353 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2354 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002355 false, 0,
2356 false, false, 0, 0, false,
2357 CC_Default);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002358 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002359 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002360 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002361 FunctionDecl::Extern, false);
Steve Naroff17978c42008-03-11 17:37:02 +00002362}
2363
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002364// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002365void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002366 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2367 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002368 QualType argT = Context->getObjCIdType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002369 assert(!argT.isNull() && "Can't find 'id' type");
2370 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002371 argT = Context->getObjCSelType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002372 assert(!argT.isNull() && "Can't find 'SEL' type");
2373 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002374 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002375 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002376 true /*isVariadic*/, 0,
2377 false, false, 0, 0, false,
2378 CC_Default);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002379 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002380 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002381 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002382 FunctionDecl::Extern, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002383}
2384
Steve Naroff7fa2f042007-11-15 10:28:18 +00002385// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002386void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002387 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2388 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002389 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002390 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002391 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002392 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2393 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2394 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002395 argT = Context->getObjCSelType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002396 assert(!argT.isNull() && "Can't find 'SEL' type");
2397 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002398 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff7fa2f042007-11-15 10:28:18 +00002399 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002400 true /*isVariadic*/, 0,
2401 false, false, 0, 0, false,
2402 CC_Default);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002403 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002404 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002405 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002406 FunctionDecl::Extern, false);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002407}
2408
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002409// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002410void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002411 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2412 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002413 QualType argT = Context->getObjCIdType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002414 assert(!argT.isNull() && "Can't find 'id' type");
2415 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002416 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002417 assert(!argT.isNull() && "Can't find 'SEL' type");
2418 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002419 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002420 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002421 true /*isVariadic*/, 0,
2422 false, false, 0, 0, false,
2423 CC_Default);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002424 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002425 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002426 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002427 FunctionDecl::Extern, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002428}
2429
Mike Stump11289f42009-09-09 15:08:12 +00002430// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002431// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002432void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump11289f42009-09-09 15:08:12 +00002433 IdentifierInfo *msgSendIdent =
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002434 &Context->Idents.get("objc_msgSendSuper_stret");
2435 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002436 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002437 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002438 &Context->Idents.get("objc_super"));
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002439 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2440 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2441 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002442 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002443 assert(!argT.isNull() && "Can't find 'SEL' type");
2444 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002445 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002446 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002447 true /*isVariadic*/, 0,
2448 false, false, 0, 0, false,
2449 CC_Default);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002450 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002451 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002452 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002453 FunctionDecl::Extern, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002454}
2455
Steve Naroff2e4e3852008-05-08 22:02:18 +00002456// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002457void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002458 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2459 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002460 QualType argT = Context->getObjCIdType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002461 assert(!argT.isNull() && "Can't find 'id' type");
2462 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002463 argT = Context->getObjCSelType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002464 assert(!argT.isNull() && "Can't find 'SEL' type");
2465 ArgTys.push_back(argT);
Steve Naroff2e4e3852008-05-08 22:02:18 +00002466 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002467 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002468 true /*isVariadic*/, 0,
2469 false, false, 0, 0, false,
2470 CC_Default);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002471 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002472 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002473 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002474 FunctionDecl::Extern, false);
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002475}
2476
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002477// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002478void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002479 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2480 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002481 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002482 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002483 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002484 false /*isVariadic*/, 0,
2485 false, false, 0, 0, false,
2486 CC_Default);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002487 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002488 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002489 getClassIdent, getClassType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002490 FunctionDecl::Extern, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002491}
2492
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002493// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002494void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002495 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2496 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002497 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002498 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002499 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002500 false /*isVariadic*/, 0,
2501 false, false, 0, 0, false,
2502 CC_Default);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002503 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002504 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002505 getClassIdent, getClassType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002506 FunctionDecl::Extern, false);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002507}
2508
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002509Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffce8e8862008-03-15 00:55:56 +00002510 QualType strType = getConstantStringStructType();
2511
2512 std::string S = "__NSConstantStringImpl_";
Steve Naroffa6141f02008-05-31 03:35:42 +00002513
2514 std::string tmpName = InFileName;
2515 unsigned i;
2516 for (i=0; i < tmpName.length(); i++) {
2517 char c = tmpName.at(i);
2518 // replace any non alphanumeric characters with '_'.
2519 if (!isalpha(c) && (c < '0' || c > '9'))
2520 tmpName[i] = '_';
2521 }
2522 S += tmpName;
2523 S += "_";
Steve Naroffce8e8862008-03-15 00:55:56 +00002524 S += utostr(NumObjCStringLiterals++);
2525
Steve Naroff00a31762008-03-27 22:29:16 +00002526 Preamble += "static __NSConstantStringImpl " + S;
2527 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2528 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffce8e8862008-03-15 00:55:56 +00002529 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremenek2d470fc2008-09-13 05:16:45 +00002530 std::string prettyBufS;
2531 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00002532 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2533 PrintingPolicy(LangOpts));
Steve Naroff00a31762008-03-27 22:29:16 +00002534 Preamble += prettyBuf.str();
2535 Preamble += ",";
Steve Naroff94ed6dc2009-12-06 01:48:44 +00002536 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00002537
2538 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002539 &Context->Idents.get(S), strType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002540 VarDecl::Static);
Ted Kremenek5a201952009-02-07 01:47:29 +00002541 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
2542 Expr *Unop = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002543 Context->getPointerType(DRE->getType()),
Steve Naroffce8e8862008-03-15 00:55:56 +00002544 SourceLocation());
Steve Naroff265a6b92007-11-08 14:30:50 +00002545 // cast to NSConstantString *
John McCall97513962010-01-15 18:39:57 +00002546 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2547 CastExpr::CK_Unknown, Unop);
Chris Lattner2e0d2602008-01-31 19:37:57 +00002548 ReplaceStmt(Exp, cast);
Steve Naroff22216db2008-12-04 23:50:32 +00002549 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff265a6b92007-11-08 14:30:50 +00002550 return cast;
Steve Naroffa397efd2007-11-03 11:27:19 +00002551}
2552
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002553ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002554 // check if we are sending a message to 'super'
Douglas Gregorffca3a22009-01-09 17:18:27 +00002555 if (!CurMethodDef || !CurMethodDef->isInstanceMethod()) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002556
Douglas Gregor8ea1f532008-11-04 14:56:14 +00002557 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
Mike Stump11289f42009-09-09 15:08:12 +00002558 const ObjCObjectPointerType *OPT =
John McCall9dd450b2009-09-21 23:43:11 +00002559 Super->getType()->getAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00002560 assert(OPT);
2561 const ObjCInterfaceType *IT = OPT->getInterfaceType();
Chris Lattnera9b3cae2008-06-21 18:04:54 +00002562 return IT->getDecl();
2563 }
2564 return 0;
Steve Naroff7fa2f042007-11-15 10:28:18 +00002565}
2566
2567// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002568QualType RewriteObjC::getSuperStructType() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002569 if (!SuperStructDecl) {
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002570 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002571 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002572 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002573 QualType FieldTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00002574
Steve Naroff7fa2f042007-11-15 10:28:18 +00002575 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002576 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002577 // struct objc_class *super;
Mike Stump11289f42009-09-09 15:08:12 +00002578 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor91f84212008-12-11 16:49:14 +00002579
Steve Naroff7fa2f042007-11-15 10:28:18 +00002580 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002581 for (unsigned i = 0; i < 2; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002582 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2583 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002584 FieldTypes[i], 0,
2585 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002586 /*Mutable=*/false));
Douglas Gregor91f84212008-12-11 16:49:14 +00002587 }
Mike Stump11289f42009-09-09 15:08:12 +00002588
Douglas Gregord5058122010-02-11 01:19:42 +00002589 SuperStructDecl->completeDefinition();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002590 }
2591 return Context->getTagDeclType(SuperStructDecl);
2592}
2593
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002594QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffce8e8862008-03-15 00:55:56 +00002595 if (!ConstantStringDecl) {
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002596 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002597 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002598 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffce8e8862008-03-15 00:55:56 +00002599 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00002600
Steve Naroffce8e8862008-03-15 00:55:56 +00002601 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002602 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffce8e8862008-03-15 00:55:56 +00002603 // int flags;
Mike Stump11289f42009-09-09 15:08:12 +00002604 FieldTypes[1] = Context->IntTy;
Steve Naroffce8e8862008-03-15 00:55:56 +00002605 // char *str;
Mike Stump11289f42009-09-09 15:08:12 +00002606 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffce8e8862008-03-15 00:55:56 +00002607 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00002608 FieldTypes[3] = Context->LongTy;
Douglas Gregor91f84212008-12-11 16:49:14 +00002609
Steve Naroffce8e8862008-03-15 00:55:56 +00002610 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002611 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002612 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2613 ConstantStringDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00002614 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002615 FieldTypes[i], 0,
Douglas Gregor91f84212008-12-11 16:49:14 +00002616 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002617 /*Mutable=*/true));
Douglas Gregor91f84212008-12-11 16:49:14 +00002618 }
2619
Douglas Gregord5058122010-02-11 01:19:42 +00002620 ConstantStringDecl->completeDefinition();
Steve Naroffce8e8862008-03-15 00:55:56 +00002621 }
2622 return Context->getTagDeclType(ConstantStringDecl);
2623}
2624
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002625Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2626 SourceLocation StartLoc,
2627 SourceLocation EndLoc) {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002628 if (!SelGetUidFunctionDecl)
2629 SynthSelGetUidFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002630 if (!MsgSendFunctionDecl)
2631 SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002632 if (!MsgSendSuperFunctionDecl)
2633 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002634 if (!MsgSendStretFunctionDecl)
2635 SynthMsgSendStretFunctionDecl();
2636 if (!MsgSendSuperStretFunctionDecl)
2637 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002638 if (!MsgSendFpretFunctionDecl)
2639 SynthMsgSendFpretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002640 if (!GetClassFunctionDecl)
2641 SynthGetClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002642 if (!GetMetaClassFunctionDecl)
2643 SynthGetMetaClassFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002644
Steve Naroff7fa2f042007-11-15 10:28:18 +00002645 // default to objc_msgSend().
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002646 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2647 // May need to use objc_msgSend_stret() as well.
2648 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroffd9803712009-04-29 16:37:50 +00002649 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2650 QualType resultType = mDecl->getResultType();
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002651 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002652 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002653 else if (resultType->isRealFloatingType())
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002654 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002655 }
Mike Stump11289f42009-09-09 15:08:12 +00002656
Steve Naroff574440f2007-10-24 22:48:43 +00002657 // Synthesize a call to objc_msgSend().
2658 llvm::SmallVector<Expr*, 8> MsgExprs;
2659 IdentifierInfo *clsName = Exp->getClassName();
Mike Stump11289f42009-09-09 15:08:12 +00002660
Steve Naroff574440f2007-10-24 22:48:43 +00002661 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2662 if (clsName) { // class message.
Steve Naroff6c79f972008-07-24 19:44:33 +00002663 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2664 // the 'super' idiom within a class method.
Daniel Dunbar07d07852009-10-18 21:17:35 +00002665 if (clsName->getName() == "super") {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002666 MsgSendFlavor = MsgSendSuperFunctionDecl;
2667 if (MsgSendStretFlavor)
2668 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2669 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002670
2671 ObjCInterfaceDecl *SuperDecl =
Steve Naroff677ab3a2008-10-27 17:20:55 +00002672 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002673
2674 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00002675
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002676 // set the receiver to self, the first argument to all methods.
Steve Naroffd9803712009-04-29 16:37:50 +00002677 InitExprs.push_back(
John McCall97513962010-01-15 18:39:57 +00002678 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2679 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002680 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroffd9803712009-04-29 16:37:50 +00002681 Context->getObjCIdType(),
John McCall97513962010-01-15 18:39:57 +00002682 SourceLocation()))
2683 ); // set the 'receiver'.
Steve Naroffd9803712009-04-29 16:37:50 +00002684
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002685 llvm::SmallVector<Expr*, 8> ClsExprs;
2686 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002687 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002688 SuperDecl->getIdentifier()->getNameStart(),
2689 SuperDecl->getIdentifier()->getLength(),
2690 false, argType, SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002691 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002692 &ClsExprs[0],
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002693 ClsExprs.size(),
2694 StartLoc,
2695 EndLoc);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002696 // To turn off a warning, type-cast to 'id'
Douglas Gregore200adc2008-10-27 19:41:14 +00002697 InitExprs.push_back( // set 'super class', using objc_getClass().
John McCall97513962010-01-15 18:39:57 +00002698 NoTypeInfoCStyleCastExpr(Context,
2699 Context->getObjCIdType(),
2700 CastExpr::CK_Unknown, Cls));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002701 // struct objc_super
2702 QualType superType = getSuperStructType();
Steve Naroff0b844f02008-03-11 18:14:26 +00002703 Expr *SuperRep;
Mike Stump11289f42009-09-09 15:08:12 +00002704
Steve Naroff0b844f02008-03-11 18:14:26 +00002705 if (LangOpts.Microsoft) {
2706 SynthSuperContructorFunctionDecl();
2707 // Simulate a contructor call...
Mike Stump11289f42009-09-09 15:08:12 +00002708 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff0b844f02008-03-11 18:14:26 +00002709 superType, SourceLocation());
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002710 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002711 InitExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002712 superType, SourceLocation());
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002713 // The code for super is a little tricky to prevent collision with
2714 // the structure definition in the header. The rewriter has it's own
2715 // internal definition (__rw_objc_super) that is uses. This is why
2716 // we need the cast below. For example:
2717 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2718 //
Ted Kremenek5a201952009-02-07 01:47:29 +00002719 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002720 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002721 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00002722 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2723 Context->getPointerType(superType),
2724 CastExpr::CK_Unknown, SuperRep);
Mike Stump11289f42009-09-09 15:08:12 +00002725 } else {
Steve Naroff0b844f02008-03-11 18:14:26 +00002726 // (struct objc_super) { <exprs from above> }
Ted Kremenek013041e2010-02-19 01:50:18 +00002727 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2728 &InitExprs[0], InitExprs.size(),
2729 SourceLocation());
John McCalle15bbff2010-01-18 19:35:47 +00002730 TypeSourceInfo *superTInfo
2731 = Context->getTrivialTypeSourceInfo(superType);
John McCall5d7aa7f2010-01-19 22:33:45 +00002732 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2733 superType, ILE, false);
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002734 // struct objc_super *
Ted Kremenek5a201952009-02-07 01:47:29 +00002735 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002736 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002737 SourceLocation());
Steve Naroff0b844f02008-03-11 18:14:26 +00002738 }
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002739 MsgExprs.push_back(SuperRep);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002740 } else {
2741 llvm::SmallVector<Expr*, 8> ClsExprs;
2742 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002743 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002744 clsName->getNameStart(),
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002745 clsName->getLength(),
2746 false, argType,
2747 SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002748 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002749 &ClsExprs[0],
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002750 ClsExprs.size(),
2751 StartLoc, EndLoc);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002752 MsgExprs.push_back(Cls);
2753 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002754 } else { // instance message.
2755 Expr *recExpr = Exp->getReceiver();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002756
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002757 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002758 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002759 if (MsgSendStretFlavor)
2760 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff7fa2f042007-11-15 10:28:18 +00002761 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002762
Steve Naroff7fa2f042007-11-15 10:28:18 +00002763 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00002764
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002765 InitExprs.push_back(
John McCall97513962010-01-15 18:39:57 +00002766 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2767 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002768 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroff97adf602008-07-16 22:35:27 +00002769 Context->getObjCIdType(),
John McCall97513962010-01-15 18:39:57 +00002770 SourceLocation()))
2771 ); // set the 'receiver'.
Mike Stump11289f42009-09-09 15:08:12 +00002772
Steve Naroff7fa2f042007-11-15 10:28:18 +00002773 llvm::SmallVector<Expr*, 8> ClsExprs;
2774 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002775 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002776 SuperDecl->getIdentifier()->getNameStart(),
2777 SuperDecl->getIdentifier()->getLength(),
2778 false, argType, SourceLocation()));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002779 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002780 &ClsExprs[0],
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002781 ClsExprs.size(),
2782 StartLoc, EndLoc);
Fariborz Jahaniand5db92b2007-12-05 17:29:46 +00002783 // To turn off a warning, type-cast to 'id'
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002784 InitExprs.push_back(
Douglas Gregore200adc2008-10-27 19:41:14 +00002785 // set 'super class', using objc_getClass().
John McCall97513962010-01-15 18:39:57 +00002786 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2787 CastExpr::CK_Unknown, Cls));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002788 // struct objc_super
2789 QualType superType = getSuperStructType();
Steve Naroff17978c42008-03-11 17:37:02 +00002790 Expr *SuperRep;
Mike Stump11289f42009-09-09 15:08:12 +00002791
Steve Naroff17978c42008-03-11 17:37:02 +00002792 if (LangOpts.Microsoft) {
2793 SynthSuperContructorFunctionDecl();
2794 // Simulate a contructor call...
Mike Stump11289f42009-09-09 15:08:12 +00002795 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff17978c42008-03-11 17:37:02 +00002796 superType, SourceLocation());
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002797 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002798 InitExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002799 superType, SourceLocation());
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002800 // The code for super is a little tricky to prevent collision with
2801 // the structure definition in the header. The rewriter has it's own
2802 // internal definition (__rw_objc_super) that is uses. This is why
2803 // we need the cast below. For example:
2804 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2805 //
Ted Kremenek5a201952009-02-07 01:47:29 +00002806 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002807 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002808 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00002809 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2810 Context->getPointerType(superType),
2811 CastExpr::CK_Unknown, SuperRep);
Steve Naroff17978c42008-03-11 17:37:02 +00002812 } else {
2813 // (struct objc_super) { <exprs from above> }
Ted Kremenek013041e2010-02-19 01:50:18 +00002814 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2815 &InitExprs[0], InitExprs.size(),
2816 SourceLocation());
John McCalle15bbff2010-01-18 19:35:47 +00002817 TypeSourceInfo *superTInfo
2818 = Context->getTrivialTypeSourceInfo(superType);
John McCall5d7aa7f2010-01-19 22:33:45 +00002819 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2820 superType, ILE, false);
Steve Naroff17978c42008-03-11 17:37:02 +00002821 }
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002822 MsgExprs.push_back(SuperRep);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002823 } else {
Fariborz Jahanianff6a4552007-12-07 21:21:21 +00002824 // Remove all type-casts because it may contain objc-style types; e.g.
2825 // Foo<Proto> *.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002826 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanianff6a4552007-12-07 21:21:21 +00002827 recExpr = CE->getSubExpr();
John McCall97513962010-01-15 18:39:57 +00002828 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2829 CastExpr::CK_Unknown, recExpr);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002830 MsgExprs.push_back(recExpr);
2831 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002832 }
Steve Naroffa397efd2007-11-03 11:27:19 +00002833 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff574440f2007-10-24 22:48:43 +00002834 llvm::SmallVector<Expr*, 8> SelExprs;
2835 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002836 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00002837 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00002838 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00002839 false, argType, SourceLocation()));
Steve Naroff574440f2007-10-24 22:48:43 +00002840 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002841 &SelExprs[0], SelExprs.size(),
2842 StartLoc,
2843 EndLoc);
Steve Naroff574440f2007-10-24 22:48:43 +00002844 MsgExprs.push_back(SelExp);
Mike Stump11289f42009-09-09 15:08:12 +00002845
Steve Naroff574440f2007-10-24 22:48:43 +00002846 // Now push any user supplied arguments.
2847 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroffe7f18192007-11-14 23:54:14 +00002848 Expr *userExpr = Exp->getArg(i);
Steve Narofff60782b2007-11-15 02:58:25 +00002849 // Make all implicit casts explicit...ICE comes in handy:-)
2850 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2851 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregore200adc2008-10-27 19:41:14 +00002852 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002853 ? Context->getObjCIdType()
Douglas Gregore200adc2008-10-27 19:41:14 +00002854 : ICE->getType();
John McCall97513962010-01-15 18:39:57 +00002855 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CastExpr::CK_Unknown,
2856 userExpr);
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002857 }
2858 // Make id<P...> cast into an 'id' cast.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002859 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002860 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregorf19b2312008-10-28 15:36:24 +00002861 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002862 userExpr = CE->getSubExpr();
John McCall97513962010-01-15 18:39:57 +00002863 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2864 CastExpr::CK_Unknown, userExpr);
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002865 }
Mike Stump11289f42009-09-09 15:08:12 +00002866 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002867 MsgExprs.push_back(userExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00002868 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2869 // out the argument in the original expression (since we aren't deleting
2870 // the ObjCMessageExpr). See RewritePropertySetter() usage for more info.
2871 //Exp->setArg(i, 0);
Steve Naroff574440f2007-10-24 22:48:43 +00002872 }
Steve Narofff36987c2007-11-04 22:37:50 +00002873 // Generate the funky cast.
2874 CastExpr *cast;
2875 llvm::SmallVector<QualType, 8> ArgTypes;
2876 QualType returnType;
Mike Stump11289f42009-09-09 15:08:12 +00002877
Steve Narofff36987c2007-11-04 22:37:50 +00002878 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff44864e42007-11-15 10:43:57 +00002879 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2880 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2881 else
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002882 ArgTypes.push_back(Context->getObjCIdType());
2883 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattnera4997152009-02-20 18:43:26 +00002884 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Narofff36987c2007-11-04 22:37:50 +00002885 // Push any user argument types.
Chris Lattnera4997152009-02-20 18:43:26 +00002886 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2887 E = OMD->param_end(); PI != E; ++PI) {
2888 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump11289f42009-09-09 15:08:12 +00002889 ? Context->getObjCIdType()
Chris Lattnera4997152009-02-20 18:43:26 +00002890 : (*PI)->getType();
Steve Naroff52c65fa2008-10-29 14:49:46 +00002891 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffa5c0db82008-12-11 21:05:33 +00002892 if (isTopLevelBlockPointerType(t)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002893 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroff52c65fa2008-10-29 14:49:46 +00002894 t = Context->getPointerType(BPT->getPointeeType());
2895 }
Steve Naroff98eb8d12007-11-05 14:36:37 +00002896 ArgTypes.push_back(t);
2897 }
Chris Lattnera4997152009-02-20 18:43:26 +00002898 returnType = OMD->getResultType()->isObjCQualifiedIdType()
2899 ? Context->getObjCIdType() : OMD->getResultType();
Fariborz Jahanianf89eb2b2010-02-24 01:25:40 +00002900 if (isTopLevelBlockPointerType(returnType)) {
2901 const BlockPointerType *BPT = returnType->getAs<BlockPointerType>();
2902 returnType = Context->getPointerType(BPT->getPointeeType());
2903 }
Steve Narofff36987c2007-11-04 22:37:50 +00002904 } else {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002905 returnType = Context->getObjCIdType();
Steve Narofff36987c2007-11-04 22:37:50 +00002906 }
2907 // Get the type, we will need to reference it in a couple spots.
Steve Naroff7fa2f042007-11-15 10:28:18 +00002908 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002909
Steve Narofff36987c2007-11-04 22:37:50 +00002910 // Create a reference to the objc_msgSend() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00002911 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002912 SourceLocation());
Steve Narofff36987c2007-11-04 22:37:50 +00002913
Mike Stump11289f42009-09-09 15:08:12 +00002914 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Narofff36987c2007-11-04 22:37:50 +00002915 // If we don't do this cast, we get the following bizarre warning/note:
2916 // xx.m:13: warning: function called through a non-compatible type
2917 // xx.m:13: note: if this code is reached, the program will abort
John McCall97513962010-01-15 18:39:57 +00002918 cast = NoTypeInfoCStyleCastExpr(Context,
2919 Context->getPointerType(Context->VoidTy),
2920 CastExpr::CK_Unknown, DRE);
Mike Stump11289f42009-09-09 15:08:12 +00002921
Steve Narofff36987c2007-11-04 22:37:50 +00002922 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00002923 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00002924 &ArgTypes[0], ArgTypes.size(),
Steve Naroff327f0f42008-03-18 02:02:04 +00002925 // If we don't have a method decl, force a variadic cast.
Douglas Gregor36c569f2010-02-21 22:15:06 +00002926 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0,
2927 false, false, 0, 0, false,
2928 CC_Default);
Steve Narofff36987c2007-11-04 22:37:50 +00002929 castType = Context->getPointerType(castType);
John McCall97513962010-01-15 18:39:57 +00002930 cast = NoTypeInfoCStyleCastExpr(Context, castType, CastExpr::CK_Unknown,
2931 cast);
Steve Narofff36987c2007-11-04 22:37:50 +00002932
2933 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002934 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump11289f42009-09-09 15:08:12 +00002935
John McCall9dd450b2009-09-21 23:43:11 +00002936 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002937 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002938 MsgExprs.size(),
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002939 FT->getResultType(), EndLoc);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002940 Stmt *ReplacingStmt = CE;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002941 if (MsgSendStretFlavor) {
2942 // We have the method which returns a struct/union. Must also generate
2943 // call to objc_msgSend_stret and hang both varieties on a conditional
2944 // expression which dictate which one to envoke depending on size of
2945 // method's return type.
Mike Stump11289f42009-09-09 15:08:12 +00002946
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002947 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00002948 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002949 SourceLocation());
2950 // Need to cast objc_msgSend_stret to "void *" (see above comment).
John McCall97513962010-01-15 18:39:57 +00002951 cast = NoTypeInfoCStyleCastExpr(Context,
2952 Context->getPointerType(Context->VoidTy),
2953 CastExpr::CK_Unknown, STDRE);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002954 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00002955 castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00002956 &ArgTypes[0], ArgTypes.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002957 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0,
2958 false, false, 0, 0, false,
2959 CC_Default);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002960 castType = Context->getPointerType(castType);
John McCall97513962010-01-15 18:39:57 +00002961 cast = NoTypeInfoCStyleCastExpr(Context, castType, CastExpr::CK_Unknown,
2962 cast);
Mike Stump11289f42009-09-09 15:08:12 +00002963
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002964 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00002965 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump11289f42009-09-09 15:08:12 +00002966
John McCall9dd450b2009-09-21 23:43:11 +00002967 FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002968 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002969 MsgExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002970 FT->getResultType(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002971
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002972 // Build sizeof(returnType)
Mike Stump11289f42009-09-09 15:08:12 +00002973 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
John McCallbcd03502009-12-07 02:54:59 +00002974 Context->getTrivialTypeSourceInfo(returnType),
Sebastian Redl6f282892008-11-11 17:56:53 +00002975 Context->getSizeType(),
2976 SourceLocation(), SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002977 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2978 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2979 // For X86 it is more complicated and some kind of target specific routine
2980 // is needed to decide what to do.
Mike Stump11289f42009-09-09 15:08:12 +00002981 unsigned IntSize =
Chris Lattner37e05872008-03-05 18:54:05 +00002982 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Mike Stump11289f42009-09-09 15:08:12 +00002983 IntegerLiteral *limit = new (Context) IntegerLiteral(llvm::APInt(IntSize, 8),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002984 Context->IntTy,
2985 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002986 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
2987 BinaryOperator::LE,
2988 Context->IntTy,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002989 SourceLocation());
2990 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump11289f42009-09-09 15:08:12 +00002991 ConditionalOperator *CondExpr =
Douglas Gregor7e112b02009-08-26 14:37:04 +00002992 new (Context) ConditionalOperator(lessThanExpr,
2993 SourceLocation(), CE,
2994 SourceLocation(), STCE, returnType);
Ted Kremenek5a201952009-02-07 01:47:29 +00002995 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002996 }
Mike Stump11289f42009-09-09 15:08:12 +00002997 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002998 return ReplacingStmt;
2999}
3000
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003001Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00003002 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3003 Exp->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003004
Steve Naroff574440f2007-10-24 22:48:43 +00003005 // Now do the actual rewrite.
Chris Lattner2e0d2602008-01-31 19:37:57 +00003006 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00003007
3008 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00003009 return ReplacingStmt;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00003010}
3011
Steve Naroffd9803712009-04-29 16:37:50 +00003012// typedef struct objc_object Protocol;
3013QualType RewriteObjC::getProtocolType() {
3014 if (!ProtocolTypeDecl) {
John McCallbcd03502009-12-07 02:54:59 +00003015 TypeSourceInfo *TInfo
3016 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroffd9803712009-04-29 16:37:50 +00003017 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00003018 SourceLocation(),
Steve Naroffd9803712009-04-29 16:37:50 +00003019 &Context->Idents.get("Protocol"),
John McCallbcd03502009-12-07 02:54:59 +00003020 TInfo);
Steve Naroffd9803712009-04-29 16:37:50 +00003021 }
3022 return Context->getTypeDeclType(ProtocolTypeDecl);
3023}
3024
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00003025/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroffd9803712009-04-29 16:37:50 +00003026/// a synthesized/forward data reference (to the protocol's metadata).
3027/// The forward references (and metadata) are generated in
3028/// RewriteObjC::HandleTranslationUnit().
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003029Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroffd9803712009-04-29 16:37:50 +00003030 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3031 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump11289f42009-09-09 15:08:12 +00003032 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Douglas Gregored6c7442009-11-23 11:41:28 +00003033 ID, getProtocolType(), 0, VarDecl::Extern);
Steve Naroffd9803712009-04-29 16:37:50 +00003034 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), SourceLocation());
3035 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
3036 Context->getPointerType(DRE->getType()),
3037 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00003038 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3039 CastExpr::CK_Unknown,
3040 DerefExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00003041 ReplaceStmt(Exp, castExpr);
3042 ProtocolExprDecls.insert(Exp->getProtocol());
Mike Stump11289f42009-09-09 15:08:12 +00003043 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffd9803712009-04-29 16:37:50 +00003044 return castExpr;
Mike Stump11289f42009-09-09 15:08:12 +00003045
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00003046}
3047
Mike Stump11289f42009-09-09 15:08:12 +00003048bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003049 const char *endBuf) {
3050 while (startBuf < endBuf) {
3051 if (*startBuf == '#') {
3052 // Skip whitespace.
3053 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3054 ;
3055 if (!strncmp(startBuf, "if", strlen("if")) ||
3056 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3057 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3058 !strncmp(startBuf, "define", strlen("define")) ||
3059 !strncmp(startBuf, "undef", strlen("undef")) ||
3060 !strncmp(startBuf, "else", strlen("else")) ||
3061 !strncmp(startBuf, "elif", strlen("elif")) ||
3062 !strncmp(startBuf, "endif", strlen("endif")) ||
3063 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3064 !strncmp(startBuf, "include", strlen("include")) ||
3065 !strncmp(startBuf, "import", strlen("import")) ||
3066 !strncmp(startBuf, "include_next", strlen("include_next")))
3067 return true;
3068 }
3069 startBuf++;
3070 }
3071 return false;
3072}
3073
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003074/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003075/// an objective-c class with ivars.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003076void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003077 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003078 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Mike Stump11289f42009-09-09 15:08:12 +00003079 assert(CDecl->getNameAsCString() &&
Douglas Gregor77324f32008-11-17 14:58:09 +00003080 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00003081 // Do not synthesize more than once.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003082 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00003083 return;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003084 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003085 int NumIvars = CDecl->ivar_size();
Steve Naroffdde78982007-11-14 19:25:57 +00003086 SourceLocation LocStart = CDecl->getLocStart();
3087 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00003088
Steve Naroffdde78982007-11-14 19:25:57 +00003089 const char *startBuf = SM->getCharacterData(LocStart);
3090 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump11289f42009-09-09 15:08:12 +00003091
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003092 // If no ivars and no root or if its root, directly or indirectly,
3093 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003094 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
3095 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner184e65d2009-04-14 23:22:57 +00003096 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003097 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003098 return;
3099 }
Mike Stump11289f42009-09-09 15:08:12 +00003100
3101 // FIXME: This has potential of causing problem. If
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003102 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003103 Result += "\nstruct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003104 Result += CDecl->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +00003105 if (LangOpts.Microsoft)
3106 Result += "_IMPL";
Steve Naroffdc5b6b22008-03-12 00:25:36 +00003107
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003108 if (NumIvars > 0) {
Steve Naroffdde78982007-11-14 19:25:57 +00003109 const char *cursor = strchr(startBuf, '{');
Mike Stump11289f42009-09-09 15:08:12 +00003110 assert((cursor && endBuf)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003111 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003112 // If the buffer contains preprocessor directives, we do more fine-grained
3113 // rewrites. This is intended to fix code that looks like (which occurs in
3114 // NSURL.h, for example):
3115 //
3116 // #ifdef XYZ
3117 // @interface Foo : NSObject
3118 // #else
3119 // @interface FooBar : NSObject
3120 // #endif
3121 // {
3122 // int i;
3123 // }
3124 // @end
3125 //
3126 // This clause is segregated to avoid breaking the common case.
3127 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump11289f42009-09-09 15:08:12 +00003128 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003129 CDecl->getClassLoc();
3130 const char *endHeader = SM->getCharacterData(L);
Chris Lattner184e65d2009-04-14 23:22:57 +00003131 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003132
Chris Lattnerf5b77512009-02-20 18:18:36 +00003133 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003134 // advance to the end of the referenced protocols.
3135 while (endHeader < cursor && *endHeader != '>') endHeader++;
3136 endHeader++;
3137 }
3138 // rewrite the original header
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003139 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003140 } else {
3141 // rewrite the original header *without* disturbing the '{'
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003142 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003143 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003144 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroffdde78982007-11-14 19:25:57 +00003145 Result = "\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003146 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00003147 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003148 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00003149 Result += "_IVARS;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003150
Steve Naroffdde78982007-11-14 19:25:57 +00003151 // insert the super class structure definition.
Chris Lattner1780a852008-01-31 19:42:41 +00003152 SourceLocation OnePastCurly =
3153 LocStart.getFileLocWithOffset(cursor-startBuf+1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003154 InsertText(OnePastCurly, Result);
Steve Naroffdde78982007-11-14 19:25:57 +00003155 }
3156 cursor++; // past '{'
Mike Stump11289f42009-09-09 15:08:12 +00003157
Steve Naroffdde78982007-11-14 19:25:57 +00003158 // Now comment out any visibility specifiers.
3159 while (cursor < endBuf) {
3160 if (*cursor == '@') {
3161 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner174a8252007-11-14 22:57:51 +00003162 // Skip whitespace.
3163 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3164 /*scan*/;
3165
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003166 // FIXME: presence of @public, etc. inside comment results in
3167 // this transformation as well, which is still correct c-code.
Steve Naroffdde78982007-11-14 19:25:57 +00003168 if (!strncmp(cursor, "public", strlen("public")) ||
3169 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffaf91b9a2008-04-04 22:34:24 +00003170 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003171 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003172 InsertText(atLoc, "// ");
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003173 }
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003174 // FIXME: If there are cases where '<' is used in ivar declaration part
3175 // of user code, then scan the ivar list and use needToScanForQualifiers
3176 // for type checking.
3177 else if (*cursor == '<') {
3178 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003179 InsertText(atLoc, "/* ");
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003180 cursor = strchr(cursor, '>');
3181 cursor++;
3182 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003183 InsertText(atLoc, " */");
Steve Naroff295570a2008-10-30 12:09:33 +00003184 } else if (*cursor == '^') { // rewrite block specifier.
3185 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003186 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003187 }
Steve Naroffdde78982007-11-14 19:25:57 +00003188 cursor++;
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003189 }
Steve Naroffdde78982007-11-14 19:25:57 +00003190 // Don't forget to add a ';'!!
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003191 InsertText(LocEnd.getFileLocWithOffset(1), ";");
Steve Naroffdde78982007-11-14 19:25:57 +00003192 } else { // we don't have any instance variables - insert super struct.
Chris Lattner184e65d2009-04-14 23:22:57 +00003193 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Naroffdde78982007-11-14 19:25:57 +00003194 Result += " {\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003195 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00003196 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003197 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00003198 Result += "_IVARS;\n};\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003199 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003200 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003201 // Mark this struct as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003202 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Naroff13e74872008-05-06 18:26:51 +00003203 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003204}
3205
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003206// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003207/// class methods.
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003208template<typename MethodIterator>
3209void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
3210 MethodIterator MethodEnd,
Fariborz Jahanian3df412a2007-10-25 00:14:44 +00003211 bool IsInstanceMethod,
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003212 const char *prefix,
Chris Lattner211f8b82007-10-25 17:07:24 +00003213 const char *ClassName,
3214 std::string &Result) {
Chris Lattner31bc07e2007-12-12 07:46:12 +00003215 if (MethodBegin == MethodEnd) return;
Mike Stump11289f42009-09-09 15:08:12 +00003216
Chris Lattner31bc07e2007-12-12 07:46:12 +00003217 if (!objc_impl_method) {
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003218 /* struct _objc_method {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003219 SEL _cmd;
3220 char *method_types;
3221 void *_imp;
3222 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003223 */
Chris Lattner211f8b82007-10-25 17:07:24 +00003224 Result += "\nstruct _objc_method {\n";
3225 Result += "\tSEL _cmd;\n";
3226 Result += "\tchar *method_types;\n";
3227 Result += "\tvoid *_imp;\n";
3228 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003229
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003230 objc_impl_method = true;
Fariborz Jahanian74a1cfa2007-10-19 00:36:46 +00003231 }
Mike Stump11289f42009-09-09 15:08:12 +00003232
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003233 // Build _objc_method_list for class's methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003234
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003235 /* struct {
3236 struct _objc_method_list *next_method;
3237 int method_count;
3238 struct _objc_method method_list[];
3239 }
3240 */
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003241 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003242 Result += "\nstatic struct {\n";
3243 Result += "\tstruct _objc_method_list *next_method;\n";
3244 Result += "\tint method_count;\n";
3245 Result += "\tstruct _objc_method method_list[";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003246 Result += utostr(NumMethods);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003247 Result += "];\n} _OBJC_";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003248 Result += prefix;
3249 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
3250 Result += "_METHODS_";
3251 Result += ClassName;
Steve Naroffb327e492008-03-12 17:18:30 +00003252 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003253 Result += IsInstanceMethod ? "inst" : "cls";
3254 Result += "_meth\")))= ";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003255 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003256
Chris Lattner31bc07e2007-12-12 07:46:12 +00003257 Result += "\t,{{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00003258 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattner31bc07e2007-12-12 07:46:12 +00003259 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003260 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattner31bc07e2007-12-12 07:46:12 +00003261 Result += "\", \"";
3262 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003263 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003264 Result += MethodInternalNames[*MethodBegin];
3265 Result += "}\n";
3266 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3267 Result += "\t ,{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00003268 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003269 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003270 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003271 Result += "\", \"";
3272 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003273 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003274 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanian56338352007-11-13 21:02:00 +00003275 Result += "}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003276 }
Chris Lattner31bc07e2007-12-12 07:46:12 +00003277 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003278}
3279
Steve Naroffd9803712009-04-29 16:37:50 +00003280/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner390d39a2008-07-21 21:32:27 +00003281void RewriteObjC::
Steve Naroffd9803712009-04-29 16:37:50 +00003282RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, const char *prefix,
3283 const char *ClassName, std::string &Result) {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003284 static bool objc_protocol_methods = false;
Steve Naroffd9803712009-04-29 16:37:50 +00003285
3286 // Output struct protocol_methods holder of method selector and type.
3287 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3288 /* struct protocol_methods {
3289 SEL _cmd;
3290 char *method_types;
3291 }
3292 */
3293 Result += "\nstruct _protocol_methods {\n";
3294 Result += "\tstruct objc_selector *_cmd;\n";
3295 Result += "\tchar *method_types;\n";
3296 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003297
Steve Naroffd9803712009-04-29 16:37:50 +00003298 objc_protocol_methods = true;
3299 }
3300 // Do not synthesize the protocol more than once.
3301 if (ObjCSynthesizedProtocols.count(PDecl))
3302 return;
Mike Stump11289f42009-09-09 15:08:12 +00003303
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003304 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3305 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3306 PDecl->instmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003307 /* struct _objc_protocol_method_list {
3308 int protocol_method_count;
3309 struct protocol_methods protocols[];
3310 }
Steve Naroff251084d2008-03-12 01:06:30 +00003311 */
Steve Naroffd9803712009-04-29 16:37:50 +00003312 Result += "\nstatic struct {\n";
3313 Result += "\tint protocol_method_count;\n";
3314 Result += "\tstruct _protocol_methods protocol_methods[";
3315 Result += utostr(NumMethods);
3316 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3317 Result += PDecl->getNameAsString();
3318 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3319 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003320
Steve Naroffd9803712009-04-29 16:37:50 +00003321 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003322 for (ObjCProtocolDecl::instmeth_iterator
3323 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003324 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003325 if (I == PDecl->instmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003326 Result += "\t ,{{(struct objc_selector *)\"";
3327 else
3328 Result += "\t ,{(struct objc_selector *)\"";
3329 Result += (*I)->getSelector().getAsString().c_str();
3330 std::string MethodTypeString;
3331 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3332 Result += "\", \"";
3333 Result += MethodTypeString;
3334 Result += "\"}\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003335 }
Steve Naroffd9803712009-04-29 16:37:50 +00003336 Result += "\t }\n};\n";
3337 }
Mike Stump11289f42009-09-09 15:08:12 +00003338
Steve Naroffd9803712009-04-29 16:37:50 +00003339 // Output class methods declared in this protocol.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003340 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3341 PDecl->classmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003342 if (NumMethods > 0) {
3343 /* struct _objc_protocol_method_list {
3344 int protocol_method_count;
3345 struct protocol_methods protocols[];
3346 }
3347 */
3348 Result += "\nstatic struct {\n";
3349 Result += "\tint protocol_method_count;\n";
3350 Result += "\tstruct _protocol_methods protocol_methods[";
3351 Result += utostr(NumMethods);
3352 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3353 Result += PDecl->getNameAsString();
3354 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3355 "{\n\t";
3356 Result += utostr(NumMethods);
3357 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003358
Steve Naroffd9803712009-04-29 16:37:50 +00003359 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003360 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003361 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003362 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003363 if (I == PDecl->classmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003364 Result += "\t ,{{(struct objc_selector *)\"";
3365 else
3366 Result += "\t ,{(struct objc_selector *)\"";
3367 Result += (*I)->getSelector().getAsString().c_str();
3368 std::string MethodTypeString;
3369 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3370 Result += "\", \"";
3371 Result += MethodTypeString;
3372 Result += "\"}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003373 }
Steve Naroffd9803712009-04-29 16:37:50 +00003374 Result += "\t }\n};\n";
3375 }
3376
3377 // Output:
3378 /* struct _objc_protocol {
3379 // Objective-C 1.0 extensions
3380 struct _objc_protocol_extension *isa;
3381 char *protocol_name;
3382 struct _objc_protocol **protocol_list;
3383 struct _objc_protocol_method_list *instance_methods;
3384 struct _objc_protocol_method_list *class_methods;
Mike Stump11289f42009-09-09 15:08:12 +00003385 };
Steve Naroffd9803712009-04-29 16:37:50 +00003386 */
3387 static bool objc_protocol = false;
3388 if (!objc_protocol) {
3389 Result += "\nstruct _objc_protocol {\n";
3390 Result += "\tstruct _objc_protocol_extension *isa;\n";
3391 Result += "\tchar *protocol_name;\n";
3392 Result += "\tstruct _objc_protocol **protocol_list;\n";
3393 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3394 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003395 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003396
Steve Naroffd9803712009-04-29 16:37:50 +00003397 objc_protocol = true;
Chris Lattner388f6e92008-07-21 21:33:21 +00003398 }
Mike Stump11289f42009-09-09 15:08:12 +00003399
Steve Naroffd9803712009-04-29 16:37:50 +00003400 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3401 Result += PDecl->getNameAsString();
3402 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3403 "{\n\t0, \"";
3404 Result += PDecl->getNameAsString();
3405 Result += "\", 0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003406 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003407 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3408 Result += PDecl->getNameAsString();
3409 Result += ", ";
3410 }
3411 else
3412 Result += "0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003413 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003414 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3415 Result += PDecl->getNameAsString();
3416 Result += "\n";
3417 }
3418 else
3419 Result += "0\n";
3420 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003421
Steve Naroffd9803712009-04-29 16:37:50 +00003422 // Mark this protocol as having been generated.
3423 if (!ObjCSynthesizedProtocols.insert(PDecl))
3424 assert(false && "protocol already synthesized");
3425
3426}
3427
3428void RewriteObjC::
3429RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
3430 const char *prefix, const char *ClassName,
3431 std::string &Result) {
3432 if (Protocols.empty()) return;
Mike Stump11289f42009-09-09 15:08:12 +00003433
Steve Naroffd9803712009-04-29 16:37:50 +00003434 for (unsigned i = 0; i != Protocols.size(); i++)
3435 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3436
Chris Lattner388f6e92008-07-21 21:33:21 +00003437 // Output the top lovel protocol meta-data for the class.
3438 /* struct _objc_protocol_list {
3439 struct _objc_protocol_list *next;
3440 int protocol_count;
3441 struct _objc_protocol *class_protocols[];
3442 }
3443 */
3444 Result += "\nstatic struct {\n";
3445 Result += "\tstruct _objc_protocol_list *next;\n";
3446 Result += "\tint protocol_count;\n";
3447 Result += "\tstruct _objc_protocol *class_protocols[";
3448 Result += utostr(Protocols.size());
3449 Result += "];\n} _OBJC_";
3450 Result += prefix;
3451 Result += "_PROTOCOLS_";
3452 Result += ClassName;
3453 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3454 "{\n\t0, ";
3455 Result += utostr(Protocols.size());
3456 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003457
Chris Lattner388f6e92008-07-21 21:33:21 +00003458 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003459 Result += Protocols[0]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003460 Result += " \n";
Mike Stump11289f42009-09-09 15:08:12 +00003461
Chris Lattner388f6e92008-07-21 21:33:21 +00003462 for (unsigned i = 1; i != Protocols.size(); i++) {
3463 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003464 Result += Protocols[i]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003465 Result += "\n";
3466 }
3467 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003468}
3469
Steve Naroffd9803712009-04-29 16:37:50 +00003470
Mike Stump11289f42009-09-09 15:08:12 +00003471/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003472/// implementation.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003473void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003474 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003475 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003476 // Find category declaration for this implementation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003477 ObjCCategoryDecl *CDecl;
Mike Stump11289f42009-09-09 15:08:12 +00003478 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003479 CDecl = CDecl->getNextClassCategory())
3480 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3481 break;
Mike Stump11289f42009-09-09 15:08:12 +00003482
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003483 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003484 FullCategoryName += '_';
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003485 FullCategoryName += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003486
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003487 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003488 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003489 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003490
3491 // If any of our property implementations have associated getters or
3492 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003493 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3494 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003495 Prop != PropEnd; ++Prop) {
3496 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3497 continue;
3498 if (!(*Prop)->getPropertyIvarDecl())
3499 continue;
3500 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3501 if (!PD)
3502 continue;
3503 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3504 InstanceMethods.push_back(Getter);
3505 if (PD->isReadOnly())
3506 continue;
3507 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3508 InstanceMethods.push_back(Setter);
3509 }
3510 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003511 true, "CATEGORY_", FullCategoryName.c_str(),
3512 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003513
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003514 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003515 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003516 false, "CATEGORY_", FullCategoryName.c_str(),
3517 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003518
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003519 // Protocols referenced in class declaration?
Fariborz Jahanian989e0392007-11-13 22:09:49 +00003520 // Null CDecl is case of a category implementation with no category interface
3521 if (CDecl)
Steve Naroffd9803712009-04-29 16:37:50 +00003522 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
3523 FullCategoryName.c_str(), Result);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003524 /* struct _objc_category {
3525 char *category_name;
3526 char *class_name;
3527 struct _objc_method_list *instance_methods;
3528 struct _objc_method_list *class_methods;
3529 struct _objc_protocol_list *protocols;
3530 // Objective-C 1.0 extensions
3531 uint32_t size; // sizeof (struct _objc_category)
Mike Stump11289f42009-09-09 15:08:12 +00003532 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003533 // @property decl.
Mike Stump11289f42009-09-09 15:08:12 +00003534 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003535 */
Mike Stump11289f42009-09-09 15:08:12 +00003536
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003537 static bool objc_category = false;
3538 if (!objc_category) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003539 Result += "\nstruct _objc_category {\n";
3540 Result += "\tchar *category_name;\n";
3541 Result += "\tchar *class_name;\n";
3542 Result += "\tstruct _objc_method_list *instance_methods;\n";
3543 Result += "\tstruct _objc_method_list *class_methods;\n";
3544 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003545 Result += "\tunsigned int size;\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003546 Result += "\tstruct _objc_property_list *instance_properties;\n";
3547 Result += "};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003548 objc_category = true;
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003549 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003550 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3551 Result += FullCategoryName;
Steve Naroffb327e492008-03-12 17:18:30 +00003552 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003553 Result += IDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003554 Result += "\"\n\t, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003555 Result += ClassDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003556 Result += "\"\n";
Mike Stump11289f42009-09-09 15:08:12 +00003557
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003558 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003559 Result += "\t, (struct _objc_method_list *)"
3560 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3561 Result += FullCategoryName;
3562 Result += "\n";
3563 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003564 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003565 Result += "\t, 0\n";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003566 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003567 Result += "\t, (struct _objc_method_list *)"
3568 "&_OBJC_CATEGORY_CLASS_METHODS_";
3569 Result += FullCategoryName;
3570 Result += "\n";
3571 }
3572 else
3573 Result += "\t, 0\n";
Mike Stump11289f42009-09-09 15:08:12 +00003574
Chris Lattnerf5b77512009-02-20 18:18:36 +00003575 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump11289f42009-09-09 15:08:12 +00003576 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003577 Result += FullCategoryName;
3578 Result += "\n";
3579 }
3580 else
3581 Result += "\t, 0\n";
3582 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003583}
3584
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003585/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3586/// ivar offset.
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00003587void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCContainerDecl *IDecl,
Mike Stump11289f42009-09-09 15:08:12 +00003588 ObjCIvarDecl *ivar,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003589 std::string &Result) {
Steve Naroffde7d0f62008-07-16 18:22:22 +00003590 if (ivar->isBitField()) {
3591 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3592 // place all bitfields at offset 0.
3593 Result += "0";
3594 } else {
3595 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003596 Result += IDecl->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003597 if (LangOpts.Microsoft)
3598 Result += "_IMPL";
3599 Result += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003600 Result += ivar->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003601 Result += ")";
3602 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003603}
3604
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003605//===----------------------------------------------------------------------===//
3606// Meta Data Emission
3607//===----------------------------------------------------------------------===//
3608
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003609void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003610 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003611 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump11289f42009-09-09 15:08:12 +00003612
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003613 // Explictly declared @interface's are already synthesized.
Steve Naroffaac654a2009-04-20 20:09:33 +00003614 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump11289f42009-09-09 15:08:12 +00003615 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003616 // produce correct synthesis as yet.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003617 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003618 }
Mike Stump11289f42009-09-09 15:08:12 +00003619
Chris Lattner30d23e82007-12-12 07:56:42 +00003620 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003621 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump11289f42009-09-09 15:08:12 +00003622 ? IDecl->ivar_size()
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003623 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003624 if (NumIvars > 0) {
3625 static bool objc_ivar = false;
3626 if (!objc_ivar) {
3627 /* struct _objc_ivar {
3628 char *ivar_name;
3629 char *ivar_type;
3630 int ivar_offset;
Mike Stump11289f42009-09-09 15:08:12 +00003631 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003632 */
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003633 Result += "\nstruct _objc_ivar {\n";
3634 Result += "\tchar *ivar_name;\n";
3635 Result += "\tchar *ivar_type;\n";
3636 Result += "\tint ivar_offset;\n";
3637 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003638
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003639 objc_ivar = true;
3640 }
3641
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003642 /* struct {
3643 int ivar_count;
3644 struct _objc_ivar ivar_list[nIvars];
Mike Stump11289f42009-09-09 15:08:12 +00003645 };
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003646 */
Mike Stump11289f42009-09-09 15:08:12 +00003647 Result += "\nstatic struct {\n";
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003648 Result += "\tint ivar_count;\n";
3649 Result += "\tstruct _objc_ivar ivar_list[";
3650 Result += utostr(NumIvars);
3651 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003652 Result += IDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003653 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003654 "{\n\t";
3655 Result += utostr(NumIvars);
3656 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003657
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003658 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor5f662052009-04-23 03:23:08 +00003659 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003660 if (!IDecl->ivar_empty()) {
Fariborz Jahanianaef66222010-02-19 00:31:17 +00003661 for (ObjCInterfaceDecl::ivar_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003662 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor5f662052009-04-23 03:23:08 +00003663 IV != IVEnd; ++IV)
3664 IVars.push_back(*IV);
Fariborz Jahanianaef66222010-02-19 00:31:17 +00003665 IVI = IDecl->ivar_begin();
3666 IVE = IDecl->ivar_end();
Chris Lattner30d23e82007-12-12 07:56:42 +00003667 } else {
3668 IVI = CDecl->ivar_begin();
3669 IVE = CDecl->ivar_end();
3670 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003671 Result += "\t,{{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003672 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003673 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003674 std::string TmpString, StrEncoding;
3675 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3676 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003677 Result += StrEncoding;
3678 Result += "\", ";
Chris Lattner30d23e82007-12-12 07:56:42 +00003679 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003680 Result += "}\n";
Chris Lattner30d23e82007-12-12 07:56:42 +00003681 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003682 Result += "\t ,{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003683 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003684 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003685 std::string TmpString, StrEncoding;
3686 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3687 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003688 Result += StrEncoding;
3689 Result += "\", ";
Chris Lattner30d23e82007-12-12 07:56:42 +00003690 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003691 Result += "}\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003692 }
Mike Stump11289f42009-09-09 15:08:12 +00003693
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003694 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003695 }
Mike Stump11289f42009-09-09 15:08:12 +00003696
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003697 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003698 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003699 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003700
3701 // If any of our property implementations have associated getters or
3702 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003703 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3704 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003705 Prop != PropEnd; ++Prop) {
3706 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3707 continue;
3708 if (!(*Prop)->getPropertyIvarDecl())
3709 continue;
3710 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3711 if (!PD)
3712 continue;
3713 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3714 InstanceMethods.push_back(Getter);
3715 if (PD->isReadOnly())
3716 continue;
3717 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3718 InstanceMethods.push_back(Setter);
3719 }
3720 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattner86d7d912008-11-24 03:54:41 +00003721 true, "", IDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003722
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003723 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003724 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner86d7d912008-11-24 03:54:41 +00003725 false, "", IDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003726
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003727 // Protocols referenced in class declaration?
Steve Naroffd9803712009-04-29 16:37:50 +00003728 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
3729 "CLASS", CDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003730
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003731 // Declaration of class/meta-class metadata
3732 /* struct _objc_class {
3733 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003734 const char *super_class_name;
3735 char *name;
3736 long version;
3737 long info;
3738 long instance_size;
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003739 struct _objc_ivar_list *ivars;
3740 struct _objc_method_list *methods;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003741 struct objc_cache *cache;
3742 struct objc_protocol_list *protocols;
3743 const char *ivar_layout;
3744 struct _objc_class_ext *ext;
Mike Stump11289f42009-09-09 15:08:12 +00003745 };
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003746 */
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003747 static bool objc_class = false;
3748 if (!objc_class) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003749 Result += "\nstruct _objc_class {\n";
3750 Result += "\tstruct _objc_class *isa;\n";
3751 Result += "\tconst char *super_class_name;\n";
3752 Result += "\tchar *name;\n";
3753 Result += "\tlong version;\n";
3754 Result += "\tlong info;\n";
3755 Result += "\tlong instance_size;\n";
3756 Result += "\tstruct _objc_ivar_list *ivars;\n";
3757 Result += "\tstruct _objc_method_list *methods;\n";
3758 Result += "\tstruct objc_cache *cache;\n";
3759 Result += "\tstruct _objc_protocol_list *protocols;\n";
3760 Result += "\tconst char *ivar_layout;\n";
3761 Result += "\tstruct _objc_class_ext *ext;\n";
3762 Result += "};\n";
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003763 objc_class = true;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003764 }
Mike Stump11289f42009-09-09 15:08:12 +00003765
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003766 // Meta-class metadata generation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003767 ObjCInterfaceDecl *RootClass = 0;
3768 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003769 while (SuperClass) {
3770 RootClass = SuperClass;
3771 SuperClass = SuperClass->getSuperClass();
3772 }
3773 SuperClass = CDecl->getSuperClass();
Mike Stump11289f42009-09-09 15:08:12 +00003774
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003775 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003776 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003777 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003778 "{\n\t(struct _objc_class *)\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003779 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003780 Result += "\"";
3781
3782 if (SuperClass) {
3783 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003784 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003785 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003786 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003787 Result += "\"";
3788 }
3789 else {
3790 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003791 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003792 Result += "\"";
3793 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003794 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003795 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003796 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003797 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff0b844f02008-03-11 18:14:26 +00003798 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003799 Result += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003800 Result += "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003801 }
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003802 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003803 Result += ", 0\n";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003804 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003805 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003806 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003807 Result += ",0,0\n";
3808 }
Fariborz Jahanian486f7182007-10-24 20:54:23 +00003809 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003810 Result += "\t,0,0,0,0\n";
3811 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003812
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003813 // class metadata generation.
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003814 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003815 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003816 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003817 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003818 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003819 if (SuperClass) {
3820 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003821 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003822 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003823 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003824 Result += "\"";
3825 }
3826 else {
3827 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003828 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003829 Result += "\"";
3830 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003831 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003832 Result += ", 0,1";
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003833 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003834 Result += ",0";
3835 else {
3836 // class has size. Must synthesize its size.
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00003837 Result += ",sizeof(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003838 Result += CDecl->getNameAsString();
Steve Naroff14a07462008-03-10 23:33:22 +00003839 if (LangOpts.Microsoft)
3840 Result += "_IMPL";
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003841 Result += ")";
3842 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003843 if (NumIvars > 0) {
Steve Naroff17978c42008-03-11 17:37:02 +00003844 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003845 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003846 Result += "\n\t";
3847 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003848 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003849 Result += ",0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003850 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003851 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003852 Result += CDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003853 Result += ", 0\n\t";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003854 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003855 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003856 Result += ",0,0";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003857 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003858 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003859 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003860 Result += ", 0,0\n";
3861 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003862 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003863 Result += ",0,0,0\n";
3864 Result += "};\n";
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003865}
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003866
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003867/// RewriteImplementations - This routine rewrites all method implementations
3868/// and emits meta-data.
3869
Steve Narofff8cfd162008-11-13 20:07:04 +00003870void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003871 int ClsDefCount = ClassImplementation.size();
3872 int CatDefCount = CategoryImplementation.size();
Mike Stump11289f42009-09-09 15:08:12 +00003873
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003874 // Rewrite implemented methods
3875 for (int i = 0; i < ClsDefCount; i++)
3876 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump11289f42009-09-09 15:08:12 +00003877
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00003878 for (int i = 0; i < CatDefCount; i++)
3879 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofff8cfd162008-11-13 20:07:04 +00003880}
Mike Stump11289f42009-09-09 15:08:12 +00003881
Steve Narofff8cfd162008-11-13 20:07:04 +00003882void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3883 int ClsDefCount = ClassImplementation.size();
3884 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00003885
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003886 // For each implemented class, write out all its meta data.
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003887 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003888 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump11289f42009-09-09 15:08:12 +00003889
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003890 // For each implemented category, write out all its meta data.
3891 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003892 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroffd9803712009-04-29 16:37:50 +00003893
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003894 // Write objc_symtab metadata
3895 /*
3896 struct _objc_symtab
3897 {
3898 long sel_ref_cnt;
3899 SEL *refs;
3900 short cls_def_cnt;
3901 short cat_def_cnt;
3902 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump11289f42009-09-09 15:08:12 +00003903 };
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003904 */
Mike Stump11289f42009-09-09 15:08:12 +00003905
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003906 Result += "\nstruct _objc_symtab {\n";
3907 Result += "\tlong sel_ref_cnt;\n";
3908 Result += "\tSEL *refs;\n";
3909 Result += "\tshort cls_def_cnt;\n";
3910 Result += "\tshort cat_def_cnt;\n";
3911 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3912 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00003913
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003914 Result += "static struct _objc_symtab "
Steve Naroffb327e492008-03-12 17:18:30 +00003915 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003916 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003917 + ", " + utostr(CatDefCount) + "\n";
3918 for (int i = 0; i < ClsDefCount; i++) {
3919 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003920 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003921 Result += "\n";
3922 }
Mike Stump11289f42009-09-09 15:08:12 +00003923
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003924 for (int i = 0; i < CatDefCount; i++) {
3925 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003926 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003927 Result += "_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003928 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003929 Result += "\n";
3930 }
Mike Stump11289f42009-09-09 15:08:12 +00003931
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003932 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00003933
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003934 // Write objc_module metadata
Mike Stump11289f42009-09-09 15:08:12 +00003935
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003936 /*
3937 struct _objc_module {
3938 long version;
3939 long size;
3940 const char *name;
3941 struct _objc_symtab *symtab;
3942 }
3943 */
Mike Stump11289f42009-09-09 15:08:12 +00003944
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003945 Result += "\nstruct _objc_module {\n";
3946 Result += "\tlong version;\n";
3947 Result += "\tlong size;\n";
3948 Result += "\tconst char *name;\n";
3949 Result += "\tstruct _objc_symtab *symtab;\n";
3950 Result += "};\n\n";
3951 Result += "static struct _objc_module "
Steve Naroffb327e492008-03-12 17:18:30 +00003952 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003953 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003954 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003955 Result += "};\n\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00003956
3957 if (LangOpts.Microsoft) {
Steve Naroffd9803712009-04-29 16:37:50 +00003958 if (ProtocolExprDecls.size()) {
3959 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
3960 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump11289f42009-09-09 15:08:12 +00003961 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00003962 E = ProtocolExprDecls.end(); I != E; ++I) {
3963 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
3964 Result += (*I)->getNameAsString();
3965 Result += " = &_OBJC_PROTOCOL_";
3966 Result += (*I)->getNameAsString();
3967 Result += ";\n";
3968 }
3969 Result += "#pragma data_seg(pop)\n\n";
3970 }
Steve Naroff945a3b12008-03-10 20:43:59 +00003971 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroffcab93d52008-05-07 00:06:16 +00003972 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00003973 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3974 Result += "&_OBJC_MODULES;\n";
3975 Result += "#pragma data_seg(pop)\n\n";
3976 }
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003977}
Chris Lattnera7c19fe2007-10-16 22:36:42 +00003978
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00003979void RewriteObjC::RewriteByRefString(std::string &ResultStr,
3980 const std::string &Name,
3981 ValueDecl *VD) {
3982 assert(BlockByRefDeclNo.count(VD) &&
3983 "RewriteByRefString: ByRef decl missing");
3984 ResultStr += "struct __Block_byref_" + Name +
3985 "_" + utostr(BlockByRefDeclNo[VD]) ;
3986}
3987
Steve Naroff677ab3a2008-10-27 17:20:55 +00003988std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3989 const char *funcName,
3990 std::string Tag) {
3991 const FunctionType *AFT = CE->getFunctionType();
3992 QualType RT = AFT->getResultType();
3993 std::string StructRef = "struct " + Tag;
3994 std::string S = "static " + RT.getAsString() + " __" +
3995 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00003996
Steve Naroff677ab3a2008-10-27 17:20:55 +00003997 BlockDecl *BD = CE->getBlockDecl();
Mike Stump11289f42009-09-09 15:08:12 +00003998
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003999 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump11289f42009-09-09 15:08:12 +00004000 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Narofff26a1d42009-02-02 17:19:26 +00004001 // block (to reference imported block decl refs).
4002 S += "(" + StructRef + " *__cself)";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004003 } else if (BD->param_empty()) {
4004 S += "(" + StructRef + " *__cself)";
4005 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004006 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004007 assert(FT && "SynthesizeBlockFunc: No function proto");
4008 S += '(';
4009 // first add the implicit argument.
4010 S += StructRef + " *__cself, ";
4011 std::string ParamStr;
4012 for (BlockDecl::param_iterator AI = BD->param_begin(),
4013 E = BD->param_end(); AI != E; ++AI) {
4014 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004015 ParamStr = (*AI)->getNameAsString();
Douglas Gregor7de59662009-05-29 20:38:28 +00004016 (*AI)->getType().getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004017 S += ParamStr;
4018 }
4019 if (FT->isVariadic()) {
4020 if (!BD->param_empty()) S += ", ";
4021 S += "...";
4022 }
4023 S += ')';
4024 }
4025 S += " {\n";
Mike Stump11289f42009-09-09 15:08:12 +00004026
Steve Naroff677ab3a2008-10-27 17:20:55 +00004027 // Create local declarations to avoid rewriting all closure decl ref exprs.
4028 // First, emit a declaration for all "by ref" decls.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004029 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004030 E = BlockByRefDecls.end(); I != E; ++I) {
4031 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004032 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004033 std::string TypeString;
4034 RewriteByRefString(TypeString, Name, (*I));
4035 TypeString += " *";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004036 Name = TypeString + Name;
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004037 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump11289f42009-09-09 15:08:12 +00004038 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004039 // Next, emit a declaration for all "by copy" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004040 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004041 E = BlockByCopyDecls.end(); I != E; ++I) {
4042 S += " ";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004043 // Handle nested closure invocation. For example:
4044 //
4045 // void (^myImportedClosure)(void);
4046 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00004047 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00004048 // void (^anotherClosure)(void);
4049 // anotherClosure = ^(void) {
4050 // myImportedClosure(); // import and invoke the closure
4051 // };
4052 //
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00004053 if (isTopLevelBlockPointerType((*I)->getType())) {
4054 RewriteBlockPointerTypeVariable(S, (*I));
4055 S += " = (";
4056 RewriteBlockPointerType(S, (*I)->getType());
4057 S += ")";
4058 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4059 }
4060 else {
Fariborz Jahanianb6a68c02010-02-16 17:26:03 +00004061 std::string Name = (*I)->getNameAsString();
Douglas Gregor7de59662009-05-29 20:38:28 +00004062 (*I)->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00004063 S += Name + " = __cself->" +
4064 (*I)->getNameAsString() + "; // bound by copy\n";
4065 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004066 }
4067 std::string RewrittenStr = RewrittenBlockExprs[CE];
4068 const char *cstr = RewrittenStr.c_str();
4069 while (*cstr++ != '{') ;
4070 S += cstr;
4071 S += "\n";
4072 return S;
4073}
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00004074
Steve Naroff677ab3a2008-10-27 17:20:55 +00004075std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
4076 const char *funcName,
4077 std::string Tag) {
4078 std::string StructRef = "struct " + Tag;
4079 std::string S = "static void __";
Mike Stump11289f42009-09-09 15:08:12 +00004080
Steve Naroff677ab3a2008-10-27 17:20:55 +00004081 S += funcName;
4082 S += "_block_copy_" + utostr(i);
4083 S += "(" + StructRef;
4084 S += "*dst, " + StructRef;
4085 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00004086 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004087 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00004088 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004089 S += (*I)->getNameAsString();
Steve Naroff5ac4eac2008-12-11 20:51:38 +00004090 S += ", (void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004091 S += (*I)->getNameAsString();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004092 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00004093 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00004094 else
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00004095 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004096 }
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00004097 S += "}\n";
4098
Steve Naroff677ab3a2008-10-27 17:20:55 +00004099 S += "\nstatic void __";
4100 S += funcName;
4101 S += "_block_dispose_" + utostr(i);
4102 S += "(" + StructRef;
4103 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00004104 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004105 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00004106 S += "_Block_object_dispose((void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004107 S += (*I)->getNameAsString();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004108 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00004109 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00004110 else
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00004111 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004112 }
Mike Stump11289f42009-09-09 15:08:12 +00004113 S += "}\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004114 return S;
4115}
4116
Steve Naroff30484702009-12-06 21:14:13 +00004117std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4118 std::string Desc) {
Steve Naroff295570a2008-10-30 12:09:33 +00004119 std::string S = "\nstruct " + Tag;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004120 std::string Constructor = " " + Tag;
Mike Stump11289f42009-09-09 15:08:12 +00004121
Steve Naroff677ab3a2008-10-27 17:20:55 +00004122 S += " {\n struct __block_impl impl;\n";
Steve Naroff30484702009-12-06 21:14:13 +00004123 S += " struct " + Desc;
4124 S += "* Desc;\n";
Mike Stump11289f42009-09-09 15:08:12 +00004125
Steve Naroff30484702009-12-06 21:14:13 +00004126 Constructor += "(void *fp, "; // Invoke function pointer.
4127 Constructor += "struct " + Desc; // Descriptor pointer.
4128 Constructor += " *desc";
Mike Stump11289f42009-09-09 15:08:12 +00004129
Steve Naroff677ab3a2008-10-27 17:20:55 +00004130 if (BlockDeclRefs.size()) {
4131 // Output all "by copy" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004132 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004133 E = BlockByCopyDecls.end(); I != E; ++I) {
4134 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004135 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004136 std::string ArgName = "_" + FieldName;
4137 // Handle nested closure invocation. For example:
4138 //
4139 // void (^myImportedBlock)(void);
4140 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00004141 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00004142 // void (^anotherBlock)(void);
4143 // anotherBlock = ^(void) {
4144 // myImportedBlock(); // import and invoke the closure
4145 // };
4146 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00004147 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004148 S += "struct __block_impl *";
4149 Constructor += ", void *" + ArgName;
4150 } else {
Douglas Gregor7de59662009-05-29 20:38:28 +00004151 (*I)->getType().getAsStringInternal(FieldName, Context->PrintingPolicy);
4152 (*I)->getType().getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004153 Constructor += ", " + ArgName;
4154 }
4155 S += FieldName + ";\n";
4156 }
4157 // Output all "by ref" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004158 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004159 E = BlockByRefDecls.end(); I != E; ++I) {
4160 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004161 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004162 std::string ArgName = "_" + FieldName;
4163 // Handle nested closure invocation. For example:
4164 //
4165 // void (^myImportedBlock)(void);
4166 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00004167 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00004168 // void (^anotherBlock)(void);
4169 // anotherBlock = ^(void) {
4170 // myImportedBlock(); // import and invoke the closure
4171 // };
4172 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00004173 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004174 S += "struct __block_impl *";
4175 Constructor += ", void *" + ArgName;
4176 } else {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004177 std::string TypeString;
4178 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004179 TypeString += " *";
4180 FieldName = TypeString + FieldName;
4181 ArgName = TypeString + ArgName;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004182 Constructor += ", " + ArgName;
4183 }
4184 S += FieldName + "; // by ref\n";
4185 }
4186 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00004187 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00004188 if (GlobalVarDecl)
4189 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4190 else
4191 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00004192 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump11289f42009-09-09 15:08:12 +00004193
Steve Naroff30484702009-12-06 21:14:13 +00004194 Constructor += " Desc = desc;\n";
Mike Stump11289f42009-09-09 15:08:12 +00004195
Steve Naroff677ab3a2008-10-27 17:20:55 +00004196 // Initialize all "by copy" arguments.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004197 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004198 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004199 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004200 Constructor += " ";
Steve Naroffa5c0db82008-12-11 21:05:33 +00004201 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004202 Constructor += Name + " = (struct __block_impl *)_";
4203 else
4204 Constructor += Name + " = _";
4205 Constructor += Name + ";\n";
4206 }
4207 // Initialize all "by ref" arguments.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004208 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004209 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004210 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004211 Constructor += " ";
Steve Naroffa5c0db82008-12-11 21:05:33 +00004212 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004213 Constructor += Name + " = (struct __block_impl *)_";
4214 else
4215 Constructor += Name + " = _";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004216 Constructor += Name + "->__forwarding;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004217 }
4218 } else {
4219 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00004220 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00004221 if (GlobalVarDecl)
4222 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4223 else
4224 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00004225 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4226 Constructor += " Desc = desc;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004227 }
4228 Constructor += " ";
4229 Constructor += "}\n";
4230 S += Constructor;
4231 S += "};\n";
4232 return S;
4233}
4234
Steve Naroff30484702009-12-06 21:14:13 +00004235std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
4236 std::string ImplTag, int i,
4237 const char *FunName,
4238 unsigned hasCopy) {
4239 std::string S = "\nstatic struct " + DescTag;
4240
4241 S += " {\n unsigned long reserved;\n";
4242 S += " unsigned long Block_size;\n";
4243 if (hasCopy) {
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00004244 S += " void (*copy)(struct ";
4245 S += ImplTag; S += "*, struct ";
4246 S += ImplTag; S += "*);\n";
4247
4248 S += " void (*dispose)(struct ";
4249 S += ImplTag; S += "*);\n";
Steve Naroff30484702009-12-06 21:14:13 +00004250 }
4251 S += "} ";
4252
4253 S += DescTag + "_DATA = { 0, sizeof(struct ";
4254 S += ImplTag + ")";
4255 if (hasCopy) {
4256 S += ", __" + std::string(FunName) + "_block_copy_" + utostr(i);
4257 S += ", __" + std::string(FunName) + "_block_dispose_" + utostr(i);
4258 }
4259 S += "};\n";
4260 return S;
4261}
4262
Steve Naroff677ab3a2008-10-27 17:20:55 +00004263void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004264 const char *FunName) {
4265 // Insert declaration for the function in which block literal is used.
Fariborz Jahanian5c26eee2010-01-15 18:14:52 +00004266 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004267 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004268 // Insert closures that were part of the function.
4269 for (unsigned i = 0; i < Blocks.size(); i++) {
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004270 // Need to copy-in the inner copied-in variables not actually used in this
4271 // block.
4272 for (int j = 0; j < InnerDeclRefsCount[i]; j++)
4273 BlockDeclRefs.push_back(InnerDeclRefs[j]);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004274 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004275 llvm::SmallPtrSet<ValueDecl *, 8> InnerBlockValueDecls;
4276 llvm::SmallVector<BlockDeclRefExpr *, 8> InnerBlockDeclRefs;
4277 GetInnerBlockDeclRefExprs(Blocks[i]->getBody(),
4278 InnerBlockDeclRefs, InnerBlockValueDecls);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004279
Steve Naroff30484702009-12-06 21:14:13 +00004280 std::string ImplTag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
4281 std::string DescTag = "__" + std::string(FunName) + "_block_desc_" + utostr(i);
Mike Stump11289f42009-09-09 15:08:12 +00004282
Steve Naroff30484702009-12-06 21:14:13 +00004283 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004284
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004285 InsertText(FunLocStart, CI);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004286
Steve Naroff30484702009-12-06 21:14:13 +00004287 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump11289f42009-09-09 15:08:12 +00004288
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004289 InsertText(FunLocStart, CF);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004290
4291 if (ImportedBlockDecls.size()) {
Steve Naroff30484702009-12-06 21:14:13 +00004292 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004293 InsertText(FunLocStart, HF);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004294 }
Steve Naroff30484702009-12-06 21:14:13 +00004295 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4296 ImportedBlockDecls.size() > 0);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004297 InsertText(FunLocStart, BD);
Mike Stump11289f42009-09-09 15:08:12 +00004298
Steve Naroff677ab3a2008-10-27 17:20:55 +00004299 BlockDeclRefs.clear();
4300 BlockByRefDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004301 BlockByRefDeclsPtrSet.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004302 BlockByCopyDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004303 BlockByCopyDeclsPtrSet.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004304 BlockCallExprs.clear();
4305 ImportedBlockDecls.clear();
4306 }
4307 Blocks.clear();
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004308 InnerDeclRefsCount.clear();
4309 InnerDeclRefs.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004310 RewrittenBlockExprs.clear();
4311}
4312
4313void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4314 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner86d7d912008-11-24 03:54:41 +00004315 const char *FuncName = FD->getNameAsCString();
Mike Stump11289f42009-09-09 15:08:12 +00004316
Steve Naroff677ab3a2008-10-27 17:20:55 +00004317 SynthesizeBlockLiterals(FunLocStart, FuncName);
4318}
4319
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00004320static void BuildUniqueMethodName(std::string &Name,
4321 ObjCMethodDecl *MD) {
4322 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4323 Name = IFace->getNameAsCString();
4324 Name += "__" + MD->getSelector().getAsString();
4325 // Convert colons to underscores.
4326 std::string::size_type loc = 0;
4327 while ((loc = Name.find(":", loc)) != std::string::npos)
4328 Name.replace(loc, 1, "_");
4329}
4330
Steve Naroff677ab3a2008-10-27 17:20:55 +00004331void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroff295570a2008-10-30 12:09:33 +00004332 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4333 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanianb5f99c32010-01-29 01:55:49 +00004334 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00004335 std::string FuncName;
4336 BuildUniqueMethodName(FuncName, MD);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004337 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
4338}
4339
4340void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
4341 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4342 CI != E; ++CI)
4343 if (*CI) {
4344 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4345 GetBlockDeclRefExprs(CBE->getBody());
4346 else
4347 GetBlockDeclRefExprs(*CI);
4348 }
4349 // Handle specific things.
4350 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
4351 // FIXME: Handle enums.
4352 if (!isa<FunctionDecl>(CDRE->getDecl()))
4353 BlockDeclRefs.push_back(CDRE);
4354 return;
4355}
4356
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004357void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4358 llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
4359 llvm::SmallPtrSet<ValueDecl *, 8> &InnerBlockValueDecls) {
4360 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4361 CI != E; ++CI)
4362 if (*CI) {
4363 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4364 GetInnerBlockDeclRefExprs(CBE->getBody(),
4365 InnerBlockDeclRefs,
4366 InnerBlockValueDecls);
4367 else
4368 GetInnerBlockDeclRefExprs(*CI,
4369 InnerBlockDeclRefs,
4370 InnerBlockValueDecls);
4371
4372 }
4373 // Handle specific things.
4374 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
4375 if (!isa<FunctionDecl>(CDRE->getDecl()) &&
4376 !CDRE->isByRef() &&
Fariborz Jahanian5743d4d2010-02-26 19:05:20 +00004377 !isa<ParmVarDecl>(CDRE->getDecl()) &&
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004378 !InnerBlockValueDecls.count(CDRE->getDecl())) {
4379 InnerBlockValueDecls.insert(CDRE->getDecl());
4380 InnerBlockDeclRefs.push_back(CDRE);
4381 }
4382 return;
4383}
4384
Steve Naroff677ab3a2008-10-27 17:20:55 +00004385void RewriteObjC::GetBlockCallExprs(Stmt *S) {
4386 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4387 CI != E; ++CI)
4388 if (*CI) {
4389 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4390 GetBlockCallExprs(CBE->getBody());
4391 else
4392 GetBlockCallExprs(*CI);
4393 }
Mike Stump11289f42009-09-09 15:08:12 +00004394
Steve Naroff677ab3a2008-10-27 17:20:55 +00004395 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
4396 if (CE->getCallee()->getType()->isBlockPointerType()) {
4397 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
4398 }
4399 }
4400 return;
4401}
4402
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004403Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004404 // Navigate to relevant type information.
Steve Naroff677ab3a2008-10-27 17:20:55 +00004405 const BlockPointerType *CPT = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004406
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004407 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004408 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004409 } else if (const BlockDeclRefExpr *CDRE =
4410 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004411 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004412 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004413 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004414 }
4415 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4416 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4417 }
4418 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4419 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4420 else if (const ConditionalOperator *CEXPR =
4421 dyn_cast<ConditionalOperator>(BlockExp)) {
4422 Expr *LHSExp = CEXPR->getLHS();
4423 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4424 Expr *RHSExp = CEXPR->getRHS();
4425 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4426 Expr *CONDExp = CEXPR->getCond();
4427 ConditionalOperator *CondExpr =
4428 new (Context) ConditionalOperator(CONDExp,
4429 SourceLocation(), cast<Expr>(LHSStmt),
4430 SourceLocation(), cast<Expr>(RHSStmt),
4431 Exp->getType());
4432 return CondExpr;
Fariborz Jahanian6ab7ed42009-12-18 01:15:21 +00004433 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4434 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004435 } else {
4436 assert(1 && "RewriteBlockClass: Bad type");
4437 }
4438 assert(CPT && "RewriteBlockClass: Bad type");
John McCall9dd450b2009-09-21 23:43:11 +00004439 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004440 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004441 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004442 // FTP will be null for closures that don't take arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004443
Steve Naroff350b6652008-10-30 10:07:53 +00004444 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
4445 SourceLocation(),
4446 &Context->Idents.get("__block_impl"));
4447 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff677ab3a2008-10-27 17:20:55 +00004448
Steve Naroff350b6652008-10-30 10:07:53 +00004449 // Generate a funky cast.
4450 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00004451
Steve Naroff350b6652008-10-30 10:07:53 +00004452 // Push the block argument type.
4453 ArgTypes.push_back(PtrBlock);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004454 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004455 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff350b6652008-10-30 10:07:53 +00004456 E = FTP->arg_type_end(); I && (I != E); ++I) {
4457 QualType t = *I;
4458 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffa5c0db82008-12-11 21:05:33 +00004459 if (isTopLevelBlockPointerType(t)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004460 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroff350b6652008-10-30 10:07:53 +00004461 t = Context->getPointerType(BPT->getPointeeType());
4462 }
4463 ArgTypes.push_back(t);
4464 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004465 }
Steve Naroff350b6652008-10-30 10:07:53 +00004466 // Now do the pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00004467 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00004468 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0,
4469 false, false, 0, 0,
4470 false, CC_Default);
Mike Stump11289f42009-09-09 15:08:12 +00004471
Steve Naroff350b6652008-10-30 10:07:53 +00004472 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump11289f42009-09-09 15:08:12 +00004473
John McCall97513962010-01-15 18:39:57 +00004474 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4475 CastExpr::CK_Unknown,
4476 const_cast<Expr*>(BlockExp));
Steve Naroff350b6652008-10-30 10:07:53 +00004477 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00004478 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4479 BlkCast);
Steve Naroff350b6652008-10-30 10:07:53 +00004480 //PE->dump();
Mike Stump11289f42009-09-09 15:08:12 +00004481
Douglas Gregor91f84212008-12-11 16:49:14 +00004482 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00004483 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004484 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek5a201952009-02-07 01:47:29 +00004485 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4486 FD->getType());
Mike Stump11289f42009-09-09 15:08:12 +00004487
John McCall97513962010-01-15 18:39:57 +00004488 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4489 CastExpr::CK_Unknown, ME);
Ted Kremenek5a201952009-02-07 01:47:29 +00004490 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump11289f42009-09-09 15:08:12 +00004491
Steve Naroff350b6652008-10-30 10:07:53 +00004492 llvm::SmallVector<Expr*, 8> BlkExprs;
4493 // Add the implicit argument.
4494 BlkExprs.push_back(BlkCast);
4495 // Add the user arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004496 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004497 E = Exp->arg_end(); I != E; ++I) {
Steve Naroff350b6652008-10-30 10:07:53 +00004498 BlkExprs.push_back(*I);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004499 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004500 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4501 BlkExprs.size(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004502 Exp->getType(), SourceLocation());
Steve Naroff350b6652008-10-30 10:07:53 +00004503 return CE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004504}
4505
4506void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004507 Stmt *BlockCall = SynthesizeBlockCall(Exp, Exp->getCallee());
Steve Naroff350b6652008-10-30 10:07:53 +00004508 ReplaceStmt(Exp, BlockCall);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004509}
4510
Steve Naroffd9803712009-04-29 16:37:50 +00004511// We need to return the rewritten expression to handle cases where the
4512// BlockDeclRefExpr is embedded in another expression being rewritten.
4513// For example:
4514//
4515// int main() {
4516// __block Foo *f;
4517// __block int i;
Mike Stump11289f42009-09-09 15:08:12 +00004518//
Steve Naroffd9803712009-04-29 16:37:50 +00004519// void (^myblock)() = ^() {
4520// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4521// i = 77;
4522// };
4523//}
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004524Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanian25c07fa2009-12-23 19:26:34 +00004525 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004526 // for each DeclRefExp where BYREFVAR is name of the variable.
4527 ValueDecl *VD;
4528 bool isArrow = true;
4529 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4530 VD = BDRE->getDecl();
4531 else {
4532 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4533 isArrow = false;
4534 }
4535
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004536 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4537 &Context->Idents.get("__forwarding"),
4538 Context->VoidPtrTy, 0,
4539 /*BitWidth=*/0, /*Mutable=*/true);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004540 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4541 FD, SourceLocation(),
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004542 FD->getType());
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004543
4544 const char *Name = VD->getNameAsCString();
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004545 FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4546 &Context->Idents.get(Name),
4547 Context->VoidPtrTy, 0,
4548 /*BitWidth=*/0, /*Mutable=*/true);
4549 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004550 DeclRefExp->getType());
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004551
4552
4553
Steve Narofff26a1d42009-02-02 17:19:26 +00004554 // Need parens to enforce precedence.
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004555 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4556 ME);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004557 ReplaceStmt(DeclRefExp, PE);
Steve Naroffd9803712009-04-29 16:37:50 +00004558 return PE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004559}
4560
Steve Naroffc989a7b2008-11-03 23:29:32 +00004561void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4562 SourceLocation LocStart = CE->getLParenLoc();
4563 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofff4b992a2008-10-28 20:29:00 +00004564
4565 // Need to avoid trying to rewrite synthesized casts.
4566 if (LocStart.isInvalid())
4567 return;
Steve Naroff3e7ced12008-11-03 11:20:24 +00004568 // Need to avoid trying to rewrite casts contained in macros.
4569 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4570 return;
Mike Stump11289f42009-09-09 15:08:12 +00004571
Steve Naroff677ab3a2008-10-27 17:20:55 +00004572 const char *startBuf = SM->getCharacterData(LocStart);
4573 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00004574 QualType QT = CE->getType();
4575 const Type* TypePtr = QT->getAs<Type>();
4576 if (isa<TypeOfExprType>(TypePtr)) {
4577 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4578 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4579 std::string TypeAsString = "(";
Fariborz Jahanianf5067912010-02-18 01:20:22 +00004580 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00004581 TypeAsString += ")";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004582 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00004583 return;
4584 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004585 // advance the location to startArgList.
4586 const char *argPtr = startBuf;
Mike Stump11289f42009-09-09 15:08:12 +00004587
Steve Naroff677ab3a2008-10-27 17:20:55 +00004588 while (*argPtr++ && (argPtr < endBuf)) {
4589 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004590 case '^':
4591 // Replace the '^' with '*'.
4592 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004593 ReplaceText(LocStart, 1, "*");
Mike Stump281d6d72010-01-20 02:03:14 +00004594 break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004595 }
4596 }
4597 return;
4598}
4599
4600void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4601 SourceLocation DeclLoc = FD->getLocation();
4602 unsigned parenCount = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004603
Steve Naroff677ab3a2008-10-27 17:20:55 +00004604 // We have 1 or more arguments that have closure pointers.
4605 const char *startBuf = SM->getCharacterData(DeclLoc);
4606 const char *startArgList = strchr(startBuf, '(');
Mike Stump11289f42009-09-09 15:08:12 +00004607
Steve Naroff677ab3a2008-10-27 17:20:55 +00004608 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004609
Steve Naroff677ab3a2008-10-27 17:20:55 +00004610 parenCount++;
4611 // advance the location to startArgList.
4612 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4613 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump11289f42009-09-09 15:08:12 +00004614
Steve Naroff677ab3a2008-10-27 17:20:55 +00004615 const char *argPtr = startArgList;
Mike Stump11289f42009-09-09 15:08:12 +00004616
Steve Naroff677ab3a2008-10-27 17:20:55 +00004617 while (*argPtr++ && parenCount) {
4618 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004619 case '^':
4620 // Replace the '^' with '*'.
4621 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004622 ReplaceText(DeclLoc, 1, "*");
Mike Stump281d6d72010-01-20 02:03:14 +00004623 break;
4624 case '(':
4625 parenCount++;
4626 break;
4627 case ')':
4628 parenCount--;
4629 break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004630 }
4631 }
4632 return;
4633}
4634
4635bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004636 const FunctionProtoType *FTP;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004637 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004638 if (PT) {
John McCall9dd450b2009-09-21 23:43:11 +00004639 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004640 } else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004641 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004642 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall9dd450b2009-09-21 23:43:11 +00004643 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004644 }
4645 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004646 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004647 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +00004648 if (isTopLevelBlockPointerType(*I))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004649 return true;
4650 }
4651 return false;
4652}
4653
Ted Kremenek5a201952009-02-07 01:47:29 +00004654void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4655 const char *&RParen) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004656 const char *argPtr = strchr(Name, '(');
4657 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004658
Steve Naroff677ab3a2008-10-27 17:20:55 +00004659 LParen = argPtr; // output the start.
4660 argPtr++; // skip past the left paren.
4661 unsigned parenCount = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004662
Steve Naroff677ab3a2008-10-27 17:20:55 +00004663 while (*argPtr && parenCount) {
4664 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004665 case '(': parenCount++; break;
4666 case ')': parenCount--; break;
4667 default: break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004668 }
4669 if (parenCount) argPtr++;
4670 }
4671 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4672 RParen = argPtr; // output the end
4673}
4674
4675void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4676 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4677 RewriteBlockPointerFunctionArgs(FD);
4678 return;
Mike Stump11289f42009-09-09 15:08:12 +00004679 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004680 // Handle Variables and Typedefs.
4681 SourceLocation DeclLoc = ND->getLocation();
4682 QualType DeclT;
4683 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4684 DeclT = VD->getType();
4685 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4686 DeclT = TDD->getUnderlyingType();
4687 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4688 DeclT = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00004689 else
Steve Naroff677ab3a2008-10-27 17:20:55 +00004690 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump11289f42009-09-09 15:08:12 +00004691
Steve Naroff677ab3a2008-10-27 17:20:55 +00004692 const char *startBuf = SM->getCharacterData(DeclLoc);
4693 const char *endBuf = startBuf;
4694 // scan backward (from the decl location) for the end of the previous decl.
4695 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4696 startBuf--;
Mike Stump11289f42009-09-09 15:08:12 +00004697
Steve Naroff677ab3a2008-10-27 17:20:55 +00004698 // *startBuf != '^' if we are dealing with a pointer to function that
4699 // may take block argument types (which will be handled below).
4700 if (*startBuf == '^') {
4701 // Replace the '^' with '*', computing a negative offset.
4702 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004703 ReplaceText(DeclLoc, 1, "*");
Steve Naroff677ab3a2008-10-27 17:20:55 +00004704 }
4705 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4706 // Replace the '^' with '*' for arguments.
4707 DeclLoc = ND->getLocation();
4708 startBuf = SM->getCharacterData(DeclLoc);
4709 const char *argListBegin, *argListEnd;
4710 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4711 while (argListBegin < argListEnd) {
4712 if (*argListBegin == '^') {
4713 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004714 ReplaceText(CaretLoc, 1, "*");
Steve Naroff677ab3a2008-10-27 17:20:55 +00004715 }
4716 argListBegin++;
4717 }
4718 }
4719 return;
4720}
4721
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004722
4723/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4724/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4725/// struct Block_byref_id_object *src) {
4726/// _Block_object_assign (&_dest->object, _src->object,
4727/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4728/// [|BLOCK_FIELD_IS_WEAK]) // object
4729/// _Block_object_assign(&_dest->object, _src->object,
4730/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4731/// [|BLOCK_FIELD_IS_WEAK]) // block
4732/// }
4733/// And:
4734/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4735/// _Block_object_dispose(_src->object,
4736/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4737/// [|BLOCK_FIELD_IS_WEAK]) // object
4738/// _Block_object_dispose(_src->object,
4739/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4740/// [|BLOCK_FIELD_IS_WEAK]) // block
4741/// }
4742
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004743std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4744 int flag) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004745 std::string S;
Benjamin Kramere056cea2010-01-10 19:57:50 +00004746 if (CopyDestroyCache.count(flag))
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004747 return S;
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004748 CopyDestroyCache.insert(flag);
4749 S = "static void __Block_byref_id_object_copy_";
4750 S += utostr(flag);
4751 S += "(void *dst, void *src) {\n";
4752
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004753 // offset into the object pointer is computed as:
4754 // void * + void* + int + int + void* + void *
4755 unsigned IntSize =
4756 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4757 unsigned VoidPtrSize =
4758 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4759
4760 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/8;
4761 S += " _Block_object_assign((char*)dst + ";
4762 S += utostr(offset);
4763 S += ", *(void * *) ((char*)src + ";
4764 S += utostr(offset);
4765 S += "), ";
4766 S += utostr(flag);
4767 S += ");\n}\n";
4768
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004769 S += "static void __Block_byref_id_object_dispose_";
4770 S += utostr(flag);
4771 S += "(void *src) {\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004772 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4773 S += utostr(offset);
4774 S += "), ";
4775 S += utostr(flag);
4776 S += ");\n}\n";
4777 return S;
4778}
4779
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004780/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4781/// the declaration into:
4782/// struct __Block_byref_ND {
4783/// void *__isa; // NULL for everything except __weak pointers
4784/// struct __Block_byref_ND *__forwarding;
4785/// int32_t __flags;
4786/// int32_t __size;
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004787/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4788/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004789/// typex ND;
4790/// };
4791///
4792/// It then replaces declaration of ND variable with:
4793/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4794/// __size=sizeof(struct __Block_byref_ND),
4795/// ND=initializer-if-any};
4796///
4797///
4798void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004799 // Insert declaration for the function in which block literal is
4800 // used.
4801 if (CurFunctionDeclToDeclareForBlock)
4802 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004803 int flag = 0;
4804 int isa = 0;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004805 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4806 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian92368a12009-12-30 20:38:08 +00004807 SourceLocation X = ND->getLocEnd();
4808 X = SM->getInstantiationLoc(X);
4809 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004810 std::string Name(ND->getNameAsString());
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004811 std::string ByrefType;
4812 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004813 ByrefType += " {\n";
4814 ByrefType += " void *__isa;\n";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004815 RewriteByRefString(ByrefType, Name, ND);
4816 ByrefType += " *__forwarding;\n";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004817 ByrefType += " int __flags;\n";
4818 ByrefType += " int __size;\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004819 // Add void *__Block_byref_id_object_copy;
4820 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004821 QualType Ty = ND->getType();
4822 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4823 if (HasCopyAndDispose) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004824 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4825 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004826 }
4827
4828 Ty.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004829 ByrefType += " " + Name + ";\n";
4830 ByrefType += "};\n";
4831 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004832 SourceLocation FunLocStart;
4833 if (CurFunctionDef)
4834 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4835 else {
4836 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4837 FunLocStart = CurMethodDef->getLocStart();
4838 }
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004839 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004840 if (Ty.isObjCGCWeak()) {
4841 flag |= BLOCK_FIELD_IS_WEAK;
4842 isa = 1;
4843 }
4844
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004845 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004846 flag = BLOCK_BYREF_CALLER;
4847 QualType Ty = ND->getType();
4848 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4849 if (Ty->isBlockPointerType())
4850 flag |= BLOCK_FIELD_IS_BLOCK;
4851 else
4852 flag |= BLOCK_FIELD_IS_OBJECT;
4853 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004854 if (!HF.empty())
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004855 InsertText(FunLocStart, HF);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004856 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004857
4858 // struct __Block_byref_ND ND =
4859 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4860 // initializer-if-any};
4861 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanianf7945432010-01-05 18:15:57 +00004862 unsigned flags = 0;
4863 if (HasCopyAndDispose)
4864 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004865 Name = ND->getNameAsString();
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004866 ByrefType.clear();
4867 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004868 std::string ForwardingCastType("(");
4869 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004870 if (!hasInit) {
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004871 ByrefType += " " + Name + " = {(void*)";
4872 ByrefType += utostr(isa);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004873 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004874 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004875 ByrefType += ", ";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004876 ByrefType += "sizeof(";
4877 RewriteByRefString(ByrefType, Name, ND);
4878 ByrefType += ")";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004879 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004880 ByrefType += ", __Block_byref_id_object_copy_";
4881 ByrefType += utostr(flag);
4882 ByrefType += ", __Block_byref_id_object_dispose_";
4883 ByrefType += utostr(flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004884 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004885 ByrefType += "};\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004886 ReplaceText(DeclLoc, endBuf-startBuf+Name.size(), ByrefType);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004887 }
4888 else {
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004889 SourceLocation startLoc;
4890 Expr *E = ND->getInit();
4891 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4892 startLoc = ECE->getLParenLoc();
4893 else
4894 startLoc = E->getLocStart();
Fariborz Jahanianb8646ed2010-01-05 23:06:29 +00004895 startLoc = SM->getInstantiationLoc(startLoc);
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004896 endBuf = SM->getCharacterData(startLoc);
4897
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004898 ByrefType += " " + Name;
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004899 ByrefType += " = {(void*)";
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004900 ByrefType += utostr(isa);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004901 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004902 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004903 ByrefType += ", ";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004904 ByrefType += "sizeof(";
4905 RewriteByRefString(ByrefType, Name, ND);
4906 ByrefType += "), ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004907 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004908 ByrefType += "__Block_byref_id_object_copy_";
4909 ByrefType += utostr(flag);
4910 ByrefType += ", __Block_byref_id_object_dispose_";
4911 ByrefType += utostr(flag);
4912 ByrefType += ", ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004913 }
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004914 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroff13468372009-12-23 17:24:33 +00004915
4916 // Complete the newly synthesized compound expression by inserting a right
4917 // curly brace before the end of the declaration.
4918 // FIXME: This approach avoids rewriting the initializer expression. It
4919 // also assumes there is only one declarator. For example, the following
4920 // isn't currently supported by this routine (in general):
4921 //
4922 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4923 //
4924 const char *startBuf = SM->getCharacterData(startLoc);
4925 const char *semiBuf = strchr(startBuf, ';');
4926 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4927 SourceLocation semiLoc =
4928 startLoc.getFileLocWithOffset(semiBuf-startBuf);
4929
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004930 InsertText(semiLoc, "}");
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004931 }
Fariborz Jahanian81203462009-12-22 00:48:54 +00004932 return;
4933}
4934
Mike Stump11289f42009-09-09 15:08:12 +00004935void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004936 // Add initializers for any closure decl refs.
4937 GetBlockDeclRefExprs(Exp->getBody());
4938 if (BlockDeclRefs.size()) {
4939 // Unique all "by copy" declarations.
4940 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004941 if (!BlockDeclRefs[i]->isByRef()) {
4942 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4943 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4944 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4945 }
4946 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004947 // Unique all "by ref" declarations.
4948 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4949 if (BlockDeclRefs[i]->isByRef()) {
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004950 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4951 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4952 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4953 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004954 }
4955 // Find any imported blocks...they will need special attention.
4956 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00004957 if (BlockDeclRefs[i]->isByRef() ||
4958 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4959 BlockDeclRefs[i]->getType()->isBlockPointerType()) {
Steve Naroff832d8902008-11-13 17:40:07 +00004960 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004961 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4962 }
4963 }
4964}
4965
Steve Narofff4b992a2008-10-28 20:29:00 +00004966FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
4967 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004968 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Mike Stump11289f42009-09-09 15:08:12 +00004969 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00004970 ID, FType, 0, FunctionDecl::Extern, false,
Douglas Gregor739ef0c2009-02-25 16:33:18 +00004971 false);
Steve Narofff4b992a2008-10-28 20:29:00 +00004972}
4973
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004974Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
4975 const llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004976 Blocks.push_back(Exp);
4977
4978 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004979
4980 // Add inner imported variables now used in current block.
4981 int countOfInnerDecls = 0;
4982 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
4983 BlockDeclRefExpr *Exp = InnerBlockDeclRefs[i];
4984 ValueDecl *VD = Exp->getDecl();
4985 if (!BlockByCopyDeclsPtrSet.count(VD)) {
4986 // We need to save the copied-in variables in nested
4987 // blocks because it is needed at the end for some of the API generations.
4988 // See SynthesizeBlockLiterals routine.
4989 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4990 BlockDeclRefs.push_back(Exp);
4991 BlockByCopyDeclsPtrSet.insert(VD);
4992 BlockByCopyDecls.push_back(VD);
4993 if (Exp->getType()->isObjCObjectPointerType() ||
4994 Exp->getType()->isBlockPointerType()) {
4995 GetBlockCallExprs(Exp);
4996 ImportedBlockDecls.insert(VD);
4997 }
4998 }
4999 }
5000 InnerDeclRefsCount.push_back(countOfInnerDecls);
5001
Steve Narofff4b992a2008-10-28 20:29:00 +00005002 std::string FuncName;
Mike Stump11289f42009-09-09 15:08:12 +00005003
Steve Narofff4b992a2008-10-28 20:29:00 +00005004 if (CurFunctionDef)
Chris Lattnere4b95692008-11-24 03:33:13 +00005005 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00005006 else if (CurMethodDef)
5007 BuildUniqueMethodName(FuncName, CurMethodDef);
5008 else if (GlobalVarDecl)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005009 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump11289f42009-09-09 15:08:12 +00005010
Steve Narofff4b992a2008-10-28 20:29:00 +00005011 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump11289f42009-09-09 15:08:12 +00005012
Steve Narofff4b992a2008-10-28 20:29:00 +00005013 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
5014 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump11289f42009-09-09 15:08:12 +00005015
Steve Narofff4b992a2008-10-28 20:29:00 +00005016 // Get a pointer to the function type so we can cast appropriately.
5017 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
5018
5019 FunctionDecl *FD;
5020 Expr *NewRep;
Mike Stump11289f42009-09-09 15:08:12 +00005021
Steve Narofff4b992a2008-10-28 20:29:00 +00005022 // Simulate a contructor call...
5023 FD = SynthBlockInitFunctionDecl(Tag.c_str());
Ted Kremenek5a201952009-02-07 01:47:29 +00005024 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00005025
Steve Narofff4b992a2008-10-28 20:29:00 +00005026 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00005027
Steve Naroffe2514232008-10-29 21:23:59 +00005028 // Initialize the block function.
Steve Narofff4b992a2008-10-28 20:29:00 +00005029 FD = SynthBlockInitFunctionDecl(Func.c_str());
Ted Kremenek5a201952009-02-07 01:47:29 +00005030 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
5031 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00005032 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5033 CastExpr::CK_Unknown, Arg);
Mike Stump11289f42009-09-09 15:08:12 +00005034 InitExprs.push_back(castExpr);
5035
Steve Naroff30484702009-12-06 21:14:13 +00005036 // Initialize the block descriptor.
5037 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump11289f42009-09-09 15:08:12 +00005038
Steve Naroff30484702009-12-06 21:14:13 +00005039 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
5040 &Context->Idents.get(DescData.c_str()),
5041 Context->VoidPtrTy, 0,
5042 VarDecl::Static);
5043 UnaryOperator *DescRefExpr = new (Context) UnaryOperator(
5044 new (Context) DeclRefExpr(NewVD,
5045 Context->VoidPtrTy, SourceLocation()),
5046 UnaryOperator::AddrOf,
5047 Context->getPointerType(Context->VoidPtrTy),
5048 SourceLocation());
5049 InitExprs.push_back(DescRefExpr);
5050
Steve Narofff4b992a2008-10-28 20:29:00 +00005051 // Add initializers for any closure decl refs.
5052 if (BlockDeclRefs.size()) {
Steve Naroffe2514232008-10-29 21:23:59 +00005053 Expr *Exp;
Steve Narofff4b992a2008-10-28 20:29:00 +00005054 // Output all "by copy" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005055 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00005056 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005057 if (isObjCType((*I)->getType())) {
Steve Naroffe2514232008-10-29 21:23:59 +00005058 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner86d7d912008-11-24 03:54:41 +00005059 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00005060 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroffa5c0db82008-12-11 21:05:33 +00005061 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Chris Lattner86d7d912008-11-24 03:54:41 +00005062 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00005063 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
John McCall97513962010-01-15 18:39:57 +00005064 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5065 CastExpr::CK_Unknown, Arg);
Steve Narofff4b992a2008-10-28 20:29:00 +00005066 } else {
Chris Lattner86d7d912008-11-24 03:54:41 +00005067 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00005068 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00005069 }
Mike Stump11289f42009-09-09 15:08:12 +00005070 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00005071 }
5072 // Output all "by ref" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005073 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00005074 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005075 ValueDecl *ND = (*I);
5076 std::string Name(ND->getNameAsString());
5077 std::string RecName;
5078 RewriteByRefString(RecName, Name, ND);
5079 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5080 + sizeof("struct"));
5081 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
5082 SourceLocation(), II);
5083 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5084 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5085
Chris Lattner86d7d912008-11-24 03:54:41 +00005086 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00005087 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
5088 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00005089 Context->getPointerType(Exp->getType()),
Steve Naroffe2514232008-10-29 21:23:59 +00005090 SourceLocation());
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00005091 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CastExpr::CK_Unknown, Exp);
Mike Stump11289f42009-09-09 15:08:12 +00005092 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00005093 }
5094 }
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00005095 if (ImportedBlockDecls.size()) {
5096 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5097 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff30484702009-12-06 21:14:13 +00005098 unsigned IntSize =
5099 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00005100 Expr *FlagExp = new (Context) IntegerLiteral(llvm::APInt(IntSize, flag),
5101 Context->IntTy, SourceLocation());
5102 InitExprs.push_back(FlagExp);
Steve Naroff30484702009-12-06 21:14:13 +00005103 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00005104 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
5105 FType, SourceLocation());
Ted Kremenek5a201952009-02-07 01:47:29 +00005106 NewRep = new (Context) UnaryOperator(NewRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00005107 Context->getPointerType(NewRep->getType()),
Steve Narofff4b992a2008-10-28 20:29:00 +00005108 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00005109 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CastExpr::CK_Unknown,
5110 NewRep);
Steve Narofff4b992a2008-10-28 20:29:00 +00005111 BlockDeclRefs.clear();
5112 BlockByRefDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005113 BlockByRefDeclsPtrSet.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00005114 BlockByCopyDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00005115 BlockByCopyDeclsPtrSet.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00005116 ImportedBlockDecls.clear();
5117 return NewRep;
5118}
5119
5120//===----------------------------------------------------------------------===//
5121// Function Body / Expression rewriting
5122//===----------------------------------------------------------------------===//
5123
Steve Naroff4588d0f2008-12-04 16:24:46 +00005124// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
5125// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
5126// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
5127// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
5128// Since the rewriter isn't capable of rewriting rewritten code, it's important
5129// we get this right.
5130void RewriteObjC::CollectPropertySetters(Stmt *S) {
5131 // Perform a bottom up traversal of all children.
5132 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
5133 CI != E; ++CI)
5134 if (*CI)
5135 CollectPropertySetters(*CI);
5136
5137 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
5138 if (BinOp->isAssignmentOp()) {
5139 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
5140 PropSetters[PRE] = BinOp;
5141 }
5142 }
5143}
5144
Steve Narofff4b992a2008-10-28 20:29:00 +00005145Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump11289f42009-09-09 15:08:12 +00005146 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00005147 isa<DoStmt>(S) || isa<ForStmt>(S))
5148 Stmts.push_back(S);
5149 else if (isa<ObjCForCollectionStmt>(S)) {
5150 Stmts.push_back(S);
Chris Lattnerb71980f2010-01-09 21:45:57 +00005151 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofff4b992a2008-10-28 20:29:00 +00005152 }
Mike Stump11289f42009-09-09 15:08:12 +00005153
Steve Narofff4b992a2008-10-28 20:29:00 +00005154 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00005155
Steve Narofff4b992a2008-10-28 20:29:00 +00005156 // Perform a bottom up rewrite of all children.
5157 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
5158 CI != E; ++CI)
5159 if (*CI) {
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00005160 Stmt *newStmt;
5161 Stmt *S = (*CI);
5162 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5163 Expr *OldBase = IvarRefExpr->getBase();
5164 bool replaced = false;
5165 newStmt = RewriteObjCNestedIvarRefExpr(S, replaced);
5166 if (replaced) {
5167 if (ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(newStmt))
5168 ReplaceStmt(OldBase, IRE->getBase());
5169 else
5170 ReplaceStmt(S, newStmt);
5171 }
5172 }
5173 else
5174 newStmt = RewriteFunctionBodyOrGlobalInitializer(S);
Mike Stump11289f42009-09-09 15:08:12 +00005175 if (newStmt)
Steve Narofff4b992a2008-10-28 20:29:00 +00005176 *CI = newStmt;
5177 }
Mike Stump11289f42009-09-09 15:08:12 +00005178
Steve Narofff4b992a2008-10-28 20:29:00 +00005179 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005180 llvm::SmallPtrSet<ValueDecl *, 8> InnerBlockValueDecls;
5181 llvm::SmallVector<BlockDeclRefExpr *, 8> InnerBlockDeclRefs;
5182 GetInnerBlockDeclRefExprs(BE->getBody(),
5183 InnerBlockDeclRefs, InnerBlockValueDecls);
Steve Narofff4b992a2008-10-28 20:29:00 +00005184 // Rewrite the block body in place.
5185 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Mike Stump11289f42009-09-09 15:08:12 +00005186
Steve Narofff4b992a2008-10-28 20:29:00 +00005187 // Now we snarf the rewritten text and stash it away for later use.
Ted Kremenekdb2ef372010-01-07 18:00:35 +00005188 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroffd8907b72008-10-29 18:15:37 +00005189 RewrittenBlockExprs[BE] = Str;
Mike Stump11289f42009-09-09 15:08:12 +00005190
Fariborz Jahanian8652be02010-02-24 22:48:18 +00005191 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5192
Steve Narofff4b992a2008-10-28 20:29:00 +00005193 //blockTranscribed->dump();
Steve Naroffd8907b72008-10-29 18:15:37 +00005194 ReplaceStmt(S, blockTranscribed);
Steve Narofff4b992a2008-10-28 20:29:00 +00005195 return blockTranscribed;
5196 }
5197 // Handle specific things.
5198 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5199 return RewriteAtEncode(AtEncode);
Mike Stump11289f42009-09-09 15:08:12 +00005200
Steve Naroff4588d0f2008-12-04 16:24:46 +00005201 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
5202 BinaryOperator *BinOp = PropSetters[PropRefExpr];
5203 if (BinOp) {
5204 // Because the rewriter doesn't allow us to rewrite rewritten code,
5205 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroff08628db2008-12-09 12:56:34 +00005206 DisableReplaceStmt = true;
5207 // Save the source range. Even if we disable the replacement, the
5208 // rewritten node will have been inserted into the tree. If the synthesized
5209 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump11289f42009-09-09 15:08:12 +00005210 // self.errorHandler = handler ? handler :
Steve Naroff08628db2008-12-09 12:56:34 +00005211 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
5212 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroff4588d0f2008-12-04 16:24:46 +00005213 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroff08628db2008-12-09 12:56:34 +00005214 DisableReplaceStmt = false;
Steve Naroff22216db2008-12-04 23:50:32 +00005215 //
5216 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
5217 // we changed the RHS of BinOp, the rewriter would fail (since it needs
5218 // to see the original expression). Consider this example:
5219 //
5220 // Foo *obj1, *obj2;
5221 //
5222 // obj1.i = [obj2 rrrr];
5223 //
5224 // 'BinOp' for the previous expression looks like:
5225 //
5226 // (BinaryOperator 0x231ccf0 'int' '='
5227 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
5228 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
5229 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
5230 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
5231 //
5232 // 'newStmt' represents the rewritten message expression. For example:
5233 //
5234 // (CallExpr 0x231d300 'id':'struct objc_object *'
5235 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
5236 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
5237 // (CStyleCastExpr 0x231d220 'void *'
5238 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
5239 //
5240 // Note that 'newStmt' is passed to RewritePropertySetter so that it
5241 // can be used as the setter argument. ReplaceStmt() will still 'see'
5242 // the original RHS (since we haven't altered BinOp).
5243 //
Mike Stump11289f42009-09-09 15:08:12 +00005244 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff22216db2008-12-04 23:50:32 +00005245 // node. As a result, we now leak the original AST nodes.
5246 //
Steve Naroff08628db2008-12-09 12:56:34 +00005247 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroff4588d0f2008-12-04 16:24:46 +00005248 } else {
5249 return RewritePropertyGetter(PropRefExpr);
Steve Narofff326f402008-12-03 00:56:33 +00005250 }
5251 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005252 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5253 return RewriteAtSelector(AtSelector);
Mike Stump11289f42009-09-09 15:08:12 +00005254
Steve Narofff4b992a2008-10-28 20:29:00 +00005255 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5256 return RewriteObjCStringLiteral(AtString);
Mike Stump11289f42009-09-09 15:08:12 +00005257
Steve Narofff4b992a2008-10-28 20:29:00 +00005258 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00005259#if 0
Steve Narofff4b992a2008-10-28 20:29:00 +00005260 // Before we rewrite it, put the original message expression in a comment.
5261 SourceLocation startLoc = MessExpr->getLocStart();
5262 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00005263
Steve Narofff4b992a2008-10-28 20:29:00 +00005264 const char *startBuf = SM->getCharacterData(startLoc);
5265 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump11289f42009-09-09 15:08:12 +00005266
Steve Narofff4b992a2008-10-28 20:29:00 +00005267 std::string messString;
5268 messString += "// ";
5269 messString.append(startBuf, endBuf-startBuf+1);
5270 messString += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00005271
5272 // FIXME: Missing definition of
Steve Narofff4b992a2008-10-28 20:29:00 +00005273 // InsertText(clang::SourceLocation, char const*, unsigned int).
5274 // InsertText(startLoc, messString.c_str(), messString.size());
5275 // Tried this, but it didn't work either...
5276 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroff4588d0f2008-12-04 16:24:46 +00005277#endif
Steve Narofff4b992a2008-10-28 20:29:00 +00005278 return RewriteMessageExpr(MessExpr);
5279 }
Mike Stump11289f42009-09-09 15:08:12 +00005280
Steve Narofff4b992a2008-10-28 20:29:00 +00005281 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5282 return RewriteObjCTryStmt(StmtTry);
5283
5284 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5285 return RewriteObjCSynchronizedStmt(StmtTry);
5286
5287 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5288 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump11289f42009-09-09 15:08:12 +00005289
Steve Narofff4b992a2008-10-28 20:29:00 +00005290 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5291 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump11289f42009-09-09 15:08:12 +00005292
5293 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofff4b992a2008-10-28 20:29:00 +00005294 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump11289f42009-09-09 15:08:12 +00005295 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofff4b992a2008-10-28 20:29:00 +00005296 OrigStmtRange.getEnd());
5297 if (BreakStmt *StmtBreakStmt =
5298 dyn_cast<BreakStmt>(S))
5299 return RewriteBreakStmt(StmtBreakStmt);
5300 if (ContinueStmt *StmtContinueStmt =
5301 dyn_cast<ContinueStmt>(S))
5302 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump11289f42009-09-09 15:08:12 +00005303
5304 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofff4b992a2008-10-28 20:29:00 +00005305 // and cast exprs.
5306 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5307 // FIXME: What we're doing here is modifying the type-specifier that
5308 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump11289f42009-09-09 15:08:12 +00005309 // a separate type-specifier that we can rewrite.
Steve Naroffe70a52a2009-12-05 15:55:59 +00005310 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5311 // the context of an ObjCForCollectionStmt. For example:
5312 // NSArray *someArray;
5313 // for (id <FooProtocol> index in someArray) ;
5314 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5315 // and it depends on the original text locations/positions.
Benjamin Krameracc5fa12009-12-05 22:16:51 +00005316 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
Steve Naroffe70a52a2009-12-05 15:55:59 +00005317 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump11289f42009-09-09 15:08:12 +00005318
Steve Narofff4b992a2008-10-28 20:29:00 +00005319 // Blocks rewrite rules.
5320 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5321 DI != DE; ++DI) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +00005322 Decl *SD = *DI;
Steve Narofff4b992a2008-10-28 20:29:00 +00005323 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005324 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005325 RewriteBlockPointerDecl(ND);
Mike Stump11289f42009-09-09 15:08:12 +00005326 else if (ND->getType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005327 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00005328 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005329 if (VD->hasAttr<BlocksAttr>()) {
5330 static unsigned uniqueByrefDeclCount = 0;
5331 assert(!BlockByRefDeclNo.count(ND) &&
5332 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5333 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005334 RewriteByRefVar(VD);
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005335 }
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00005336 else
5337 RewriteTypeOfDecl(VD);
5338 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005339 }
5340 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005341 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005342 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00005343 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005344 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5345 }
5346 }
5347 }
Mike Stump11289f42009-09-09 15:08:12 +00005348
Steve Narofff4b992a2008-10-28 20:29:00 +00005349 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5350 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump11289f42009-09-09 15:08:12 +00005351
5352 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00005353 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5354 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump11289f42009-09-09 15:08:12 +00005355 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5356 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005357 && "Statement stack mismatch");
5358 Stmts.pop_back();
5359 }
5360 // Handle blocks rewriting.
5361 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
5362 if (BDRE->isByRef())
Steve Naroffd9803712009-04-29 16:37:50 +00005363 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofff4b992a2008-10-28 20:29:00 +00005364 }
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005365 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5366 ValueDecl *VD = DRE->getDecl();
5367 if (VD->hasAttr<BlocksAttr>())
5368 return RewriteBlockDeclRefExpr(DRE);
5369 }
5370
Steve Narofff4b992a2008-10-28 20:29:00 +00005371 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroff350b6652008-10-30 10:07:53 +00005372 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00005373 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroff350b6652008-10-30 10:07:53 +00005374 ReplaceStmt(S, BlockCall);
5375 return BlockCall;
5376 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005377 }
Steve Naroffc989a7b2008-11-03 23:29:32 +00005378 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005379 RewriteCastExpr(CE);
5380 }
5381#if 0
5382 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Ted Kremenek5a201952009-02-07 01:47:29 +00005383 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00005384 // Get the new text.
5385 std::string SStr;
5386 llvm::raw_string_ostream Buf(SStr);
Eli Friedman0905f142009-05-30 05:19:26 +00005387 Replacement->printPretty(Buf, *Context);
Steve Narofff4b992a2008-10-28 20:29:00 +00005388 const std::string &Str = Buf.str();
5389
5390 printf("CAST = %s\n", &Str[0]);
5391 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5392 delete S;
5393 return Replacement;
5394 }
5395#endif
5396 // Return this stmt unmodified.
5397 return S;
5398}
5399
Steve Naroffe70a52a2009-12-05 15:55:59 +00005400void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
5401 for (RecordDecl::field_iterator i = RD->field_begin(),
5402 e = RD->field_end(); i != e; ++i) {
5403 FieldDecl *FD = *i;
5404 if (isTopLevelBlockPointerType(FD->getType()))
5405 RewriteBlockPointerDecl(FD);
5406 if (FD->getType()->isObjCQualifiedIdType() ||
5407 FD->getType()->isObjCQualifiedInterfaceType())
5408 RewriteObjCQualifiedInterfaceTypes(FD);
5409 }
5410}
5411
Steve Narofff4b992a2008-10-28 20:29:00 +00005412/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5413/// main file of the input.
5414void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5415 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffb1368882008-12-17 00:20:22 +00005416 if (FD->isOverloadedOperator())
5417 return;
Mike Stump11289f42009-09-09 15:08:12 +00005418
Steve Narofff4b992a2008-10-28 20:29:00 +00005419 // Since function prototypes don't have ParmDecl's, we check the function
5420 // prototype. This enables us to rewrite function declarations and
5421 // definitions using the same code.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005422 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005423
Sebastian Redla7b98a72009-04-26 20:35:05 +00005424 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00005425 if (CompoundStmt *Body = FD->getCompoundBody()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005426 CurFunctionDef = FD;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00005427 CurFunctionDeclToDeclareForBlock = FD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005428 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005429 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00005430 Body =
5431 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5432 FD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005433 CurrentBody = 0;
5434 if (PropParentMap) {
5435 delete PropParentMap;
5436 PropParentMap = 0;
5437 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005438 // This synthesizes and inserts the block "impl" struct, invoke function,
5439 // and any copy/dispose helper functions.
5440 InsertBlockLiteralsWithinFunction(FD);
5441 CurFunctionDef = 0;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00005442 CurFunctionDeclToDeclareForBlock = 0;
Mike Stump11289f42009-09-09 15:08:12 +00005443 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005444 return;
5445 }
5446 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00005447 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005448 CurMethodDef = MD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005449 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005450 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00005451 Body =
5452 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5453 MD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005454 CurrentBody = 0;
5455 if (PropParentMap) {
5456 delete PropParentMap;
5457 PropParentMap = 0;
5458 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005459 InsertBlockLiteralsWithinMethod(MD);
5460 CurMethodDef = 0;
5461 }
5462 }
5463 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5464 ClassImplementation.push_back(CI);
5465 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5466 CategoryImplementation.push_back(CI);
5467 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
5468 RewriteForwardClassDecl(CD);
5469 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5470 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroffa5c0db82008-12-11 21:05:33 +00005471 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005472 RewriteBlockPointerDecl(VD);
Steve Naroffd8907b72008-10-29 18:15:37 +00005473 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005474 CheckFunctionPointerDecl(VD->getType(), VD);
5475 if (VD->getInit()) {
Steve Naroffc989a7b2008-11-03 23:29:32 +00005476 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005477 RewriteCastExpr(CE);
5478 }
5479 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00005480 } else if (VD->getType()->isRecordType()) {
5481 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5482 if (RD->isDefinition())
5483 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005484 }
Steve Naroffd8907b72008-10-29 18:15:37 +00005485 if (VD->getInit()) {
5486 GlobalVarDecl = VD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005487 CollectPropertySetters(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00005488 CurrentBody = VD->getInit();
Steve Naroffd8907b72008-10-29 18:15:37 +00005489 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00005490 CurrentBody = 0;
5491 if (PropParentMap) {
5492 delete PropParentMap;
5493 PropParentMap = 0;
5494 }
Mike Stump11289f42009-09-09 15:08:12 +00005495 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner86d7d912008-11-24 03:54:41 +00005496 VD->getNameAsCString());
Steve Naroffd8907b72008-10-29 18:15:37 +00005497 GlobalVarDecl = 0;
5498
5499 // This is needed for blocks.
Steve Naroffc989a7b2008-11-03 23:29:32 +00005500 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroffd8907b72008-10-29 18:15:37 +00005501 RewriteCastExpr(CE);
5502 }
5503 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005504 return;
5505 }
5506 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005507 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005508 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00005509 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005510 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5511 return;
5512 }
5513 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroffe70a52a2009-12-05 15:55:59 +00005514 if (RD->isDefinition())
5515 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005516 return;
5517 }
5518 // Nothing yet.
5519}
5520
Chris Lattnercf169832009-03-28 04:11:33 +00005521void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005522 if (Diags.hasErrorOccurred())
5523 return;
Mike Stump11289f42009-09-09 15:08:12 +00005524
Steve Narofff4b992a2008-10-28 20:29:00 +00005525 RewriteInclude();
Mike Stump11289f42009-09-09 15:08:12 +00005526
Steve Naroffd9803712009-04-29 16:37:50 +00005527 // Here's a great place to add any extra declarations that may be needed.
5528 // Write out meta data for each @protocol(<expr>).
Mike Stump11289f42009-09-09 15:08:12 +00005529 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00005530 E = ProtocolExprDecls.end(); I != E; ++I)
5531 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5532
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005533 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005534 if (ClassImplementation.size() || CategoryImplementation.size())
5535 RewriteImplementations();
Steve Naroffd9803712009-04-29 16:37:50 +00005536
Steve Narofff4b992a2008-10-28 20:29:00 +00005537 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5538 // we are done.
Mike Stump11289f42009-09-09 15:08:12 +00005539 if (const RewriteBuffer *RewriteBuf =
Steve Narofff4b992a2008-10-28 20:29:00 +00005540 Rewrite.getRewriteBufferFor(MainFileID)) {
5541 //printf("Changed:\n");
5542 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5543 } else {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005544 llvm::errs() << "No changes\n";
Steve Narofff4b992a2008-10-28 20:29:00 +00005545 }
Steve Narofff8cfd162008-11-13 20:07:04 +00005546
Steve Naroffd9803712009-04-29 16:37:50 +00005547 if (ClassImplementation.size() || CategoryImplementation.size() ||
5548 ProtocolExprDecls.size()) {
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005549 // Rewrite Objective-c meta data*
5550 std::string ResultStr;
5551 SynthesizeMetaDataIntoBuffer(ResultStr);
5552 // Emit metadata.
5553 *OutFile << ResultStr;
5554 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005555 OutFile->flush();
5556}
5557