blob: a2dd8d3f4b916b4739da123a4fa080f3f4d6df1e [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;
123 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
124 llvm::DenseMap<BlockDeclRefExpr *, CallExpr *> BlockCallExprs;
Mike Stump11289f42009-09-09 15:08:12 +0000125
Steve Naroff677ab3a2008-10-27 17:20:55 +0000126 // Block related declarations.
127 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDecls;
128 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDecls;
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +0000129 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000130 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
131
132 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
133
Steve Naroff4588d0f2008-12-04 16:24:46 +0000134 // This maps a property to it's assignment statement.
135 llvm::DenseMap<ObjCPropertyRefExpr *, BinaryOperator *> PropSetters;
Steve Naroff1042ff32008-12-08 16:43:47 +0000136 // This maps a property to it's synthesied message expression.
137 // This allows us to rewrite chained getters (e.g. o.a.b.c).
138 llvm::DenseMap<ObjCPropertyRefExpr *, Stmt *> PropGetters;
Mike Stump11289f42009-09-09 15:08:12 +0000139
Steve Naroff22216db2008-12-04 23:50:32 +0000140 // This maps an original source AST to it's rewritten form. This allows
141 // us to avoid rewriting the same node twice (which is very uncommon).
142 // This is needed to support some of the exotic property rewriting.
143 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Narofff326f402008-12-03 00:56:33 +0000144
Steve Naroff677ab3a2008-10-27 17:20:55 +0000145 FunctionDecl *CurFunctionDef;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000146 FunctionDecl *CurFunctionDeclToDeclareForBlock;
Steve Naroffd8907b72008-10-29 18:15:37 +0000147 VarDecl *GlobalVarDecl;
Mike Stump11289f42009-09-09 15:08:12 +0000148
Steve Naroff08628db2008-12-09 12:56:34 +0000149 bool DisableReplaceStmt;
Mike Stump11289f42009-09-09 15:08:12 +0000150
Fariborz Jahanian93191af2007-10-18 19:23:00 +0000151 static const int OBJC_ABI_VERSION =7 ;
Chris Lattnere99c8322007-10-11 00:43:27 +0000152 public:
Ted Kremenek380df932008-05-31 20:11:04 +0000153 virtual void Initialize(ASTContext &context);
154
Chris Lattner3c799d72007-10-24 17:06:59 +0000155 // Top Level Driver code.
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000156 virtual void HandleTopLevelDecl(DeclGroupRef D) {
157 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I)
158 HandleTopLevelSingleDecl(*I);
159 }
160 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000161 void HandleDeclInMainFile(Decl *D);
Eli Friedman94cf21e2009-05-18 22:20:00 +0000162 RewriteObjC(std::string inFile, llvm::raw_ostream *OS,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000163 Diagnostic &D, const LangOptions &LOpts,
164 bool silenceMacroWarn);
Ted Kremenek6231e7e2008-08-08 04:15:52 +0000165
166 ~RewriteObjC() {}
Mike Stump11289f42009-09-09 15:08:12 +0000167
Chris Lattnercf169832009-03-28 04:11:33 +0000168 virtual void HandleTranslationUnit(ASTContext &C);
Mike Stump11289f42009-09-09 15:08:12 +0000169
Fariborz Jahaniana7e1dcd2010-02-05 16:43:40 +0000170 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff22216db2008-12-04 23:50:32 +0000171 Stmt *ReplacingStmt = ReplacedNodes[Old];
Mike Stump11289f42009-09-09 15:08:12 +0000172
Steve Naroff22216db2008-12-04 23:50:32 +0000173 if (ReplacingStmt)
174 return; // We can't rewrite the same node twice.
Chris Lattner2e0d2602008-01-31 19:37:57 +0000175
Steve Naroff08628db2008-12-09 12:56:34 +0000176 if (DisableReplaceStmt)
177 return; // Used when rewriting the assignment of a property setter.
178
Steve Naroff22216db2008-12-04 23:50:32 +0000179 // If replacement succeeded or warning disabled return with no warning.
Fariborz Jahaniana7e1dcd2010-02-05 16:43:40 +0000180 if (!Rewrite.ReplaceStmt(Old, New)) {
Steve Naroff22216db2008-12-04 23:50:32 +0000181 ReplacedNodes[Old] = New;
182 return;
183 }
184 if (SilenceRewriteMacroWarning)
185 return;
Chris Lattner8488c822008-11-18 07:04:44 +0000186 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
187 << Old->getSourceRange();
Chris Lattner2e0d2602008-01-31 19:37:57 +0000188 }
Steve Naroff08628db2008-12-09 12:56:34 +0000189
190 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
191 // Measaure the old text.
192 int Size = Rewrite.getRangeSize(SrcRange);
193 if (Size == -1) {
194 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
195 << Old->getSourceRange();
196 return;
197 }
198 // Get the new text.
199 std::string SStr;
200 llvm::raw_string_ostream S(SStr);
Chris Lattnerc61089a2009-06-30 01:26:17 +0000201 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
Steve Naroff08628db2008-12-09 12:56:34 +0000202 const std::string &Str = S.str();
203
204 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbardec484a2009-08-19 19:10:30 +0000205 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroff08628db2008-12-09 12:56:34 +0000206 ReplacedNodes[Old] = New;
207 return;
208 }
209 if (SilenceRewriteMacroWarning)
210 return;
211 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
212 << Old->getSourceRange();
213 }
214
Steve Naroff00a31762008-03-27 22:29:16 +0000215 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
216 bool InsertAfter = true) {
Chris Lattner9cc55f52008-01-31 19:51:04 +0000217 // If insertion succeeded or warning disabled return with no warning.
Daniel Dunbardec484a2009-08-19 19:10:30 +0000218 if (!Rewrite.InsertText(Loc, llvm::StringRef(StrData, StrLen),
219 InsertAfter) ||
Chris Lattner1780a852008-01-31 19:42:41 +0000220 SilenceRewriteMacroWarning)
221 return;
Mike Stump11289f42009-09-09 15:08:12 +0000222
Chris Lattner1780a852008-01-31 19:42:41 +0000223 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
224 }
Mike Stump11289f42009-09-09 15:08:12 +0000225
Chris Lattner9cc55f52008-01-31 19:51:04 +0000226 void RemoveText(SourceLocation Loc, unsigned StrLen) {
227 // If removal succeeded or warning disabled return with no warning.
228 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
229 return;
Mike Stump11289f42009-09-09 15:08:12 +0000230
Chris Lattner9cc55f52008-01-31 19:51:04 +0000231 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
232 }
Chris Lattner3c799d72007-10-24 17:06:59 +0000233
Chris Lattner9cc55f52008-01-31 19:51:04 +0000234 void ReplaceText(SourceLocation Start, unsigned OrigLength,
235 const char *NewStr, unsigned NewLength) {
236 // If removal succeeded or warning disabled return with no warning.
Daniel Dunbardec484a2009-08-19 19:10:30 +0000237 if (!Rewrite.ReplaceText(Start, OrigLength,
238 llvm::StringRef(NewStr, NewLength)) ||
Chris Lattner9cc55f52008-01-31 19:51:04 +0000239 SilenceRewriteMacroWarning)
240 return;
Mike Stump11289f42009-09-09 15:08:12 +0000241
Chris Lattner9cc55f52008-01-31 19:51:04 +0000242 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
243 }
Mike Stump11289f42009-09-09 15:08:12 +0000244
Chris Lattner3c799d72007-10-24 17:06:59 +0000245 // Syntactic Rewriting.
Steve Narofff36987c2007-11-04 22:37:50 +0000246 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian80258362008-01-19 00:30:35 +0000247 void RewriteInclude();
Chris Lattner3c799d72007-10-24 17:06:59 +0000248 void RewriteTabs();
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000249 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffc038b3a2008-12-02 17:36:43 +0000250 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
251 ObjCImplementationDecl *IMD,
252 ObjCCategoryImplDecl *CID);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000253 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000254 void RewriteImplementationDecl(Decl *Dcl);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000255 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +0000256 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
257 ValueDecl *VD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000258 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
259 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
260 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
261 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000262 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000263 void RewriteFunctionDecl(FunctionDecl *FD);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000264 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000265 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +0000266 void RewriteTypeOfDecl(VarDecl *VD);
Steve Naroff873bd842008-07-29 18:15:38 +0000267 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroff50d42052007-11-01 13:24:47 +0000268 bool needToScanForQualifiers(QualType T);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000269 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff7fa2f042007-11-15 10:28:18 +0000270 QualType getSuperStructType();
Steve Naroffce8e8862008-03-15 00:55:56 +0000271 QualType getConstantStringStructType();
Steve Naroffcd92aeb2008-05-31 14:15:04 +0000272 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Mike Stump11289f42009-09-09 15:08:12 +0000273
Chris Lattner3c799d72007-10-24 17:06:59 +0000274 // Expression Rewriting.
Steve Naroff20113382007-11-09 15:20:18 +0000275 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroff4588d0f2008-12-04 16:24:46 +0000276 void CollectPropertySetters(Stmt *S);
Mike Stump11289f42009-09-09 15:08:12 +0000277
Steve Naroff1042ff32008-12-08 16:43:47 +0000278 Stmt *CurrentBody;
279 ParentMap *PropParentMap; // created lazily.
Mike Stump11289f42009-09-09 15:08:12 +0000280
Chris Lattner69534692007-10-24 16:57:36 +0000281 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Fariborz Jahanian80fadb52010-02-05 01:35:00 +0000282 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart,
283 bool &replaced);
284 Stmt *RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced);
Steve Naroff4588d0f2008-12-04 16:24:46 +0000285 Stmt *RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr);
Mike Stump11289f42009-09-09 15:08:12 +0000286 Stmt *RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroff08628db2008-12-09 12:56:34 +0000287 SourceRange SrcRange);
Steve Naroffe4f9b232007-11-05 14:50:49 +0000288 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner69534692007-10-24 16:57:36 +0000289 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffa397efd2007-11-03 11:27:19 +0000290 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian33c0e812007-12-07 18:47:10 +0000291 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffec60b432009-12-05 21:43:12 +0000292 void WarnAboutReturnGotoStmts(Stmt *S);
293 void HasReturnStmts(Stmt *S, bool &hasReturns);
294 void RewriteTryReturnStmts(Stmt *S);
295 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000296 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian284011b2008-01-29 22:59:37 +0000297 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000298 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
299 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
300 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattnera779d692008-01-31 05:10:40 +0000301 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
302 SourceLocation OrigEnd);
Mike Stump11289f42009-09-09 15:08:12 +0000303 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
Steve Naroff574440f2007-10-24 22:48:43 +0000304 Expr **args, unsigned nargs);
Fariborz Jahanian965a8962008-01-08 22:06:28 +0000305 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +0000306 Stmt *RewriteBreakStmt(BreakStmt *S);
307 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian965a8962008-01-08 22:06:28 +0000308 void SynthCountByEnumWithState(std::string &buf);
Mike Stump11289f42009-09-09 15:08:12 +0000309
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000310 void SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +0000311 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +0000312 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +0000313 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +0000314 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000315 void SynthGetClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +0000316 void SynthGetMetaClassFunctionDecl();
Fariborz Jahanian31e18502007-12-04 21:47:40 +0000317 void SynthSelGetUidFunctionDecl();
Steve Naroff17978c42008-03-11 17:37:02 +0000318 void SynthSuperContructorFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000319
Chris Lattner3c799d72007-10-24 17:06:59 +0000320 // Metadata emission.
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000321 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +0000322 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000323
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000324 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +0000325 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000326
Douglas Gregor29bd76f2009-04-23 01:02:12 +0000327 template<typename MethodIterator>
328 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
329 MethodIterator MethodEnd,
Fariborz Jahanian3df412a2007-10-25 00:14:44 +0000330 bool IsInstanceMethod,
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +0000331 const char *prefix,
Chris Lattner211f8b82007-10-25 17:07:24 +0000332 const char *ClassName,
333 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000334
Steve Naroffd9803712009-04-29 16:37:50 +0000335 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
336 const char *prefix,
337 const char *ClassName,
338 std::string &Result);
339 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
Mike Stump11289f42009-09-09 15:08:12 +0000340 const char *prefix,
Steve Naroffd9803712009-04-29 16:37:50 +0000341 const char *ClassName,
342 std::string &Result);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000343 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +0000344 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000345 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
346 ObjCIvarDecl *ivar,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +0000347 std::string &Result);
Steve Narofff8cfd162008-11-13 20:07:04 +0000348 void RewriteImplementations();
349 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000350
Steve Naroff677ab3a2008-10-27 17:20:55 +0000351 // Block rewriting.
Mike Stump11289f42009-09-09 15:08:12 +0000352 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000353 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
Mike Stump11289f42009-09-09 15:08:12 +0000354
Steve Naroff677ab3a2008-10-27 17:20:55 +0000355 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
356 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
Mike Stump11289f42009-09-09 15:08:12 +0000357
358 // Block specific rewrite rules.
Steve Naroff677ab3a2008-10-27 17:20:55 +0000359 void RewriteBlockCall(CallExpr *Exp);
360 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian02e07732009-12-23 02:07:37 +0000361 void RewriteByRefVar(VarDecl *VD);
Fariborz Jahaniane3891582010-01-05 18:04:40 +0000362 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +0000363 Stmt *RewriteBlockDeclRefExpr(Expr *VD);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000364 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Mike Stump11289f42009-09-09 15:08:12 +0000365
366 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Steve Naroff677ab3a2008-10-27 17:20:55 +0000367 const char *funcName, std::string Tag);
Mike Stump11289f42009-09-09 15:08:12 +0000368 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Steve Naroff677ab3a2008-10-27 17:20:55 +0000369 const char *funcName, std::string Tag);
Steve Naroff30484702009-12-06 21:14:13 +0000370 std::string SynthesizeBlockImpl(BlockExpr *CE,
371 std::string Tag, std::string Desc);
372 std::string SynthesizeBlockDescriptor(std::string DescTag,
373 std::string ImplTag,
374 int i, const char *funcName,
375 unsigned hasCopy);
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +0000376 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000377 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000378 const char *FunName);
Steve Naroffe70a52a2009-12-05 15:55:59 +0000379 void RewriteRecordBody(RecordDecl *RD);
Mike Stump11289f42009-09-09 15:08:12 +0000380
Steve Naroff677ab3a2008-10-27 17:20:55 +0000381 void CollectBlockDeclRefInfo(BlockExpr *Exp);
382 void GetBlockCallExprs(Stmt *S);
383 void GetBlockDeclRefExprs(Stmt *S);
Mike Stump11289f42009-09-09 15:08:12 +0000384
Steve Naroff677ab3a2008-10-27 17:20:55 +0000385 // We avoid calling Type::isBlockPointerType(), since it operates on the
386 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek5a201952009-02-07 01:47:29 +0000387 bool isTopLevelBlockPointerType(QualType T) {
388 return isa<BlockPointerType>(T);
389 }
Mike Stump11289f42009-09-09 15:08:12 +0000390
Steve Naroff677ab3a2008-10-27 17:20:55 +0000391 // FIXME: This predicate seems like it would be useful to add to ASTContext.
392 bool isObjCType(QualType T) {
393 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
394 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000395
Steve Naroff677ab3a2008-10-27 17:20:55 +0000396 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000397
Steve Naroff677ab3a2008-10-27 17:20:55 +0000398 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
399 OCT == Context->getCanonicalType(Context->getObjCClassType()))
400 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000401
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000402 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump11289f42009-09-09 15:08:12 +0000403 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Narofffb4330f2009-06-17 22:40:22 +0000404 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff677ab3a2008-10-27 17:20:55 +0000405 return true;
406 }
407 return false;
408 }
409 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Ted Kremenek5a201952009-02-07 01:47:29 +0000410 void GetExtentOfArgList(const char *Name, const char *&LParen,
411 const char *&RParen);
Steve Naroffc989a7b2008-11-03 23:29:32 +0000412 void RewriteCastExpr(CStyleCastExpr *CE);
Mike Stump11289f42009-09-09 15:08:12 +0000413
Steve Narofff4b992a2008-10-28 20:29:00 +0000414 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Steve Naroffd8907b72008-10-29 18:15:37 +0000415 Stmt *SynthBlockInitExpr(BlockExpr *Exp);
Mike Stump11289f42009-09-09 15:08:12 +0000416
Steve Naroffd9803712009-04-29 16:37:50 +0000417 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump11289f42009-09-09 15:08:12 +0000418 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroffd9803712009-04-29 16:37:50 +0000419 if (From[i] == '"')
420 To += "\\\"";
421 else
422 To += From[i];
423 }
424 }
Chris Lattnere99c8322007-10-11 00:43:27 +0000425 };
John McCall97513962010-01-15 18:39:57 +0000426
427 // Helper function: create a CStyleCastExpr with trivial type source info.
428 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
429 CastExpr::CastKind Kind, Expr *E) {
430 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
431 return new (Ctx) CStyleCastExpr(Ty, Kind, E, TInfo,
432 SourceLocation(), SourceLocation());
433 }
Chris Lattnere99c8322007-10-11 00:43:27 +0000434}
435
Mike Stump11289f42009-09-09 15:08:12 +0000436void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
437 NamedDecl *D) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000438 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000439 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +0000440 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +0000441 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff677ab3a2008-10-27 17:20:55 +0000442 // All the args are checked/rewritten. Don't call twice!
443 RewriteBlockPointerDecl(D);
444 break;
445 }
446 }
447}
448
449void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000450 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +0000451 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000452 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000453}
454
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000455static bool IsHeaderFile(const std::string &Filename) {
456 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump11289f42009-09-09 15:08:12 +0000457
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000458 if (DotPos == std::string::npos) {
459 // no file extension
Mike Stump11289f42009-09-09 15:08:12 +0000460 return false;
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000461 }
Mike Stump11289f42009-09-09 15:08:12 +0000462
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000463 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
464 // C header: .h
465 // C++ header: .hh or .H;
466 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump11289f42009-09-09 15:08:12 +0000467}
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000468
Eli Friedman94cf21e2009-05-18 22:20:00 +0000469RewriteObjC::RewriteObjC(std::string inFile, llvm::raw_ostream* OS,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000470 Diagnostic &D, const LangOptions &LOpts,
471 bool silenceMacroWarn)
472 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
473 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Narofff9e7c902008-03-28 22:26:09 +0000474 IsHeader = IsHeaderFile(inFile);
Mike Stump11289f42009-09-09 15:08:12 +0000475 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Steve Narofff9e7c902008-03-28 22:26:09 +0000476 "rewriting sub-expression within a macro (may not be correct)");
Mike Stump11289f42009-09-09 15:08:12 +0000477 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek5a201952009-02-07 01:47:29 +0000478 "rewriter doesn't support user-specified control flow semantics "
479 "for @try/@finally (code may not execute properly)");
Steve Narofff9e7c902008-03-28 22:26:09 +0000480}
481
Eli Friedmana63ab2d2009-05-18 22:29:17 +0000482ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
483 llvm::raw_ostream* OS,
Mike Stump11289f42009-09-09 15:08:12 +0000484 Diagnostic &Diags,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000485 const LangOptions &LOpts,
486 bool SilenceRewriteMacroWarning) {
487 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere9c810c2007-11-30 22:25:36 +0000488}
Chris Lattnere99c8322007-10-11 00:43:27 +0000489
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000490void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner187f6262008-01-31 19:38:44 +0000491 Context = &context;
492 SM = &Context->getSourceManager();
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +0000493 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner187f6262008-01-31 19:38:44 +0000494 MsgSendFunctionDecl = 0;
495 MsgSendSuperFunctionDecl = 0;
496 MsgSendStretFunctionDecl = 0;
497 MsgSendSuperStretFunctionDecl = 0;
498 MsgSendFpretFunctionDecl = 0;
499 GetClassFunctionDecl = 0;
500 GetMetaClassFunctionDecl = 0;
501 SelGetUidFunctionDecl = 0;
502 CFStringFunctionDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000503 ConstantStringClassReference = 0;
504 NSStringRecord = 0;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000505 CurMethodDef = 0;
506 CurFunctionDef = 0;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000507 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000508 GlobalVarDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000509 SuperStructDecl = 0;
Steve Naroffd9803712009-04-29 16:37:50 +0000510 ProtocolTypeDecl = 0;
Steve Naroff60a9ef62008-03-27 22:59:54 +0000511 ConstantStringDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000512 BcLabelCount = 0;
Steve Naroff17978c42008-03-11 17:37:02 +0000513 SuperContructorFunctionDecl = 0;
Steve Naroffce8e8862008-03-15 00:55:56 +0000514 NumObjCStringLiterals = 0;
Steve Narofff1ab6002008-12-08 20:01:41 +0000515 PropParentMap = 0;
516 CurrentBody = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000517 DisableReplaceStmt = false;
Fariborz Jahanianbc6811c2010-01-07 22:51:18 +0000518 objc_impl_method = false;
Mike Stump11289f42009-09-09 15:08:12 +0000519
Chris Lattner187f6262008-01-31 19:38:44 +0000520 // Get the ID and start/end of the main file.
521 MainFileID = SM->getMainFileID();
522 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
523 MainFileStart = MainBuf->getBufferStart();
524 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000525
Chris Lattner184e65d2009-04-14 23:22:57 +0000526 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump11289f42009-09-09 15:08:12 +0000527
Chris Lattner187f6262008-01-31 19:38:44 +0000528 // declaring objc_selector outside the parameter list removes a silly
529 // scope related warning...
Steve Naroff00a31762008-03-27 22:29:16 +0000530 if (IsHeader)
Steve Narofffcc6fd52009-02-03 20:39:18 +0000531 Preamble = "#pragma once\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000532 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff6ab6dc72008-12-23 20:11:22 +0000533 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroff00a31762008-03-27 22:29:16 +0000534 Preamble += "struct objc_object *superClass; ";
Steve Naroff17978c42008-03-11 17:37:02 +0000535 if (LangOpts.Microsoft) {
536 // Add a constructor for creating temporary objects.
Ted Kremenek5a201952009-02-07 01:47:29 +0000537 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
538 ": ";
Steve Naroff00a31762008-03-27 22:29:16 +0000539 Preamble += "object(o), superClass(s) {} ";
Steve Naroff17978c42008-03-11 17:37:02 +0000540 }
Steve Naroff00a31762008-03-27 22:29:16 +0000541 Preamble += "};\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000542 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
543 Preamble += "typedef struct objc_object Protocol;\n";
544 Preamble += "#define _REWRITER_typedef_Protocol\n";
545 Preamble += "#endif\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000546 if (LangOpts.Microsoft) {
547 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
548 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
549 } else
550 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
551 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroff00a31762008-03-27 22:29:16 +0000552 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000553 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroff00a31762008-03-27 22:29:16 +0000554 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000555 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroff00a31762008-03-27 22:29:16 +0000556 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000557 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroff00a31762008-03-27 22:29:16 +0000558 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000559 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroff00a31762008-03-27 22:29:16 +0000560 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000561 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroff00a31762008-03-27 22:29:16 +0000562 Preamble += "(const char *);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000563 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroff00a31762008-03-27 22:29:16 +0000564 Preamble += "(const char *);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000565 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
566 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
567 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
568 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
569 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroffd30f8c52008-05-09 21:17:56 +0000570 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff8dd15252008-07-16 18:58:11 +0000571 // @synchronized hooks.
Steve Narofff122ff02008-12-08 17:30:33 +0000572 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
573 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
574 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000575 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
576 Preamble += "struct __objcFastEnumerationState {\n\t";
577 Preamble += "unsigned long state;\n\t";
Steve Naroff4dbab8a2008-04-04 22:58:22 +0000578 Preamble += "void **itemsPtr;\n\t";
Steve Naroff00a31762008-03-27 22:29:16 +0000579 Preamble += "unsigned long *mutationsPtr;\n\t";
580 Preamble += "unsigned long extra[5];\n};\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000581 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000582 Preamble += "#define __FASTENUMERATIONSTATE\n";
583 Preamble += "#endif\n";
584 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
585 Preamble += "struct __NSConstantStringImpl {\n";
586 Preamble += " int *isa;\n";
587 Preamble += " int flags;\n";
588 Preamble += " char *str;\n";
589 Preamble += " long length;\n";
590 Preamble += "};\n";
Steve Naroffdd514e02008-08-05 20:04:48 +0000591 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
592 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
593 Preamble += "#else\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000594 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroffdd514e02008-08-05 20:04:48 +0000595 Preamble += "#endif\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000596 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
597 Preamble += "#endif\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000598 // Blocks preamble.
599 Preamble += "#ifndef BLOCK_IMPL\n";
600 Preamble += "#define BLOCK_IMPL\n";
601 Preamble += "struct __block_impl {\n";
602 Preamble += " void *isa;\n";
603 Preamble += " int Flags;\n";
Steve Naroff30484702009-12-06 21:14:13 +0000604 Preamble += " int Reserved;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000605 Preamble += " void *FuncPtr;\n";
606 Preamble += "};\n";
Steve Naroff61d879e2008-12-16 15:50:30 +0000607 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
Steve Naroff287a2bf2009-12-06 01:52:22 +0000608 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
Steve Naroff2b3843d2009-12-06 01:33:56 +0000609 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_assign(void *, const void *, const int);\n";
610 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
611 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
612 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
613 Preamble += "#else\n";
Steve Naroff7bf01ea2010-01-05 18:09:31 +0000614 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
615 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
Steve Naroff2b3843d2009-12-06 01:33:56 +0000616 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
617 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
618 Preamble += "#endif\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000619 Preamble += "#endif\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000620 if (LangOpts.Microsoft) {
Steve Narofff122ff02008-12-08 17:30:33 +0000621 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
622 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000623 Preamble += "#define __attribute__(X)\n";
Fariborz Jahanianf0462ff2010-01-15 22:29:39 +0000624 Preamble += "#define __weak\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000625 }
Fariborz Jahanian7fac6552010-01-05 19:21:35 +0000626 else {
Fariborz Jahanian02e07732009-12-23 02:07:37 +0000627 Preamble += "#define __block\n";
Fariborz Jahanian7fac6552010-01-05 19:21:35 +0000628 Preamble += "#define __weak\n";
629 }
Chris Lattner187f6262008-01-31 19:38:44 +0000630}
631
632
Chris Lattner3c799d72007-10-24 17:06:59 +0000633//===----------------------------------------------------------------------===//
634// Top Level Driver Code
635//===----------------------------------------------------------------------===//
636
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000637void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremenek31e7f0f2010-02-05 21:28:51 +0000638 if (Diags.hasErrorOccurred())
639 return;
640
Chris Lattner0bd1c972007-10-16 21:07:07 +0000641 // Two cases: either the decl could be in the main file, or it could be in a
642 // #included file. If the former, rewrite it now. If the later, check to see
643 // if we rewrote the #include/#import.
644 SourceLocation Loc = D->getLocation();
Chris Lattner8a425862009-01-16 07:36:28 +0000645 Loc = SM->getInstantiationLoc(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000646
Chris Lattner0bd1c972007-10-16 21:07:07 +0000647 // If this is for a builtin, ignore it.
648 if (Loc.isInvalid()) return;
649
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000650 // Look for built-in declarations that we need to refer during the rewrite.
651 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000652 RewriteFunctionDecl(FD);
Steve Naroff08899ff2008-04-15 22:42:06 +0000653 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffa397efd2007-11-03 11:27:19 +0000654 // declared in <Foundation/NSString.h>
Chris Lattner86d7d912008-11-24 03:54:41 +0000655 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroffa397efd2007-11-03 11:27:19 +0000656 ConstantStringClassReference = FVD;
657 return;
658 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000659 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroff161a92b2007-10-26 20:53:56 +0000660 RewriteInterfaceDecl(MD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000661 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000662 RewriteCategoryDecl(CD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000663 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Narofff921385f2007-10-30 16:42:30 +0000664 RewriteProtocolDecl(PD);
Mike Stump11289f42009-09-09 15:08:12 +0000665 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000666 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000667 RewriteForwardProtocolDecl(FP);
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000668 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
669 // Recurse into linkage specifications
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000670 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
671 DIEnd = LSD->decls_end();
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000672 DI != DIEnd; ++DI)
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000673 HandleTopLevelSingleDecl(*DI);
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000674 }
Chris Lattner3c799d72007-10-24 17:06:59 +0000675 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekd61ed3b2008-04-14 21:24:13 +0000676 if (SM->isFromMainFile(Loc))
Chris Lattner0bd1c972007-10-16 21:07:07 +0000677 return HandleDeclInMainFile(D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000678}
679
Chris Lattner3c799d72007-10-24 17:06:59 +0000680//===----------------------------------------------------------------------===//
681// Syntactic (non-AST) Rewriting Code
682//===----------------------------------------------------------------------===//
683
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000684void RewriteObjC::RewriteInclude() {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000685 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Fariborz Jahanian80258362008-01-19 00:30:35 +0000686 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
687 const char *MainBufStart = MainBuf.first;
688 const char *MainBufEnd = MainBuf.second;
689 size_t ImportLen = strlen("import");
690 size_t IncludeLen = strlen("include");
Mike Stump11289f42009-09-09 15:08:12 +0000691
Fariborz Jahanian137d6932008-01-19 01:03:17 +0000692 // Loop over the whole file, looking for includes.
Fariborz Jahanian80258362008-01-19 00:30:35 +0000693 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
694 if (*BufPtr == '#') {
695 if (++BufPtr == MainBufEnd)
696 return;
697 while (*BufPtr == ' ' || *BufPtr == '\t')
698 if (++BufPtr == MainBufEnd)
699 return;
700 if (!strncmp(BufPtr, "import", ImportLen)) {
701 // replace import with include
Mike Stump11289f42009-09-09 15:08:12 +0000702 SourceLocation ImportLoc =
Fariborz Jahanian80258362008-01-19 00:30:35 +0000703 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattner9cc55f52008-01-31 19:51:04 +0000704 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian80258362008-01-19 00:30:35 +0000705 BufPtr += ImportLen;
706 }
707 }
708 }
Chris Lattner0bd1c972007-10-16 21:07:07 +0000709}
710
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000711void RewriteObjC::RewriteTabs() {
Chris Lattner3c799d72007-10-24 17:06:59 +0000712 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
713 const char *MainBufStart = MainBuf.first;
714 const char *MainBufEnd = MainBuf.second;
Mike Stump11289f42009-09-09 15:08:12 +0000715
Chris Lattner3c799d72007-10-24 17:06:59 +0000716 // Loop over the whole file, looking for tabs.
717 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
718 if (*BufPtr != '\t')
719 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000720
Chris Lattner3c799d72007-10-24 17:06:59 +0000721 // Okay, we found a tab. This tab will turn into at least one character,
722 // but it depends on which 'virtual column' it is in. Compute that now.
723 unsigned VCol = 0;
724 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
725 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
726 ++VCol;
Mike Stump11289f42009-09-09 15:08:12 +0000727
Chris Lattner3c799d72007-10-24 17:06:59 +0000728 // Okay, now that we know the virtual column, we know how many spaces to
729 // insert. We assume 8-character tab-stops.
730 unsigned Spaces = 8-(VCol & 7);
Mike Stump11289f42009-09-09 15:08:12 +0000731
Chris Lattner3c799d72007-10-24 17:06:59 +0000732 // Get the location of the tab.
Chris Lattnerd32480d2009-01-17 06:22:33 +0000733 SourceLocation TabLoc = SM->getLocForStartOfFile(MainFileID);
734 TabLoc = TabLoc.getFileLocWithOffset(BufPtr-MainBufStart);
Mike Stump11289f42009-09-09 15:08:12 +0000735
Chris Lattner3c799d72007-10-24 17:06:59 +0000736 // Rewrite the single tab character into a sequence of spaces.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000737 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattner3c799d72007-10-24 17:06:59 +0000738 }
Chris Lattner16a0de42007-10-11 18:38:32 +0000739}
740
Steve Naroff9af94912008-12-02 15:48:25 +0000741static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
742 ObjCIvarDecl *OID) {
743 std::string S;
744 S = "((struct ";
745 S += ClassDecl->getIdentifier()->getName();
746 S += "_IMPL *)self)->";
Daniel Dunbar70e7ead2009-10-18 20:26:27 +0000747 S += OID->getName();
Steve Naroff9af94912008-12-02 15:48:25 +0000748 return S;
749}
750
Steve Naroffc038b3a2008-12-02 17:36:43 +0000751void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
752 ObjCImplementationDecl *IMD,
753 ObjCCategoryImplDecl *CID) {
Steve Naroffe1908e32008-12-01 20:33:01 +0000754 SourceLocation startLoc = PID->getLocStart();
755 InsertText(startLoc, "// ", 3);
Steve Naroff9af94912008-12-02 15:48:25 +0000756 const char *startBuf = SM->getCharacterData(startLoc);
757 assert((*startBuf == '@') && "bogus @synthesize location");
758 const char *semiBuf = strchr(startBuf, ';');
759 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek5a201952009-02-07 01:47:29 +0000760 SourceLocation onePastSemiLoc =
761 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroff9af94912008-12-02 15:48:25 +0000762
763 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
764 return; // FIXME: is this correct?
Mike Stump11289f42009-09-09 15:08:12 +0000765
Steve Naroff9af94912008-12-02 15:48:25 +0000766 // Generate the 'getter' function.
Steve Naroff9af94912008-12-02 15:48:25 +0000767 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroff9af94912008-12-02 15:48:25 +0000768 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroff9af94912008-12-02 15:48:25 +0000769 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000770
Steve Naroff003d00e2008-12-02 16:05:55 +0000771 if (!OID)
772 return;
Mike Stump11289f42009-09-09 15:08:12 +0000773
Steve Naroff003d00e2008-12-02 16:05:55 +0000774 std::string Getr;
775 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
776 Getr += "{ ";
777 // Synthesize an explicit cast to gain access to the ivar.
Mike Stump11289f42009-09-09 15:08:12 +0000778 // FIXME: deal with code generation implications for various property
779 // attributes (copy, retain, nonatomic).
Steve Naroff06297042008-12-02 17:54:50 +0000780 // See objc-act.c:objc_synthesize_new_getter() for details.
Steve Naroff003d00e2008-12-02 16:05:55 +0000781 Getr += "return " + getIvarAccessString(ClassDecl, OID);
782 Getr += "; }";
Steve Naroff9af94912008-12-02 15:48:25 +0000783 InsertText(onePastSemiLoc, Getr.c_str(), Getr.size());
Steve Naroff9af94912008-12-02 15:48:25 +0000784 if (PD->isReadOnly())
785 return;
Mike Stump11289f42009-09-09 15:08:12 +0000786
Steve Naroff9af94912008-12-02 15:48:25 +0000787 // Generate the 'setter' function.
788 std::string Setr;
789 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroff9af94912008-12-02 15:48:25 +0000790 Setr += "{ ";
Steve Naroff003d00e2008-12-02 16:05:55 +0000791 // Synthesize an explicit cast to initialize the ivar.
Mike Stump11289f42009-09-09 15:08:12 +0000792 // FIXME: deal with code generation implications for various property
793 // attributes (copy, retain, nonatomic).
Steve Narofff326f402008-12-03 00:56:33 +0000794 // See objc-act.c:objc_synthesize_new_setter() for details.
Steve Naroff003d00e2008-12-02 16:05:55 +0000795 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000796 Setr += PD->getNameAsCString();
Steve Naroff003d00e2008-12-02 16:05:55 +0000797 Setr += "; }";
Steve Naroff9af94912008-12-02 15:48:25 +0000798 InsertText(onePastSemiLoc, Setr.c_str(), Setr.size());
Steve Naroffe1908e32008-12-01 20:33:01 +0000799}
Chris Lattner16a0de42007-10-11 18:38:32 +0000800
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000801void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattner3c799d72007-10-24 17:06:59 +0000802 // Get the start location and compute the semi location.
803 SourceLocation startLoc = ClassDecl->getLocation();
804 const char *startBuf = SM->getCharacterData(startLoc);
805 const char *semiPtr = strchr(startBuf, ';');
Mike Stump11289f42009-09-09 15:08:12 +0000806
Chris Lattner3c799d72007-10-24 17:06:59 +0000807 // Translate to typedef's that forward reference structs with the same name
808 // as the class. As a convenience, we include the original declaration
809 // as a comment.
810 std::string typedefString;
Fariborz Jahanian1c2cb6d2010-01-11 22:48:40 +0000811 typedefString += "// @class ";
812 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
813 I != E; ++I) {
814 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
815 typedefString += ForwardDecl->getNameAsString();
816 if (I+1 != E)
817 typedefString += ", ";
818 else
819 typedefString += ";\n";
820 }
821
Chris Lattner9ee23b72009-02-20 18:04:31 +0000822 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
823 I != E; ++I) {
Ted Kremenek9b124e12009-11-18 00:28:11 +0000824 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
Steve Naroff1b232132007-11-09 12:50:28 +0000825 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000826 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000827 typedefString += "\n";
828 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000829 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000830 typedefString += "\n";
Steve Naroff98eb8d12007-11-05 14:36:37 +0000831 typedefString += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000832 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000833 typedefString += ";\n#endif\n";
Steve Naroff574440f2007-10-24 22:48:43 +0000834 }
Mike Stump11289f42009-09-09 15:08:12 +0000835
Steve Naroff574440f2007-10-24 22:48:43 +0000836 // Replace the @class with typedefs corresponding to the classes.
Mike Stump11289f42009-09-09 15:08:12 +0000837 ReplaceText(startLoc, semiPtr-startBuf+1,
Chris Lattner9cc55f52008-01-31 19:51:04 +0000838 typedefString.c_str(), typedefString.size());
Chris Lattner3c799d72007-10-24 17:06:59 +0000839}
840
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000841void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahanianda8ec2b2010-01-21 17:36:00 +0000842 // When method is a synthesized one, such as a getter/setter there is
843 // nothing to rewrite.
844 if (Method->isSynthesized())
845 return;
Steve Naroff3ce37a62007-12-14 23:37:57 +0000846 SourceLocation LocStart = Method->getLocStart();
847 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000848
Chris Lattner88ea93e2009-02-04 01:06:56 +0000849 if (SM->getInstantiationLineNumber(LocEnd) >
850 SM->getInstantiationLineNumber(LocStart)) {
Steve Naroffe020fa12008-10-21 13:37:27 +0000851 InsertText(LocStart, "#if 0\n", 6);
852 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff3ce37a62007-12-14 23:37:57 +0000853 } else {
Chris Lattner1780a852008-01-31 19:42:41 +0000854 InsertText(LocStart, "// ", 3);
Steve Naroff5448cf62007-10-30 13:30:57 +0000855 }
856}
857
Mike Stump11289f42009-09-09 15:08:12 +0000858void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahanianda8ec2b2010-01-21 17:36:00 +0000859 SourceLocation Loc = prop->getAtLoc();
Mike Stump11289f42009-09-09 15:08:12 +0000860
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000861 ReplaceText(Loc, 0, "// ", 3);
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000862 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahaniane8a30162007-11-07 00:09:37 +0000863}
864
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000865void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000866 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000867
Steve Naroff5448cf62007-10-30 13:30:57 +0000868 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000869 ReplaceText(LocStart, 0, "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +0000870
Fariborz Jahanian68ebe632010-02-10 01:15:09 +0000871 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
872 E = CatDecl->prop_end(); I != E; ++I)
873 RewriteProperty(*I);
874
Mike Stump11289f42009-09-09 15:08:12 +0000875 for (ObjCCategoryDecl::instmeth_iterator
876 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000877 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000878 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +0000879 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000880 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000881 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000882 RewriteMethodDeclaration(*I);
883
Steve Naroff5448cf62007-10-30 13:30:57 +0000884 // Lastly, comment out the @end.
Ted Kremenekc7c64312010-01-07 01:20:12 +0000885 ReplaceText(CatDecl->getAtEndRange().getBegin(), 0, "// ", 3);
Steve Naroff5448cf62007-10-30 13:30:57 +0000886}
887
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000888void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000889 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Mike Stump11289f42009-09-09 15:08:12 +0000890
Steve Narofff921385f2007-10-30 16:42:30 +0000891 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000892
Steve Narofff921385f2007-10-30 16:42:30 +0000893 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000894 ReplaceText(LocStart, 0, "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +0000895
896 for (ObjCProtocolDecl::instmeth_iterator
897 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000898 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000899 RewriteMethodDeclaration(*I);
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000900 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000901 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000902 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000903 RewriteMethodDeclaration(*I);
904
Steve Narofff921385f2007-10-30 16:42:30 +0000905 // Lastly, comment out the @end.
Ted Kremenekc7c64312010-01-07 01:20:12 +0000906 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Chris Lattner9cc55f52008-01-31 19:51:04 +0000907 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroffa509f042007-11-14 15:03:57 +0000908
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000909 // Must comment out @optional/@required
910 const char *startBuf = SM->getCharacterData(LocStart);
911 const char *endBuf = SM->getCharacterData(LocEnd);
912 for (const char *p = startBuf; p < endBuf; p++) {
913 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
914 std::string CommentedOptional = "/* @optional */";
Steve Naroffa509f042007-11-14 15:03:57 +0000915 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattner9cc55f52008-01-31 19:51:04 +0000916 ReplaceText(OptionalLoc, strlen("@optional"),
917 CommentedOptional.c_str(), CommentedOptional.size());
Mike Stump11289f42009-09-09 15:08:12 +0000918
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000919 }
920 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
921 std::string CommentedRequired = "/* @required */";
Steve Naroffa509f042007-11-14 15:03:57 +0000922 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattner9cc55f52008-01-31 19:51:04 +0000923 ReplaceText(OptionalLoc, strlen("@required"),
924 CommentedRequired.c_str(), CommentedRequired.size());
Mike Stump11289f42009-09-09 15:08:12 +0000925
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000926 }
927 }
Steve Narofff921385f2007-10-30 16:42:30 +0000928}
929
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000930void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000931 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffc17b0562007-11-14 03:37:28 +0000932 if (LocStart.isInvalid())
933 assert(false && "Invalid SourceLocation");
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000934 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000935 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000936}
937
Mike Stump11289f42009-09-09 15:08:12 +0000938void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000939 std::string &ResultStr) {
Steve Naroff295570a2008-10-30 12:09:33 +0000940 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroffb067bbd2008-07-16 14:40:40 +0000941 const FunctionType *FPRetType = 0;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000942 ResultStr += "\nstatic ";
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000943 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanian24cb52c2007-12-17 21:03:50 +0000944 ResultStr += "id";
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000945 else if (OMD->getResultType()->isFunctionPointerType() ||
946 OMD->getResultType()->isBlockPointerType()) {
Steve Naroffb067bbd2008-07-16 14:40:40 +0000947 // needs special handling, since pointer-to-functions have special
948 // syntax (where a decaration models use).
949 QualType retType = OMD->getResultType();
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000950 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000951 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000952 PointeeTy = PT->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000953 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000954 PointeeTy = BPT->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +0000955 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000956 ResultStr += FPRetType->getResultType().getAsString();
957 ResultStr += "(*";
Steve Naroffb067bbd2008-07-16 14:40:40 +0000958 }
959 } else
Fariborz Jahanian24cb52c2007-12-17 21:03:50 +0000960 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian7262fca2008-01-10 01:39:52 +0000961 ResultStr += " ";
Mike Stump11289f42009-09-09 15:08:12 +0000962
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000963 // Unique method name
Fariborz Jahanian56338352007-11-13 21:02:00 +0000964 std::string NameStr;
Mike Stump11289f42009-09-09 15:08:12 +0000965
Douglas Gregorffca3a22009-01-09 17:18:27 +0000966 if (OMD->isInstanceMethod())
Fariborz Jahanian56338352007-11-13 21:02:00 +0000967 NameStr += "_I_";
968 else
969 NameStr += "_C_";
Mike Stump11289f42009-09-09 15:08:12 +0000970
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000971 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +0000972 NameStr += "_";
Mike Stump11289f42009-09-09 15:08:12 +0000973
974 if (ObjCCategoryImplDecl *CID =
Steve Naroff11b387f2009-01-08 19:41:02 +0000975 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000976 NameStr += CID->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +0000977 NameStr += "_";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000978 }
Mike Stump11289f42009-09-09 15:08:12 +0000979 // Append selector names, replacing ':' with '_'
Chris Lattnere4b95692008-11-24 03:33:13 +0000980 {
981 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000982 int len = selString.size();
983 for (int i = 0; i < len; i++)
984 if (selString[i] == ':')
985 selString[i] = '_';
Fariborz Jahanian56338352007-11-13 21:02:00 +0000986 NameStr += selString;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000987 }
Fariborz Jahanian56338352007-11-13 21:02:00 +0000988 // Remember this name for metadata emission
989 MethodInternalNames[OMD] = NameStr;
990 ResultStr += NameStr;
Mike Stump11289f42009-09-09 15:08:12 +0000991
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000992 // Rewrite arguments
993 ResultStr += "(";
Mike Stump11289f42009-09-09 15:08:12 +0000994
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000995 // invisible arguments
Douglas Gregorffca3a22009-01-09 17:18:27 +0000996 if (OMD->isInstanceMethod()) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000997 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000998 selfTy = Context->getPointerType(selfTy);
Steve Naroffdc5b6b22008-03-12 00:25:36 +0000999 if (!LangOpts.Microsoft) {
1000 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
1001 ResultStr += "struct ";
1002 }
1003 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001004 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +00001005 ResultStr += " *";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001006 }
1007 else
Steve Naroffd9803712009-04-29 16:37:50 +00001008 ResultStr += Context->getObjCClassType().getAsString();
Mike Stump11289f42009-09-09 15:08:12 +00001009
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001010 ResultStr += " self, ";
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001011 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001012 ResultStr += " _cmd";
Mike Stump11289f42009-09-09 15:08:12 +00001013
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001014 // Method arguments.
Chris Lattnera4997152009-02-20 18:43:26 +00001015 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1016 E = OMD->param_end(); PI != E; ++PI) {
1017 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001018 ResultStr += ", ";
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001019 if (PDecl->getType()->isObjCQualifiedIdType()) {
1020 ResultStr += "id ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001021 ResultStr += PDecl->getNameAsString();
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001022 } else {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001023 std::string Name = PDecl->getNameAsString();
Steve Naroffa5c0db82008-12-11 21:05:33 +00001024 if (isTopLevelBlockPointerType(PDecl->getType())) {
Steve Naroff44df6a22008-10-30 14:45:29 +00001025 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001026 const BlockPointerType *BPT = PDecl->getType()->getAs<BlockPointerType>();
Douglas Gregor7de59662009-05-29 20:38:28 +00001027 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name,
1028 Context->PrintingPolicy);
Steve Naroff44df6a22008-10-30 14:45:29 +00001029 } else
Douglas Gregor7de59662009-05-29 20:38:28 +00001030 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001031 ResultStr += Name;
1032 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001033 }
Fariborz Jahanianeab81cd2008-01-21 20:14:23 +00001034 if (OMD->isVariadic())
1035 ResultStr += ", ...";
Fariborz Jahanian7262fca2008-01-10 01:39:52 +00001036 ResultStr += ") ";
Mike Stump11289f42009-09-09 15:08:12 +00001037
Steve Naroffb067bbd2008-07-16 14:40:40 +00001038 if (FPRetType) {
1039 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump11289f42009-09-09 15:08:12 +00001040
Steve Naroffb067bbd2008-07-16 14:40:40 +00001041 // Now, emit the argument types (if any).
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001042 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroffb067bbd2008-07-16 14:40:40 +00001043 ResultStr += "(";
1044 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1045 if (i) ResultStr += ", ";
1046 std::string ParamStr = FT->getArgType(i).getAsString();
1047 ResultStr += ParamStr;
1048 }
1049 if (FT->isVariadic()) {
1050 if (FT->getNumArgs()) ResultStr += ", ";
1051 ResultStr += "...";
1052 }
1053 ResultStr += ")";
1054 } else {
1055 ResultStr += "()";
1056 }
1057 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001058}
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001059void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001060 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1061 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump11289f42009-09-09 15:08:12 +00001062
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00001063 if (IMD)
Chris Lattner1780a852008-01-31 19:42:41 +00001064 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00001065 else
Chris Lattner1780a852008-01-31 19:42:41 +00001066 InsertText(CID->getLocStart(), "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +00001067
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001068 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001069 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1070 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001071 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001072 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001073 ObjCMethodDecl *OMD = *I;
1074 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001075 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001076 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redla7b98a72009-04-26 20:35:05 +00001077
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001078 const char *startBuf = SM->getCharacterData(LocStart);
1079 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattner9cc55f52008-01-31 19:51:04 +00001080 ReplaceText(LocStart, endBuf-startBuf,
1081 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001082 }
Mike Stump11289f42009-09-09 15:08:12 +00001083
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001084 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001085 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1086 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001087 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001088 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001089 ObjCMethodDecl *OMD = *I;
1090 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001091 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001092 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +00001093
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001094 const char *startBuf = SM->getCharacterData(LocStart);
1095 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattner9cc55f52008-01-31 19:51:04 +00001096 ReplaceText(LocStart, endBuf-startBuf,
Mike Stump11289f42009-09-09 15:08:12 +00001097 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001098 }
Steve Naroffe1908e32008-12-01 20:33:01 +00001099 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001100 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001101 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001102 I != E; ++I) {
Steve Naroffc038b3a2008-12-02 17:36:43 +00001103 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffe1908e32008-12-01 20:33:01 +00001104 }
1105
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00001106 if (IMD)
Chris Lattner1780a852008-01-31 19:42:41 +00001107 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00001108 else
Mike Stump11289f42009-09-09 15:08:12 +00001109 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001110}
1111
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001112void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffc5484042007-10-30 02:23:23 +00001113 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001114 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff2f55b982007-11-01 03:35:41 +00001115 // we haven't seen a forward decl - generate a typedef.
Steve Naroff03f27672007-11-14 23:02:56 +00001116 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001117 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001118 ResultStr += "\n";
1119 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001120 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001121 ResultStr += "\n";
Steve Naroffa1e115e2008-03-10 23:16:54 +00001122 ResultStr += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001123 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001124 ResultStr += ";\n#endif\n";
Steve Naroff2f55b982007-11-01 03:35:41 +00001125 // Mark this typedef as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001126 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff2f55b982007-11-01 03:35:41 +00001127 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001128 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump11289f42009-09-09 15:08:12 +00001129
1130 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001131 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff0c0f5ba2009-01-11 01:06:09 +00001132 RewriteProperty(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001133 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001134 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001135 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001136 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001137 for (ObjCInterfaceDecl::classmeth_iterator
1138 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001139 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001140 RewriteMethodDeclaration(*I);
1141
Steve Naroff4cd61ac2007-10-30 03:43:13 +00001142 // Lastly, comment out the @end.
Ted Kremenekc7c64312010-01-07 01:20:12 +00001143 ReplaceText(ClassDecl->getAtEndRange().getBegin(), 0, "// ", 3);
Steve Naroff161a92b2007-10-26 20:53:56 +00001144}
1145
Steve Naroff08628db2008-12-09 12:56:34 +00001146Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1147 SourceRange SrcRange) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00001148 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1149 // This allows us to reuse all the fun and games in SynthMessageExpr().
1150 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1151 ObjCMessageExpr *MsgExpr;
1152 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1153 llvm::SmallVector<Expr *, 1> ExprVec;
1154 ExprVec.push_back(newStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001155
Steve Naroff1042ff32008-12-08 16:43:47 +00001156 Stmt *Receiver = PropRefExpr->getBase();
1157 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1158 if (PRE && PropGetters[PRE]) {
1159 // This allows us to handle chain/nested property getters.
1160 Receiver = PropGetters[PRE];
1161 }
Ted Kremenek2c809302010-02-11 22:41:21 +00001162 MsgExpr = new (Context) ObjCMessageExpr(*Context, dyn_cast<Expr>(Receiver),
Mike Stump11289f42009-09-09 15:08:12 +00001163 PDecl->getSetterName(), PDecl->getType(),
1164 PDecl->getSetterMethodDecl(),
1165 SourceLocation(), SourceLocation(),
Steve Naroff4588d0f2008-12-04 16:24:46 +00001166 &ExprVec[0], 1);
1167 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001168
Steve Naroff4588d0f2008-12-04 16:24:46 +00001169 // Now do the actual rewrite.
Steve Naroff08628db2008-12-09 12:56:34 +00001170 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffdf705772008-12-10 14:53:27 +00001171 //delete BinOp;
Ted Kremenek5a201952009-02-07 01:47:29 +00001172 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1173 // to things that stay around.
1174 Context->Deallocate(MsgExpr);
Steve Naroff4588d0f2008-12-04 16:24:46 +00001175 return ReplacingStmt;
Steve Narofff326f402008-12-03 00:56:33 +00001176}
1177
Steve Naroff4588d0f2008-12-04 16:24:46 +00001178Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Narofff326f402008-12-03 00:56:33 +00001179 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1180 // This allows us to reuse all the fun and games in SynthMessageExpr().
1181 ObjCMessageExpr *MsgExpr;
1182 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
Mike Stump11289f42009-09-09 15:08:12 +00001183
Steve Naroff1042ff32008-12-08 16:43:47 +00001184 Stmt *Receiver = PropRefExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00001185
Steve Naroff1042ff32008-12-08 16:43:47 +00001186 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1187 if (PRE && PropGetters[PRE]) {
1188 // This allows us to handle chain/nested property getters.
1189 Receiver = PropGetters[PRE];
1190 }
Ted Kremenek2c809302010-02-11 22:41:21 +00001191 MsgExpr = new (Context) ObjCMessageExpr(*Context, dyn_cast<Expr>(Receiver),
Mike Stump11289f42009-09-09 15:08:12 +00001192 PDecl->getGetterName(), PDecl->getType(),
1193 PDecl->getGetterMethodDecl(),
1194 SourceLocation(), SourceLocation(),
Steve Narofff326f402008-12-03 00:56:33 +00001195 0, 0);
1196
Steve Naroff22216db2008-12-04 23:50:32 +00001197 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001198
1199 if (!PropParentMap)
1200 PropParentMap = new ParentMap(CurrentBody);
1201
1202 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1203 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1204 // We stash away the ReplacingStmt since actually doing the
1205 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1206 PropGetters[PropRefExpr] = ReplacingStmt;
Ted Kremenek5a201952009-02-07 01:47:29 +00001207 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1208 // to things that stay around.
1209 Context->Deallocate(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001210 return PropRefExpr; // return the original...
1211 } else {
1212 ReplaceStmt(PropRefExpr, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001213 // delete PropRefExpr; elsewhere...
Ted Kremenek5a201952009-02-07 01:47:29 +00001214 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1215 // to things that stay around.
1216 Context->Deallocate(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001217 return ReplacingStmt;
1218 }
Steve Narofff326f402008-12-03 00:56:33 +00001219}
1220
Mike Stump11289f42009-09-09 15:08:12 +00001221Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001222 SourceLocation OrigStart,
1223 bool &replaced) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001224 ObjCIvarDecl *D = IV->getDecl();
Fariborz Jahanian0f3aecf2010-01-07 18:18:32 +00001225 const Expr *BaseExpr = IV->getBase();
Steve Naroff677ab3a2008-10-27 17:20:55 +00001226 if (CurMethodDef) {
Fariborz Jahanianf9e8c2b2010-01-26 18:28:51 +00001227 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001228 ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian0f3aecf2010-01-07 18:18:32 +00001229 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanianf0ed69c2010-01-26 20:37:44 +00001230 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
Steve Naroffb1c02372008-05-08 17:52:16 +00001231 // lookup which class implements the instance variable.
1232 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001233 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001234 clsDeclared);
Steve Naroffb1c02372008-05-08 17:52:16 +00001235 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001236
Steve Naroffb1c02372008-05-08 17:52:16 +00001237 // Synthesize an explicit cast to gain access to the ivar.
1238 std::string RecName = clsDeclared->getIdentifier()->getName();
1239 RecName += "_IMPL";
1240 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00001241 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001242 SourceLocation(), II);
Steve Naroffb1c02372008-05-08 17:52:16 +00001243 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1244 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall97513962010-01-15 18:39:57 +00001245 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
1246 CastExpr::CK_Unknown,
1247 IV->getBase());
Steve Naroffb1c02372008-05-08 17:52:16 +00001248 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001249 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1250 IV->getBase()->getLocEnd(),
1251 castExpr);
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001252 replaced = true;
Mike Stump11289f42009-09-09 15:08:12 +00001253 if (IV->isFreeIvar() &&
Steve Naroff677ab3a2008-10-27 17:20:55 +00001254 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001255 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1256 IV->getLocation(),
1257 D->getType());
Steve Naroff22216db2008-12-04 23:50:32 +00001258 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffb1c02372008-05-08 17:52:16 +00001259 return ME;
Steve Naroff05caa482007-11-15 11:33:00 +00001260 }
Fariborz Jahanian81310812010-01-28 01:41:20 +00001261 // Get the new text
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001262 // Cannot delete IV->getBase(), since PE points to it.
1263 // Replace the old base with the cast. This is important when doing
1264 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001265 IV->setBase(PE);
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001266 return IV;
Steve Naroff05caa482007-11-15 11:33:00 +00001267 }
Steve Naroff24840f62008-04-18 21:55:08 +00001268 } else { // we are outside a method.
Steve Naroff29ce4e52008-05-06 23:20:07 +00001269 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump11289f42009-09-09 15:08:12 +00001270
Steve Naroff29ce4e52008-05-06 23:20:07 +00001271 // Explicit ivar refs need to have a cast inserted.
1272 // FIXME: consider sharing some of this code with the code above.
Fariborz Jahanian12e2e862010-01-12 17:31:23 +00001273 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Fariborz Jahanian9146e442010-01-11 17:50:35 +00001274 ObjCInterfaceType *iFaceDecl =
1275 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001276 // lookup which class implements the instance variable.
1277 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001278 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001279 clsDeclared);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001280 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001281
Steve Naroff29ce4e52008-05-06 23:20:07 +00001282 // Synthesize an explicit cast to gain access to the ivar.
1283 std::string RecName = clsDeclared->getIdentifier()->getName();
1284 RecName += "_IMPL";
1285 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00001286 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001287 SourceLocation(), II);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001288 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1289 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall97513962010-01-15 18:39:57 +00001290 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
1291 CastExpr::CK_Unknown,
1292 IV->getBase());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001293 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001294 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner34873d22008-05-28 16:38:23 +00001295 IV->getBase()->getLocEnd(), castExpr);
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001296 replaced = true;
Steve Naroff29ce4e52008-05-06 23:20:07 +00001297 // Cannot delete IV->getBase(), since PE points to it.
1298 // Replace the old base with the cast. This is important when doing
1299 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001300 IV->setBase(PE);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001301 return IV;
1302 }
Steve Naroff05caa482007-11-15 11:33:00 +00001303 }
Steve Naroff24840f62008-04-18 21:55:08 +00001304 return IV;
Steve Narofff60782b2007-11-15 02:58:25 +00001305}
1306
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001307Stmt *RewriteObjC::RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced) {
1308 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1309 CI != E; ++CI) {
1310 if (*CI) {
1311 Stmt *newStmt = RewriteObjCNestedIvarRefExpr(*CI, replaced);
1312 if (newStmt)
1313 *CI = newStmt;
1314 }
1315 }
1316 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
1317 SourceRange OrigStmtRange = S->getSourceRange();
1318 Stmt *newStmt = RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin(),
1319 replaced);
1320 return newStmt;
Fariborz Jahanian31433382010-02-05 17:48:10 +00001321 }
1322 if (ObjCMessageExpr *MsgRefExpr = dyn_cast<ObjCMessageExpr>(S)) {
1323 Stmt *newStmt = SynthMessageExpr(MsgRefExpr);
1324 return newStmt;
1325 }
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001326 return S;
1327}
1328
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001329/// SynthCountByEnumWithState - To print:
1330/// ((unsigned int (*)
1331/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001332/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001333/// sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001334/// "countByEnumeratingWithState:objects:count:"),
1335/// &enumState,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001336/// (id *)items, (unsigned int)16)
1337///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001338void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001339 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1340 "id *, unsigned int))(void *)objc_msgSend)";
1341 buf += "\n\t\t";
1342 buf += "((id)l_collection,\n\t\t";
1343 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1344 buf += "\n\t\t";
1345 buf += "&enumState, "
1346 "(id *)items, (unsigned int)16)";
1347}
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001348
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001349/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1350/// statement to exit to its outer synthesized loop.
1351///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001352Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001353 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1354 return S;
1355 // replace break with goto __break_label
1356 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001357
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001358 SourceLocation startLoc = S->getLocStart();
1359 buf = "goto __break_label_";
1360 buf += utostr(ObjCBcLabelNo.back());
Chris Lattner9cc55f52008-01-31 19:51:04 +00001361 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001362
1363 return 0;
1364}
1365
1366/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1367/// statement to continue with its inner synthesized loop.
1368///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001369Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001370 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1371 return S;
1372 // replace continue with goto __continue_label
1373 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001374
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001375 SourceLocation startLoc = S->getLocStart();
1376 buf = "goto __continue_label_";
1377 buf += utostr(ObjCBcLabelNo.back());
Chris Lattner9cc55f52008-01-31 19:51:04 +00001378 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001379
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001380 return 0;
1381}
1382
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001383/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001384/// It rewrites:
1385/// for ( type elem in collection) { stmts; }
Mike Stump11289f42009-09-09 15:08:12 +00001386
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001387/// Into:
1388/// {
Mike Stump11289f42009-09-09 15:08:12 +00001389/// type elem;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001390/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001391/// id items[16];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001392/// id l_collection = (id)collection;
Mike Stump11289f42009-09-09 15:08:12 +00001393/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001394/// objects:items count:16];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001395/// if (limit) {
1396/// unsigned long startMutations = *enumState.mutationsPtr;
1397/// do {
1398/// unsigned long counter = 0;
1399/// do {
Mike Stump11289f42009-09-09 15:08:12 +00001400/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001401/// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001402/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001403/// stmts;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001404/// __continue_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001405/// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001406/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001407/// objects:items count:16]);
1408/// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001409/// __break_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001410/// }
1411/// else
1412/// elem = nil;
1413/// }
1414///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001415Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattnera779d692008-01-31 05:10:40 +00001416 SourceLocation OrigEnd) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001417 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001418 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001419 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump11289f42009-09-09 15:08:12 +00001420 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001421 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001422
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001423 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001424 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001425 const char *elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001426 std::string elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001427 std::string buf;
1428 buf = "\n{\n\t";
1429 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1430 // type elem;
Chris Lattner529efc72009-03-28 06:33:19 +00001431 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek292b3842008-10-06 22:16:13 +00001432 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001433 if (ElementType->isObjCQualifiedIdType() ||
1434 ElementType->isObjCQualifiedInterfaceType())
1435 // Simply use 'id' for all qualified types.
1436 elementTypeAsString = "id";
1437 else
1438 elementTypeAsString = ElementType.getAsString();
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001439 buf += elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001440 buf += " ";
Chris Lattner86d7d912008-11-24 03:54:41 +00001441 elementName = D->getNameAsCString();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001442 buf += elementName;
1443 buf += ";\n\t";
1444 }
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001445 else {
1446 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner86d7d912008-11-24 03:54:41 +00001447 elementName = DR->getDecl()->getNameAsCString();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001448 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1449 if (VD->getType()->isObjCQualifiedIdType() ||
1450 VD->getType()->isObjCQualifiedInterfaceType())
1451 // Simply use 'id' for all qualified types.
1452 elementTypeAsString = "id";
1453 else
1454 elementTypeAsString = VD->getType().getAsString();
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001455 }
Mike Stump11289f42009-09-09 15:08:12 +00001456
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001457 // struct __objcFastEnumerationState enumState = { 0 };
1458 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1459 // id items[16];
1460 buf += "id items[16];\n\t";
1461 // id l_collection = (id)
1462 buf += "id l_collection = (id)";
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001463 // Find start location of 'collection' the hard way!
1464 const char *startCollectionBuf = startBuf;
1465 startCollectionBuf += 3; // skip 'for'
1466 startCollectionBuf = strchr(startCollectionBuf, '(');
1467 startCollectionBuf++; // skip '('
1468 // find 'in' and skip it.
1469 while (*startCollectionBuf != ' ' ||
1470 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1471 (*(startCollectionBuf+3) != ' ' &&
1472 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1473 startCollectionBuf++;
1474 startCollectionBuf += 3;
Mike Stump11289f42009-09-09 15:08:12 +00001475
1476 // Replace: "for (type element in" with string constructed thus far.
Chris Lattner9cc55f52008-01-31 19:51:04 +00001477 ReplaceText(startLoc, startCollectionBuf - startBuf,
1478 buf.c_str(), buf.size());
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001479 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001480 SourceLocation rightParenLoc = S->getRParenLoc();
1481 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1482 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001483 buf = ";\n\t";
Mike Stump11289f42009-09-09 15:08:12 +00001484
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001485 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1486 // objects:items count:16];
1487 // which is synthesized into:
Mike Stump11289f42009-09-09 15:08:12 +00001488 // unsigned int limit =
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001489 // ((unsigned int (*)
1490 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001491 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001492 // sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001493 // "countByEnumeratingWithState:objects:count:"),
1494 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001495 // (id *)items, (unsigned int)16);
1496 buf += "unsigned long limit =\n\t\t";
1497 SynthCountByEnumWithState(buf);
1498 buf += ";\n\t";
1499 /// if (limit) {
1500 /// unsigned long startMutations = *enumState.mutationsPtr;
1501 /// do {
1502 /// unsigned long counter = 0;
1503 /// do {
Mike Stump11289f42009-09-09 15:08:12 +00001504 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001505 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001506 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001507 buf += "if (limit) {\n\t";
1508 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1509 buf += "do {\n\t\t";
1510 buf += "unsigned long counter = 0;\n\t\t";
1511 buf += "do {\n\t\t\t";
1512 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1513 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1514 buf += elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001515 buf += " = (";
1516 buf += elementTypeAsString;
1517 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001518 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattner9cc55f52008-01-31 19:51:04 +00001519 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001520
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001521 /// __continue_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001522 /// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001523 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001524 /// objects:items count:16]);
1525 /// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001526 /// __break_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001527 /// }
1528 /// else
1529 /// elem = nil;
1530 /// }
Mike Stump11289f42009-09-09 15:08:12 +00001531 ///
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001532 buf = ";\n\t";
1533 buf += "__continue_label_";
1534 buf += utostr(ObjCBcLabelNo.back());
1535 buf += ": ;";
1536 buf += "\n\t\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001537 buf += "} while (counter < limit);\n\t";
1538 buf += "} while (limit = ";
1539 SynthCountByEnumWithState(buf);
1540 buf += ");\n\t";
1541 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001542 buf += " = ((";
1543 buf += elementTypeAsString;
1544 buf += ")0);\n\t";
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001545 buf += "__break_label_";
1546 buf += utostr(ObjCBcLabelNo.back());
1547 buf += ": ;\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001548 buf += "}\n\t";
1549 buf += "else\n\t\t";
1550 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001551 buf += " = ((";
1552 buf += elementTypeAsString;
1553 buf += ")0);\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001554 buf += "}\n";
Mike Stump11289f42009-09-09 15:08:12 +00001555
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001556 // Insert all these *after* the statement body.
Sebastian Redla7b98a72009-04-26 20:35:05 +00001557 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Narofff0ff8792008-07-21 18:26:02 +00001558 if (isa<CompoundStmt>(S->getBody())) {
1559 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1560 InsertText(endBodyLoc, buf.c_str(), buf.size());
1561 } else {
1562 /* Need to treat single statements specially. For example:
1563 *
1564 * for (A *a in b) if (stuff()) break;
1565 * for (A *a in b) xxxyy;
1566 *
1567 * The following code simply scans ahead to the semi to find the actual end.
1568 */
1569 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1570 const char *semiBuf = strchr(stmtBuf, ';');
1571 assert(semiBuf && "Can't find ';'");
1572 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1573 InsertText(endBodyLoc, buf.c_str(), buf.size());
1574 }
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001575 Stmts.pop_back();
1576 ObjCBcLabelNo.pop_back();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001577 return 0;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001578}
1579
Mike Stump11289f42009-09-09 15:08:12 +00001580/// RewriteObjCSynchronizedStmt -
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001581/// This routine rewrites @synchronized(expr) stmt;
1582/// into:
1583/// objc_sync_enter(expr);
1584/// @try stmt @finally { objc_sync_exit(expr); }
1585///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001586Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001587 // Get the start location and compute the semi location.
1588 SourceLocation startLoc = S->getLocStart();
1589 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001590
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001591 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump11289f42009-09-09 15:08:12 +00001592
1593 std::string buf;
Steve Naroffb2fc0522008-08-21 13:03:03 +00001594 buf = "objc_sync_enter((id)";
1595 const char *lparenBuf = startBuf;
1596 while (*lparenBuf != '(') lparenBuf++;
1597 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001598 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1599 // the sync expression is typically a message expression that's already
Steve Naroffad7013b2008-08-19 13:04:19 +00001600 // been rewritten! (which implies the SourceLocation's are invalid).
1601 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001602 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffad7013b2008-08-19 13:04:19 +00001603 while (*endBuf != ')') endBuf--;
1604 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001605 buf = ");\n";
1606 // declare a new scope with two variables, _stack and _rethrow.
1607 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1608 buf += "int buf[18/*32-bit i386*/];\n";
1609 buf += "char *pointers[4];} _stack;\n";
1610 buf += "id volatile _rethrow = 0;\n";
1611 buf += "objc_exception_try_enter(&_stack);\n";
1612 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001613 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001614 startLoc = S->getSynchBody()->getLocEnd();
1615 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001616
Steve Naroffad7013b2008-08-19 13:04:19 +00001617 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001618 SourceLocation lastCurlyLoc = startLoc;
1619 buf = "}\nelse {\n";
1620 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroffd9803712009-04-29 16:37:50 +00001621 buf += "}\n";
1622 buf += "{ /* implicit finally clause */\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001623 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffec60b432009-12-05 21:43:12 +00001624
1625 std::string syncBuf;
1626 syncBuf += " objc_sync_exit(";
John McCall97513962010-01-15 18:39:57 +00001627 Expr *syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1628 CastExpr::CK_Unknown,
1629 S->getSynchExpr());
Ted Kremenek2d470fc2008-09-13 05:16:45 +00001630 std::string syncExprBufS;
1631 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00001632 syncExpr->printPretty(syncExprBuf, *Context, 0,
1633 PrintingPolicy(LangOpts));
Steve Naroffec60b432009-12-05 21:43:12 +00001634 syncBuf += syncExprBuf.str();
1635 syncBuf += ");";
1636
1637 buf += syncBuf;
1638 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001639 buf += "}\n";
1640 buf += "}";
Mike Stump11289f42009-09-09 15:08:12 +00001641
Chris Lattner9cc55f52008-01-31 19:51:04 +00001642 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffec60b432009-12-05 21:43:12 +00001643
1644 bool hasReturns = false;
1645 HasReturnStmts(S->getSynchBody(), hasReturns);
1646 if (hasReturns)
1647 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1648
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001649 return 0;
1650}
1651
Steve Naroffec60b432009-12-05 21:43:12 +00001652void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1653{
Steve Naroff6d6da252008-12-05 17:03:39 +00001654 // Perform a bottom up traversal of all children.
1655 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1656 CI != E; ++CI)
1657 if (*CI)
Steve Naroffec60b432009-12-05 21:43:12 +00001658 WarnAboutReturnGotoStmts(*CI);
Steve Naroff6d6da252008-12-05 17:03:39 +00001659
Steve Naroffec60b432009-12-05 21:43:12 +00001660 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump11289f42009-09-09 15:08:12 +00001661 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff6d6da252008-12-05 17:03:39 +00001662 TryFinallyContainsReturnDiag);
1663 }
1664 return;
1665}
1666
Steve Naroffec60b432009-12-05 21:43:12 +00001667void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1668{
1669 // Perform a bottom up traversal of all children.
1670 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1671 CI != E; ++CI)
1672 if (*CI)
1673 HasReturnStmts(*CI, hasReturns);
1674
1675 if (isa<ReturnStmt>(S))
1676 hasReturns = true;
1677 return;
1678}
1679
1680void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1681 // Perform a bottom up traversal of all children.
1682 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1683 CI != E; ++CI)
1684 if (*CI) {
1685 RewriteTryReturnStmts(*CI);
1686 }
1687 if (isa<ReturnStmt>(S)) {
1688 SourceLocation startLoc = S->getLocStart();
1689 const char *startBuf = SM->getCharacterData(startLoc);
1690
1691 const char *semiBuf = strchr(startBuf, ';');
1692 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1693 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1694
1695 std::string buf;
1696 buf = "{ objc_exception_try_exit(&_stack); return";
1697
1698 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
1699 InsertText(onePastSemiLoc, "}", 1);
1700 }
1701 return;
1702}
1703
1704void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1705 // Perform a bottom up traversal of all children.
1706 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1707 CI != E; ++CI)
1708 if (*CI) {
1709 RewriteSyncReturnStmts(*CI, syncExitBuf);
1710 }
1711 if (isa<ReturnStmt>(S)) {
1712 SourceLocation startLoc = S->getLocStart();
1713 const char *startBuf = SM->getCharacterData(startLoc);
1714
1715 const char *semiBuf = strchr(startBuf, ';');
1716 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1717 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1718
1719 std::string buf;
1720 buf = "{ objc_exception_try_exit(&_stack);";
1721 buf += syncExitBuf;
1722 buf += " return";
1723
1724 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
1725 InsertText(onePastSemiLoc, "}", 1);
1726 }
1727 return;
1728}
1729
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001730Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001731 // Get the start location and compute the semi location.
1732 SourceLocation startLoc = S->getLocStart();
1733 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001734
Steve Naroffbf478ec2007-11-07 04:08:17 +00001735 assert((*startBuf == '@') && "bogus @try location");
1736
1737 std::string buf;
1738 // declare a new scope with two variables, _stack and _rethrow.
1739 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1740 buf += "int buf[18/*32-bit i386*/];\n";
1741 buf += "char *pointers[4];} _stack;\n";
1742 buf += "id volatile _rethrow = 0;\n";
1743 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff16018582007-11-07 18:43:40 +00001744 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffbf478ec2007-11-07 04:08:17 +00001745
Chris Lattner9cc55f52008-01-31 19:51:04 +00001746 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001747
Steve Naroffbf478ec2007-11-07 04:08:17 +00001748 startLoc = S->getTryBody()->getLocEnd();
1749 startBuf = SM->getCharacterData(startLoc);
1750
1751 assert((*startBuf == '}') && "bogus @try block");
Mike Stump11289f42009-09-09 15:08:12 +00001752
Steve Naroffbf478ec2007-11-07 04:08:17 +00001753 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffce2dca12008-07-16 15:31:30 +00001754 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1755 if (catchList) {
1756 startLoc = startLoc.getFileLocWithOffset(1);
1757 buf = " /* @catch begin */ else {\n";
1758 buf += " id _caught = objc_exception_extract(&_stack);\n";
1759 buf += " objc_exception_try_enter (&_stack);\n";
1760 buf += " if (_setjmp(_stack.buf))\n";
1761 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1762 buf += " else { /* @catch continue */";
Mike Stump11289f42009-09-09 15:08:12 +00001763
Steve Naroffce2dca12008-07-16 15:31:30 +00001764 InsertText(startLoc, buf.c_str(), buf.size());
Steve Narofffac18fe2008-09-09 19:59:12 +00001765 } else { /* no catch list */
1766 buf = "}\nelse {\n";
1767 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1768 buf += "}";
1769 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffce2dca12008-07-16 15:31:30 +00001770 }
Steve Naroffbf478ec2007-11-07 04:08:17 +00001771 bool sawIdTypedCatch = false;
1772 Stmt *lastCatchBody = 0;
Steve Naroffbf478ec2007-11-07 04:08:17 +00001773 while (catchList) {
Steve Naroff371b8fb2009-03-03 19:52:17 +00001774 ParmVarDecl *catchDecl = catchList->getCatchParamDecl();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001775
Mike Stump11289f42009-09-09 15:08:12 +00001776 if (catchList == S->getCatchStmts())
Steve Naroffbf478ec2007-11-07 04:08:17 +00001777 buf = "if ("; // we are generating code for the first catch clause
1778 else
1779 buf = "else if (";
1780 startLoc = catchList->getLocStart();
1781 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001782
Steve Naroffbf478ec2007-11-07 04:08:17 +00001783 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump11289f42009-09-09 15:08:12 +00001784
Steve Naroffbf478ec2007-11-07 04:08:17 +00001785 const char *lParenLoc = strchr(startBuf, '(');
1786
Steve Naroffe6b7ffd2008-02-01 22:08:12 +00001787 if (catchList->hasEllipsis()) {
Steve Naroffedb5bc62008-02-01 20:02:07 +00001788 // Now rewrite the body...
1789 lastCatchBody = catchList->getCatchBody();
Steve Naroffedb5bc62008-02-01 20:02:07 +00001790 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1791 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001792 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1793 "bogus @catch paren location");
Steve Naroffedb5bc62008-02-01 20:02:07 +00001794 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001795
Steve Naroffedb5bc62008-02-01 20:02:07 +00001796 buf += "1) { id _tmp = _caught;";
Daniel Dunbardec484a2009-08-19 19:10:30 +00001797 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff371b8fb2009-03-03 19:52:17 +00001798 } else if (catchDecl) {
1799 QualType t = catchDecl->getType();
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001800 if (t == Context->getObjCIdType()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001801 buf += "1) { ";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001802 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001803 sawIdTypedCatch = true;
Fariborz Jahanian59516092010-01-12 01:22:23 +00001804 } else if (t->isObjCObjectPointerType()) {
1805 QualType InterfaceTy = t->getPointeeType();
1806 const ObjCInterfaceType *cls = // Should be a pointer to a class.
1807 InterfaceTy->getAs<ObjCInterfaceType>();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001808 if (cls) {
Steve Naroff16018582007-11-07 18:43:40 +00001809 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001810 buf += cls->getDecl()->getNameAsString();
Steve Naroff16018582007-11-07 18:43:40 +00001811 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001812 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001813 }
1814 }
1815 // Now rewrite the body...
1816 lastCatchBody = catchList->getCatchBody();
1817 SourceLocation rParenLoc = catchList->getRParenLoc();
1818 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1819 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1820 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1821 assert((*rParenBuf == ')') && "bogus @catch paren location");
1822 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001823
Steve Naroffbf478ec2007-11-07 04:08:17 +00001824 buf = " = _caught;";
Mike Stump11289f42009-09-09 15:08:12 +00001825 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroffbf478ec2007-11-07 04:08:17 +00001826 // declares the @catch parameter).
Chris Lattner9cc55f52008-01-31 19:51:04 +00001827 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff371b8fb2009-03-03 19:52:17 +00001828 } else {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001829 assert(false && "@catch rewrite bug");
Steve Naroffa733c7f2007-11-07 15:32:26 +00001830 }
Steve Naroffedb5bc62008-02-01 20:02:07 +00001831 // make sure all the catch bodies get rewritten!
Steve Naroffbf478ec2007-11-07 04:08:17 +00001832 catchList = catchList->getNextCatchStmt();
1833 }
1834 // Complete the catch list...
1835 if (lastCatchBody) {
1836 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001837 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1838 "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001839
Steve Naroff4adbe312008-09-11 15:29:03 +00001840 // Insert the last (implicit) else clause *before* the right curly brace.
1841 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1842 buf = "} /* last catch end */\n";
1843 buf += "else {\n";
1844 buf += " _rethrow = _caught;\n";
1845 buf += " objc_exception_try_exit(&_stack);\n";
1846 buf += "} } /* @catch end */\n";
1847 if (!S->getFinallyStmt())
1848 buf += "}\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001849 InsertText(bodyLoc, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001850
Steve Naroffbf478ec2007-11-07 04:08:17 +00001851 // Set lastCurlyLoc
1852 lastCurlyLoc = lastCatchBody->getLocEnd();
1853 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001854 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001855 startLoc = finalStmt->getLocStart();
1856 startBuf = SM->getCharacterData(startLoc);
1857 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump11289f42009-09-09 15:08:12 +00001858
Steve Naroffbf478ec2007-11-07 04:08:17 +00001859 buf = "/* @finally */";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001860 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001861
Steve Naroffbf478ec2007-11-07 04:08:17 +00001862 Stmt *body = finalStmt->getFinallyBody();
1863 SourceLocation startLoc = body->getLocStart();
1864 SourceLocation endLoc = body->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001865 assert(*SM->getCharacterData(startLoc) == '{' &&
1866 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001867 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001868 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001869
Steve Naroffbf478ec2007-11-07 04:08:17 +00001870 startLoc = startLoc.getFileLocWithOffset(1);
1871 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001872 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001873 endLoc = endLoc.getFileLocWithOffset(-1);
1874 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001875 InsertText(endLoc, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001876
Steve Naroffbf478ec2007-11-07 04:08:17 +00001877 // Set lastCurlyLoc
1878 lastCurlyLoc = body->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00001879
Steve Naroff6d6da252008-12-05 17:03:39 +00001880 // Now check for any return/continue/go statements within the @try.
Steve Naroffec60b432009-12-05 21:43:12 +00001881 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff4adbe312008-09-11 15:29:03 +00001882 } else { /* no finally clause - make sure we synthesize an implicit one */
1883 buf = "{ /* implicit finally clause */\n";
1884 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1885 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1886 buf += "}";
1887 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffec60b432009-12-05 21:43:12 +00001888
1889 // Now check for any return/continue/go statements within the @try.
1890 // The implicit finally clause won't called if the @try contains any
1891 // jump statements.
1892 bool hasReturns = false;
1893 HasReturnStmts(S->getTryBody(), hasReturns);
1894 if (hasReturns)
1895 RewriteTryReturnStmts(S->getTryBody());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001896 }
1897 // Now emit the final closing curly brace...
1898 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1899 buf = " } /* @try scope end */\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001900 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001901 return 0;
1902}
1903
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001904Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001905 return 0;
1906}
1907
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001908Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001909 return 0;
1910}
1911
Mike Stump11289f42009-09-09 15:08:12 +00001912// This can't be done with ReplaceStmt(S, ThrowExpr), since
1913// the throw expression is typically a message expression that's already
Steve Naroffa733c7f2007-11-07 15:32:26 +00001914// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001915Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroffa733c7f2007-11-07 15:32:26 +00001916 // Get the start location and compute the semi location.
1917 SourceLocation startLoc = S->getLocStart();
1918 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001919
Steve Naroffa733c7f2007-11-07 15:32:26 +00001920 assert((*startBuf == '@') && "bogus @throw location");
1921
1922 std::string buf;
1923 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffc7d2df22008-01-19 00:42:38 +00001924 if (S->getThrowExpr())
1925 buf = "objc_exception_throw(";
1926 else // add an implicit argument
1927 buf = "objc_exception_throw(_caught";
Mike Stump11289f42009-09-09 15:08:12 +00001928
Steve Naroff29788342008-07-25 15:41:30 +00001929 // handle "@ throw" correctly.
1930 const char *wBuf = strchr(startBuf, 'w');
1931 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1932 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001933
Steve Naroffa733c7f2007-11-07 15:32:26 +00001934 const char *semiBuf = strchr(startBuf, ';');
1935 assert((*semiBuf == ';') && "@throw: can't find ';'");
1936 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1937 buf = ");";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001938 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroffa733c7f2007-11-07 15:32:26 +00001939 return 0;
1940}
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001941
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001942Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerc6d91c02007-10-17 22:35:30 +00001943 // Create a new string expression.
1944 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlssond8499822007-10-29 05:01:08 +00001945 std::string StrEncoding;
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00001946 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00001947 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
1948 StrEncoding.length(), false,StrType,
1949 SourceLocation());
Chris Lattner2e0d2602008-01-31 19:37:57 +00001950 ReplaceStmt(Exp, Replacement);
Mike Stump11289f42009-09-09 15:08:12 +00001951
Chris Lattner4431a1b2007-11-30 22:53:43 +00001952 // Replace this subexpr in the parent.
Steve Naroff22216db2008-12-04 23:50:32 +00001953 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattner69534692007-10-24 16:57:36 +00001954 return Replacement;
Chris Lattnera7c19fe2007-10-16 22:36:42 +00001955}
1956
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001957Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff2654e182008-12-22 22:16:07 +00001958 if (!SelGetUidFunctionDecl)
1959 SynthSelGetUidFunctionDecl();
Steve Naroffe4f9b232007-11-05 14:50:49 +00001960 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1961 // Create a call to sel_registerName("selName").
1962 llvm::SmallVector<Expr*, 8> SelExprs;
1963 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00001964 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00001965 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00001966 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00001967 false, argType, SourceLocation()));
Steve Naroffe4f9b232007-11-05 14:50:49 +00001968 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1969 &SelExprs[0], SelExprs.size());
Chris Lattner2e0d2602008-01-31 19:37:57 +00001970 ReplaceStmt(Exp, SelExp);
Steve Naroff22216db2008-12-04 23:50:32 +00001971 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffe4f9b232007-11-05 14:50:49 +00001972 return SelExp;
1973}
1974
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001975CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff574440f2007-10-24 22:48:43 +00001976 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001977 // Get the type, we will need to reference it in a couple spots.
Steve Naroff574440f2007-10-24 22:48:43 +00001978 QualType msgSendType = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001979
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001980 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek5a201952009-02-07 01:47:29 +00001981 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001982
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001983 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattner3c799d72007-10-24 17:06:59 +00001984 QualType pToFunc = Context->getPointerType(msgSendType);
Mike Stump11289f42009-09-09 15:08:12 +00001985 ImplicitCastExpr *ICE = new (Context) ImplicitCastExpr(pToFunc,
Anders Carlssona2615922009-07-31 00:48:10 +00001986 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00001987 DRE,
Douglas Gregora11693b2008-11-12 17:17:38 +00001988 /*isLvalue=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00001989
John McCall9dd450b2009-09-21 23:43:11 +00001990 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00001991
Ted Kremenekd7b4f402009-02-09 20:51:47 +00001992 return new (Context) CallExpr(*Context, ICE, args, nargs, FT->getResultType(),
1993 SourceLocation());
Steve Naroff574440f2007-10-24 22:48:43 +00001994}
1995
Steve Naroff50d42052007-11-01 13:24:47 +00001996static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1997 const char *&startRef, const char *&endRef) {
1998 while (startBuf < endBuf) {
1999 if (*startBuf == '<')
2000 startRef = startBuf; // mark the start.
2001 if (*startBuf == '>') {
Steve Naroff1b232132007-11-09 12:50:28 +00002002 if (startRef && *startRef == '<') {
2003 endRef = startBuf; // mark the end.
2004 return true;
2005 }
2006 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00002007 }
2008 startBuf++;
2009 }
2010 return false;
2011}
2012
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002013static void scanToNextArgument(const char *&argRef) {
2014 int angle = 0;
2015 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2016 if (*argRef == '<')
2017 angle++;
2018 else if (*argRef == '>')
2019 angle--;
2020 argRef++;
2021 }
2022 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2023}
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002024
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002025bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian80c54b02010-02-03 21:29:28 +00002026 if (T->isObjCQualifiedIdType())
2027 return true;
Fariborz Jahanian06769f92010-02-02 18:35:07 +00002028 if (const PointerType *PT = T->getAs<PointerType>()) {
2029 if (PT->getPointeeType()->isObjCQualifiedIdType())
2030 return true;
2031 }
2032 if (T->isObjCObjectPointerType()) {
2033 T = T->getPointeeType();
2034 return T->isObjCQualifiedInterfaceType();
2035 }
2036 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00002037}
2038
Steve Naroff873bd842008-07-29 18:15:38 +00002039void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2040 QualType Type = E->getType();
2041 if (needToScanForQualifiers(Type)) {
Steve Naroffdbfc6932008-11-19 21:15:47 +00002042 SourceLocation Loc, EndLoc;
Mike Stump11289f42009-09-09 15:08:12 +00002043
Steve Naroffdbfc6932008-11-19 21:15:47 +00002044 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2045 Loc = ECE->getLParenLoc();
2046 EndLoc = ECE->getRParenLoc();
2047 } else {
2048 Loc = E->getLocStart();
2049 EndLoc = E->getLocEnd();
2050 }
2051 // This will defend against trying to rewrite synthesized expressions.
2052 if (Loc.isInvalid() || EndLoc.isInvalid())
2053 return;
2054
Steve Naroff873bd842008-07-29 18:15:38 +00002055 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffdbfc6932008-11-19 21:15:47 +00002056 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff873bd842008-07-29 18:15:38 +00002057 const char *startRef = 0, *endRef = 0;
2058 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2059 // Get the locations of the startRef, endRef.
2060 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
2061 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
2062 // Comment out the protocol references.
2063 InsertText(LessLoc, "/*", 2);
2064 InsertText(GreaterLoc, "*/", 2);
2065 }
2066 }
2067}
2068
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002069void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002070 SourceLocation Loc;
2071 QualType Type;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002072 const FunctionProtoType *proto = 0;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002073 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2074 Loc = VD->getLocation();
2075 Type = VD->getType();
2076 }
2077 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2078 Loc = FD->getLocation();
2079 // Check for ObjC 'id' and class types that have been adorned with protocol
2080 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall9dd450b2009-09-21 23:43:11 +00002081 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002082 assert(funcType && "missing function type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002083 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002084 if (!proto)
2085 return;
2086 Type = proto->getResultType();
2087 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00002088 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2089 Loc = FD->getLocation();
2090 Type = FD->getType();
2091 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002092 else
2093 return;
Mike Stump11289f42009-09-09 15:08:12 +00002094
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002095 if (needToScanForQualifiers(Type)) {
Steve Naroff50d42052007-11-01 13:24:47 +00002096 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002097
Steve Naroff50d42052007-11-01 13:24:47 +00002098 const char *endBuf = SM->getCharacterData(Loc);
2099 const char *startBuf = endBuf;
Steve Naroff930e0992008-05-31 05:02:17 +00002100 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroff50d42052007-11-01 13:24:47 +00002101 startBuf--; // scan backward (from the decl location) for return type.
2102 const char *startRef = 0, *endRef = 0;
2103 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2104 // Get the locations of the startRef, endRef.
2105 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2106 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2107 // Comment out the protocol references.
Chris Lattner1780a852008-01-31 19:42:41 +00002108 InsertText(LessLoc, "/*", 2);
2109 InsertText(GreaterLoc, "*/", 2);
Steve Naroff37e011c2007-10-31 04:38:33 +00002110 }
2111 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002112 if (!proto)
2113 return; // most likely, was a variable
Steve Naroff50d42052007-11-01 13:24:47 +00002114 // Now check arguments.
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002115 const char *startBuf = SM->getCharacterData(Loc);
2116 const char *startFuncBuf = startBuf;
Steve Naroff50d42052007-11-01 13:24:47 +00002117 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2118 if (needToScanForQualifiers(proto->getArgType(i))) {
2119 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002120
Steve Naroff50d42052007-11-01 13:24:47 +00002121 const char *endBuf = startBuf;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002122 // scan forward (from the decl location) for argument types.
2123 scanToNextArgument(endBuf);
Steve Naroff50d42052007-11-01 13:24:47 +00002124 const char *startRef = 0, *endRef = 0;
2125 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2126 // Get the locations of the startRef, endRef.
Mike Stump11289f42009-09-09 15:08:12 +00002127 SourceLocation LessLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002128 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump11289f42009-09-09 15:08:12 +00002129 SourceLocation GreaterLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002130 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroff50d42052007-11-01 13:24:47 +00002131 // Comment out the protocol references.
Chris Lattner1780a852008-01-31 19:42:41 +00002132 InsertText(LessLoc, "/*", 2);
2133 InsertText(GreaterLoc, "*/", 2);
Steve Naroff50d42052007-11-01 13:24:47 +00002134 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002135 startBuf = ++endBuf;
2136 }
2137 else {
Steve Naroffc884aa82008-08-06 15:58:23 +00002138 // If the function name is derived from a macro expansion, then the
2139 // argument buffer will not follow the name. Need to speak with Chris.
2140 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002141 startBuf++; // scan forward (from the decl location) for argument types.
2142 startBuf++;
2143 }
Steve Naroff50d42052007-11-01 13:24:47 +00002144 }
Steve Naroff37e011c2007-10-31 04:38:33 +00002145}
2146
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002147void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2148 QualType QT = ND->getType();
2149 const Type* TypePtr = QT->getAs<Type>();
2150 if (!isa<TypeOfExprType>(TypePtr))
2151 return;
2152 while (isa<TypeOfExprType>(TypePtr)) {
2153 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2154 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2155 TypePtr = QT->getAs<Type>();
2156 }
2157 // FIXME. This will not work for multiple declarators; as in:
2158 // __typeof__(a) b,c,d;
2159 std::string TypeAsString(QT.getAsString());
2160 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2161 const char *startBuf = SM->getCharacterData(DeclLoc);
2162 if (ND->getInit()) {
2163 std::string Name(ND->getNameAsString());
2164 TypeAsString += " " + Name + " = ";
2165 Expr *E = ND->getInit();
2166 SourceLocation startLoc;
2167 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2168 startLoc = ECE->getLParenLoc();
2169 else
2170 startLoc = E->getLocStart();
2171 startLoc = SM->getInstantiationLoc(startLoc);
2172 const char *endBuf = SM->getCharacterData(startLoc);
2173 ReplaceText(DeclLoc, endBuf-startBuf-1,
2174 TypeAsString.c_str(), TypeAsString.size());
2175 }
2176 else {
2177 SourceLocation X = ND->getLocEnd();
2178 X = SM->getInstantiationLoc(X);
2179 const char *endBuf = SM->getCharacterData(X);
2180 ReplaceText(DeclLoc, endBuf-startBuf-1,
2181 TypeAsString.c_str(), TypeAsString.size());
2182 }
2183}
2184
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002185// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002186void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002187 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2188 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002189 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002190 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002191 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002192 false /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002193 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002194 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002195 SelGetUidIdent, getFuncType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002196 FunctionDecl::Extern, false);
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002197}
2198
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002199void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002200 // declared in <objc/objc.h>
Douglas Gregor1e21c192009-01-09 01:47:02 +00002201 if (FD->getIdentifier() &&
2202 strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002203 SelGetUidFunctionDecl = FD;
Steve Naroff37e011c2007-10-31 04:38:33 +00002204 return;
2205 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002206 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002207}
2208
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002209void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2210 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2211 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2212 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2213 if (!proto)
2214 return;
2215 QualType Type = proto->getResultType();
2216 std::string FdStr = Type.getAsString();
2217 FdStr += " ";
2218 FdStr += FD->getNameAsCString();
2219 FdStr += "(";
2220 unsigned numArgs = proto->getNumArgs();
2221 for (unsigned i = 0; i < numArgs; i++) {
2222 QualType ArgType = proto->getArgType(i);
2223 FdStr += ArgType.getAsString();
2224
2225 if (i+1 < numArgs)
2226 FdStr += ", ";
2227 }
2228 FdStr += ");\n";
2229 InsertText(FunLocStart, FdStr.c_str(), FdStr.size());
2230 CurFunctionDeclToDeclareForBlock = 0;
2231}
2232
Steve Naroff17978c42008-03-11 17:37:02 +00002233// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002234void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroff17978c42008-03-11 17:37:02 +00002235 if (SuperContructorFunctionDecl)
2236 return;
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002237 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroff17978c42008-03-11 17:37:02 +00002238 llvm::SmallVector<QualType, 16> ArgTys;
2239 QualType argT = Context->getObjCIdType();
2240 assert(!argT.isNull() && "Can't find 'id' type");
2241 ArgTys.push_back(argT);
2242 ArgTys.push_back(argT);
2243 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2244 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002245 false, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002246 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002247 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002248 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002249 FunctionDecl::Extern, false);
Steve Naroff17978c42008-03-11 17:37:02 +00002250}
2251
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002252// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002253void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002254 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2255 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002256 QualType argT = Context->getObjCIdType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002257 assert(!argT.isNull() && "Can't find 'id' type");
2258 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002259 argT = Context->getObjCSelType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002260 assert(!argT.isNull() && "Can't find 'SEL' type");
2261 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002262 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002263 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002264 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002265 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002266 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002267 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002268 FunctionDecl::Extern, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002269}
2270
Steve Naroff7fa2f042007-11-15 10:28:18 +00002271// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002272void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002273 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2274 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002275 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002276 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002277 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002278 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2279 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2280 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002281 argT = Context->getObjCSelType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002282 assert(!argT.isNull() && "Can't find 'SEL' type");
2283 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002284 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff7fa2f042007-11-15 10:28:18 +00002285 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002286 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002287 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002288 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002289 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002290 FunctionDecl::Extern, false);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002291}
2292
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002293// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002294void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002295 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2296 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002297 QualType argT = Context->getObjCIdType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002298 assert(!argT.isNull() && "Can't find 'id' type");
2299 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002300 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002301 assert(!argT.isNull() && "Can't find 'SEL' type");
2302 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002303 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002304 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002305 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002306 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002307 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002308 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002309 FunctionDecl::Extern, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002310}
2311
Mike Stump11289f42009-09-09 15:08:12 +00002312// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002313// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002314void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump11289f42009-09-09 15:08:12 +00002315 IdentifierInfo *msgSendIdent =
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002316 &Context->Idents.get("objc_msgSendSuper_stret");
2317 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002318 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002319 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002320 &Context->Idents.get("objc_super"));
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002321 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2322 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2323 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002324 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002325 assert(!argT.isNull() && "Can't find 'SEL' type");
2326 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002327 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002328 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002329 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002330 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002331 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002332 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002333 FunctionDecl::Extern, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002334}
2335
Steve Naroff2e4e3852008-05-08 22:02:18 +00002336// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002337void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002338 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2339 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002340 QualType argT = Context->getObjCIdType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002341 assert(!argT.isNull() && "Can't find 'id' type");
2342 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002343 argT = Context->getObjCSelType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002344 assert(!argT.isNull() && "Can't find 'SEL' type");
2345 ArgTys.push_back(argT);
Steve Naroff2e4e3852008-05-08 22:02:18 +00002346 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002347 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002348 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002349 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002350 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002351 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002352 FunctionDecl::Extern, false);
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002353}
2354
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002355// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002356void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002357 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2358 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002359 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002360 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002361 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002362 false /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002363 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002364 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002365 getClassIdent, getClassType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002366 FunctionDecl::Extern, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002367}
2368
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002369// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002370void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002371 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2372 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002373 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002374 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002375 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002376 false /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002377 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002378 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002379 getClassIdent, getClassType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002380 FunctionDecl::Extern, false);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002381}
2382
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002383Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffce8e8862008-03-15 00:55:56 +00002384 QualType strType = getConstantStringStructType();
2385
2386 std::string S = "__NSConstantStringImpl_";
Steve Naroffa6141f02008-05-31 03:35:42 +00002387
2388 std::string tmpName = InFileName;
2389 unsigned i;
2390 for (i=0; i < tmpName.length(); i++) {
2391 char c = tmpName.at(i);
2392 // replace any non alphanumeric characters with '_'.
2393 if (!isalpha(c) && (c < '0' || c > '9'))
2394 tmpName[i] = '_';
2395 }
2396 S += tmpName;
2397 S += "_";
Steve Naroffce8e8862008-03-15 00:55:56 +00002398 S += utostr(NumObjCStringLiterals++);
2399
Steve Naroff00a31762008-03-27 22:29:16 +00002400 Preamble += "static __NSConstantStringImpl " + S;
2401 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2402 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffce8e8862008-03-15 00:55:56 +00002403 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremenek2d470fc2008-09-13 05:16:45 +00002404 std::string prettyBufS;
2405 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00002406 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2407 PrintingPolicy(LangOpts));
Steve Naroff00a31762008-03-27 22:29:16 +00002408 Preamble += prettyBuf.str();
2409 Preamble += ",";
Steve Naroff94ed6dc2009-12-06 01:48:44 +00002410 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00002411
2412 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2413 &Context->Idents.get(S.c_str()), strType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002414 VarDecl::Static);
Ted Kremenek5a201952009-02-07 01:47:29 +00002415 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
2416 Expr *Unop = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002417 Context->getPointerType(DRE->getType()),
Steve Naroffce8e8862008-03-15 00:55:56 +00002418 SourceLocation());
Steve Naroff265a6b92007-11-08 14:30:50 +00002419 // cast to NSConstantString *
John McCall97513962010-01-15 18:39:57 +00002420 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2421 CastExpr::CK_Unknown, Unop);
Chris Lattner2e0d2602008-01-31 19:37:57 +00002422 ReplaceStmt(Exp, cast);
Steve Naroff22216db2008-12-04 23:50:32 +00002423 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff265a6b92007-11-08 14:30:50 +00002424 return cast;
Steve Naroffa397efd2007-11-03 11:27:19 +00002425}
2426
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002427ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002428 // check if we are sending a message to 'super'
Douglas Gregorffca3a22009-01-09 17:18:27 +00002429 if (!CurMethodDef || !CurMethodDef->isInstanceMethod()) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002430
Douglas Gregor8ea1f532008-11-04 14:56:14 +00002431 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
Mike Stump11289f42009-09-09 15:08:12 +00002432 const ObjCObjectPointerType *OPT =
John McCall9dd450b2009-09-21 23:43:11 +00002433 Super->getType()->getAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00002434 assert(OPT);
2435 const ObjCInterfaceType *IT = OPT->getInterfaceType();
Chris Lattnera9b3cae2008-06-21 18:04:54 +00002436 return IT->getDecl();
2437 }
2438 return 0;
Steve Naroff7fa2f042007-11-15 10:28:18 +00002439}
2440
2441// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002442QualType RewriteObjC::getSuperStructType() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002443 if (!SuperStructDecl) {
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002444 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002445 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002446 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002447 QualType FieldTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00002448
Steve Naroff7fa2f042007-11-15 10:28:18 +00002449 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002450 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002451 // struct objc_class *super;
Mike Stump11289f42009-09-09 15:08:12 +00002452 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor91f84212008-12-11 16:49:14 +00002453
Steve Naroff7fa2f042007-11-15 10:28:18 +00002454 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002455 for (unsigned i = 0; i < 2; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002456 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2457 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002458 FieldTypes[i], 0,
2459 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002460 /*Mutable=*/false));
Douglas Gregor91f84212008-12-11 16:49:14 +00002461 }
Mike Stump11289f42009-09-09 15:08:12 +00002462
Douglas Gregord5058122010-02-11 01:19:42 +00002463 SuperStructDecl->completeDefinition();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002464 }
2465 return Context->getTagDeclType(SuperStructDecl);
2466}
2467
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002468QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffce8e8862008-03-15 00:55:56 +00002469 if (!ConstantStringDecl) {
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002470 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002471 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002472 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffce8e8862008-03-15 00:55:56 +00002473 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00002474
Steve Naroffce8e8862008-03-15 00:55:56 +00002475 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002476 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffce8e8862008-03-15 00:55:56 +00002477 // int flags;
Mike Stump11289f42009-09-09 15:08:12 +00002478 FieldTypes[1] = Context->IntTy;
Steve Naroffce8e8862008-03-15 00:55:56 +00002479 // char *str;
Mike Stump11289f42009-09-09 15:08:12 +00002480 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffce8e8862008-03-15 00:55:56 +00002481 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00002482 FieldTypes[3] = Context->LongTy;
Douglas Gregor91f84212008-12-11 16:49:14 +00002483
Steve Naroffce8e8862008-03-15 00:55:56 +00002484 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002485 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002486 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2487 ConstantStringDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00002488 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002489 FieldTypes[i], 0,
Douglas Gregor91f84212008-12-11 16:49:14 +00002490 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002491 /*Mutable=*/true));
Douglas Gregor91f84212008-12-11 16:49:14 +00002492 }
2493
Douglas Gregord5058122010-02-11 01:19:42 +00002494 ConstantStringDecl->completeDefinition();
Steve Naroffce8e8862008-03-15 00:55:56 +00002495 }
2496 return Context->getTagDeclType(ConstantStringDecl);
2497}
2498
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002499Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002500 if (!SelGetUidFunctionDecl)
2501 SynthSelGetUidFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002502 if (!MsgSendFunctionDecl)
2503 SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002504 if (!MsgSendSuperFunctionDecl)
2505 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002506 if (!MsgSendStretFunctionDecl)
2507 SynthMsgSendStretFunctionDecl();
2508 if (!MsgSendSuperStretFunctionDecl)
2509 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002510 if (!MsgSendFpretFunctionDecl)
2511 SynthMsgSendFpretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002512 if (!GetClassFunctionDecl)
2513 SynthGetClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002514 if (!GetMetaClassFunctionDecl)
2515 SynthGetMetaClassFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002516
Steve Naroff7fa2f042007-11-15 10:28:18 +00002517 // default to objc_msgSend().
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002518 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2519 // May need to use objc_msgSend_stret() as well.
2520 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroffd9803712009-04-29 16:37:50 +00002521 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2522 QualType resultType = mDecl->getResultType();
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002523 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002524 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002525 else if (resultType->isRealFloatingType())
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002526 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002527 }
Mike Stump11289f42009-09-09 15:08:12 +00002528
Steve Naroff574440f2007-10-24 22:48:43 +00002529 // Synthesize a call to objc_msgSend().
2530 llvm::SmallVector<Expr*, 8> MsgExprs;
2531 IdentifierInfo *clsName = Exp->getClassName();
Mike Stump11289f42009-09-09 15:08:12 +00002532
Steve Naroff574440f2007-10-24 22:48:43 +00002533 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2534 if (clsName) { // class message.
Steve Naroff6c79f972008-07-24 19:44:33 +00002535 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2536 // the 'super' idiom within a class method.
Daniel Dunbar07d07852009-10-18 21:17:35 +00002537 if (clsName->getName() == "super") {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002538 MsgSendFlavor = MsgSendSuperFunctionDecl;
2539 if (MsgSendStretFlavor)
2540 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2541 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002542
2543 ObjCInterfaceDecl *SuperDecl =
Steve Naroff677ab3a2008-10-27 17:20:55 +00002544 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002545
2546 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00002547
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002548 // set the receiver to self, the first argument to all methods.
Steve Naroffd9803712009-04-29 16:37:50 +00002549 InitExprs.push_back(
John McCall97513962010-01-15 18:39:57 +00002550 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2551 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002552 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroffd9803712009-04-29 16:37:50 +00002553 Context->getObjCIdType(),
John McCall97513962010-01-15 18:39:57 +00002554 SourceLocation()))
2555 ); // set the 'receiver'.
Steve Naroffd9803712009-04-29 16:37:50 +00002556
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002557 llvm::SmallVector<Expr*, 8> ClsExprs;
2558 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002559 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002560 SuperDecl->getIdentifier()->getNameStart(),
2561 SuperDecl->getIdentifier()->getLength(),
2562 false, argType, SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002563 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002564 &ClsExprs[0],
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002565 ClsExprs.size());
2566 // To turn off a warning, type-cast to 'id'
Douglas Gregore200adc2008-10-27 19:41:14 +00002567 InitExprs.push_back( // set 'super class', using objc_getClass().
John McCall97513962010-01-15 18:39:57 +00002568 NoTypeInfoCStyleCastExpr(Context,
2569 Context->getObjCIdType(),
2570 CastExpr::CK_Unknown, Cls));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002571 // struct objc_super
2572 QualType superType = getSuperStructType();
Steve Naroff0b844f02008-03-11 18:14:26 +00002573 Expr *SuperRep;
Mike Stump11289f42009-09-09 15:08:12 +00002574
Steve Naroff0b844f02008-03-11 18:14:26 +00002575 if (LangOpts.Microsoft) {
2576 SynthSuperContructorFunctionDecl();
2577 // Simulate a contructor call...
Mike Stump11289f42009-09-09 15:08:12 +00002578 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff0b844f02008-03-11 18:14:26 +00002579 superType, SourceLocation());
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002580 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002581 InitExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002582 superType, SourceLocation());
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002583 // The code for super is a little tricky to prevent collision with
2584 // the structure definition in the header. The rewriter has it's own
2585 // internal definition (__rw_objc_super) that is uses. This is why
2586 // we need the cast below. For example:
2587 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2588 //
Ted Kremenek5a201952009-02-07 01:47:29 +00002589 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002590 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002591 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00002592 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2593 Context->getPointerType(superType),
2594 CastExpr::CK_Unknown, SuperRep);
Mike Stump11289f42009-09-09 15:08:12 +00002595 } else {
Steve Naroff0b844f02008-03-11 18:14:26 +00002596 // (struct objc_super) { <exprs from above> }
Mike Stump11289f42009-09-09 15:08:12 +00002597 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2598 &InitExprs[0], InitExprs.size(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002599 SourceLocation());
John McCalle15bbff2010-01-18 19:35:47 +00002600 TypeSourceInfo *superTInfo
2601 = Context->getTrivialTypeSourceInfo(superType);
John McCall5d7aa7f2010-01-19 22:33:45 +00002602 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2603 superType, ILE, false);
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002604 // struct objc_super *
Ted Kremenek5a201952009-02-07 01:47:29 +00002605 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002606 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002607 SourceLocation());
Steve Naroff0b844f02008-03-11 18:14:26 +00002608 }
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002609 MsgExprs.push_back(SuperRep);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002610 } else {
2611 llvm::SmallVector<Expr*, 8> ClsExprs;
2612 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002613 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002614 clsName->getNameStart(),
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002615 clsName->getLength(),
2616 false, argType,
2617 SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002618 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002619 &ClsExprs[0],
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002620 ClsExprs.size());
2621 MsgExprs.push_back(Cls);
2622 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002623 } else { // instance message.
2624 Expr *recExpr = Exp->getReceiver();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002625
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002626 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002627 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002628 if (MsgSendStretFlavor)
2629 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff7fa2f042007-11-15 10:28:18 +00002630 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002631
Steve Naroff7fa2f042007-11-15 10:28:18 +00002632 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00002633
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002634 InitExprs.push_back(
John McCall97513962010-01-15 18:39:57 +00002635 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2636 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002637 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroff97adf602008-07-16 22:35:27 +00002638 Context->getObjCIdType(),
John McCall97513962010-01-15 18:39:57 +00002639 SourceLocation()))
2640 ); // set the 'receiver'.
Mike Stump11289f42009-09-09 15:08:12 +00002641
Steve Naroff7fa2f042007-11-15 10:28:18 +00002642 llvm::SmallVector<Expr*, 8> ClsExprs;
2643 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002644 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002645 SuperDecl->getIdentifier()->getNameStart(),
2646 SuperDecl->getIdentifier()->getLength(),
2647 false, argType, SourceLocation()));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002648 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002649 &ClsExprs[0],
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002650 ClsExprs.size());
Fariborz Jahaniand5db92b2007-12-05 17:29:46 +00002651 // To turn off a warning, type-cast to 'id'
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002652 InitExprs.push_back(
Douglas Gregore200adc2008-10-27 19:41:14 +00002653 // set 'super class', using objc_getClass().
John McCall97513962010-01-15 18:39:57 +00002654 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2655 CastExpr::CK_Unknown, Cls));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002656 // struct objc_super
2657 QualType superType = getSuperStructType();
Steve Naroff17978c42008-03-11 17:37:02 +00002658 Expr *SuperRep;
Mike Stump11289f42009-09-09 15:08:12 +00002659
Steve Naroff17978c42008-03-11 17:37:02 +00002660 if (LangOpts.Microsoft) {
2661 SynthSuperContructorFunctionDecl();
2662 // Simulate a contructor call...
Mike Stump11289f42009-09-09 15:08:12 +00002663 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff17978c42008-03-11 17:37:02 +00002664 superType, SourceLocation());
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002665 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002666 InitExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002667 superType, SourceLocation());
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002668 // The code for super is a little tricky to prevent collision with
2669 // the structure definition in the header. The rewriter has it's own
2670 // internal definition (__rw_objc_super) that is uses. This is why
2671 // we need the cast below. For example:
2672 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2673 //
Ted Kremenek5a201952009-02-07 01:47:29 +00002674 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002675 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002676 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00002677 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2678 Context->getPointerType(superType),
2679 CastExpr::CK_Unknown, SuperRep);
Steve Naroff17978c42008-03-11 17:37:02 +00002680 } else {
2681 // (struct objc_super) { <exprs from above> }
Mike Stump11289f42009-09-09 15:08:12 +00002682 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2683 &InitExprs[0], InitExprs.size(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002684 SourceLocation());
John McCalle15bbff2010-01-18 19:35:47 +00002685 TypeSourceInfo *superTInfo
2686 = Context->getTrivialTypeSourceInfo(superType);
John McCall5d7aa7f2010-01-19 22:33:45 +00002687 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2688 superType, ILE, false);
Steve Naroff17978c42008-03-11 17:37:02 +00002689 }
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002690 MsgExprs.push_back(SuperRep);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002691 } else {
Fariborz Jahanianff6a4552007-12-07 21:21:21 +00002692 // Remove all type-casts because it may contain objc-style types; e.g.
2693 // Foo<Proto> *.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002694 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanianff6a4552007-12-07 21:21:21 +00002695 recExpr = CE->getSubExpr();
John McCall97513962010-01-15 18:39:57 +00002696 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2697 CastExpr::CK_Unknown, recExpr);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002698 MsgExprs.push_back(recExpr);
2699 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002700 }
Steve Naroffa397efd2007-11-03 11:27:19 +00002701 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff574440f2007-10-24 22:48:43 +00002702 llvm::SmallVector<Expr*, 8> SelExprs;
2703 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002704 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00002705 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00002706 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00002707 false, argType, SourceLocation()));
Steve Naroff574440f2007-10-24 22:48:43 +00002708 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2709 &SelExprs[0], SelExprs.size());
2710 MsgExprs.push_back(SelExp);
Mike Stump11289f42009-09-09 15:08:12 +00002711
Steve Naroff574440f2007-10-24 22:48:43 +00002712 // Now push any user supplied arguments.
2713 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroffe7f18192007-11-14 23:54:14 +00002714 Expr *userExpr = Exp->getArg(i);
Steve Narofff60782b2007-11-15 02:58:25 +00002715 // Make all implicit casts explicit...ICE comes in handy:-)
2716 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2717 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregore200adc2008-10-27 19:41:14 +00002718 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002719 ? Context->getObjCIdType()
Douglas Gregore200adc2008-10-27 19:41:14 +00002720 : ICE->getType();
John McCall97513962010-01-15 18:39:57 +00002721 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CastExpr::CK_Unknown,
2722 userExpr);
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002723 }
2724 // Make id<P...> cast into an 'id' cast.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002725 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002726 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregorf19b2312008-10-28 15:36:24 +00002727 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002728 userExpr = CE->getSubExpr();
John McCall97513962010-01-15 18:39:57 +00002729 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2730 CastExpr::CK_Unknown, userExpr);
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002731 }
Mike Stump11289f42009-09-09 15:08:12 +00002732 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002733 MsgExprs.push_back(userExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00002734 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2735 // out the argument in the original expression (since we aren't deleting
2736 // the ObjCMessageExpr). See RewritePropertySetter() usage for more info.
2737 //Exp->setArg(i, 0);
Steve Naroff574440f2007-10-24 22:48:43 +00002738 }
Steve Narofff36987c2007-11-04 22:37:50 +00002739 // Generate the funky cast.
2740 CastExpr *cast;
2741 llvm::SmallVector<QualType, 8> ArgTypes;
2742 QualType returnType;
Mike Stump11289f42009-09-09 15:08:12 +00002743
Steve Narofff36987c2007-11-04 22:37:50 +00002744 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff44864e42007-11-15 10:43:57 +00002745 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2746 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2747 else
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002748 ArgTypes.push_back(Context->getObjCIdType());
2749 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattnera4997152009-02-20 18:43:26 +00002750 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Narofff36987c2007-11-04 22:37:50 +00002751 // Push any user argument types.
Chris Lattnera4997152009-02-20 18:43:26 +00002752 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2753 E = OMD->param_end(); PI != E; ++PI) {
2754 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump11289f42009-09-09 15:08:12 +00002755 ? Context->getObjCIdType()
Chris Lattnera4997152009-02-20 18:43:26 +00002756 : (*PI)->getType();
Steve Naroff52c65fa2008-10-29 14:49:46 +00002757 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffa5c0db82008-12-11 21:05:33 +00002758 if (isTopLevelBlockPointerType(t)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002759 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroff52c65fa2008-10-29 14:49:46 +00002760 t = Context->getPointerType(BPT->getPointeeType());
2761 }
Steve Naroff98eb8d12007-11-05 14:36:37 +00002762 ArgTypes.push_back(t);
2763 }
Chris Lattnera4997152009-02-20 18:43:26 +00002764 returnType = OMD->getResultType()->isObjCQualifiedIdType()
2765 ? Context->getObjCIdType() : OMD->getResultType();
Steve Narofff36987c2007-11-04 22:37:50 +00002766 } else {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002767 returnType = Context->getObjCIdType();
Steve Narofff36987c2007-11-04 22:37:50 +00002768 }
2769 // Get the type, we will need to reference it in a couple spots.
Steve Naroff7fa2f042007-11-15 10:28:18 +00002770 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002771
Steve Narofff36987c2007-11-04 22:37:50 +00002772 // Create a reference to the objc_msgSend() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00002773 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002774 SourceLocation());
Steve Narofff36987c2007-11-04 22:37:50 +00002775
Mike Stump11289f42009-09-09 15:08:12 +00002776 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Narofff36987c2007-11-04 22:37:50 +00002777 // If we don't do this cast, we get the following bizarre warning/note:
2778 // xx.m:13: warning: function called through a non-compatible type
2779 // xx.m:13: note: if this code is reached, the program will abort
John McCall97513962010-01-15 18:39:57 +00002780 cast = NoTypeInfoCStyleCastExpr(Context,
2781 Context->getPointerType(Context->VoidTy),
2782 CastExpr::CK_Unknown, DRE);
Mike Stump11289f42009-09-09 15:08:12 +00002783
Steve Narofff36987c2007-11-04 22:37:50 +00002784 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00002785 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00002786 &ArgTypes[0], ArgTypes.size(),
Steve Naroff327f0f42008-03-18 02:02:04 +00002787 // If we don't have a method decl, force a variadic cast.
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002788 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Narofff36987c2007-11-04 22:37:50 +00002789 castType = Context->getPointerType(castType);
John McCall97513962010-01-15 18:39:57 +00002790 cast = NoTypeInfoCStyleCastExpr(Context, castType, CastExpr::CK_Unknown,
2791 cast);
Steve Narofff36987c2007-11-04 22:37:50 +00002792
2793 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00002794 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump11289f42009-09-09 15:08:12 +00002795
John McCall9dd450b2009-09-21 23:43:11 +00002796 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002797 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002798 MsgExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002799 FT->getResultType(), SourceLocation());
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002800 Stmt *ReplacingStmt = CE;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002801 if (MsgSendStretFlavor) {
2802 // We have the method which returns a struct/union. Must also generate
2803 // call to objc_msgSend_stret and hang both varieties on a conditional
2804 // expression which dictate which one to envoke depending on size of
2805 // method's return type.
Mike Stump11289f42009-09-09 15:08:12 +00002806
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002807 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00002808 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002809 SourceLocation());
2810 // Need to cast objc_msgSend_stret to "void *" (see above comment).
John McCall97513962010-01-15 18:39:57 +00002811 cast = NoTypeInfoCStyleCastExpr(Context,
2812 Context->getPointerType(Context->VoidTy),
2813 CastExpr::CK_Unknown, STDRE);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002814 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00002815 castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00002816 &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002817 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002818 castType = Context->getPointerType(castType);
John McCall97513962010-01-15 18:39:57 +00002819 cast = NoTypeInfoCStyleCastExpr(Context, castType, CastExpr::CK_Unknown,
2820 cast);
Mike Stump11289f42009-09-09 15:08:12 +00002821
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002822 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00002823 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump11289f42009-09-09 15:08:12 +00002824
John McCall9dd450b2009-09-21 23:43:11 +00002825 FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002826 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002827 MsgExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002828 FT->getResultType(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002829
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002830 // Build sizeof(returnType)
Mike Stump11289f42009-09-09 15:08:12 +00002831 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
John McCallbcd03502009-12-07 02:54:59 +00002832 Context->getTrivialTypeSourceInfo(returnType),
Sebastian Redl6f282892008-11-11 17:56:53 +00002833 Context->getSizeType(),
2834 SourceLocation(), SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002835 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2836 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2837 // For X86 it is more complicated and some kind of target specific routine
2838 // is needed to decide what to do.
Mike Stump11289f42009-09-09 15:08:12 +00002839 unsigned IntSize =
Chris Lattner37e05872008-03-05 18:54:05 +00002840 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Mike Stump11289f42009-09-09 15:08:12 +00002841 IntegerLiteral *limit = new (Context) IntegerLiteral(llvm::APInt(IntSize, 8),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002842 Context->IntTy,
2843 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002844 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
2845 BinaryOperator::LE,
2846 Context->IntTy,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002847 SourceLocation());
2848 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump11289f42009-09-09 15:08:12 +00002849 ConditionalOperator *CondExpr =
Douglas Gregor7e112b02009-08-26 14:37:04 +00002850 new (Context) ConditionalOperator(lessThanExpr,
2851 SourceLocation(), CE,
2852 SourceLocation(), STCE, returnType);
Ted Kremenek5a201952009-02-07 01:47:29 +00002853 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002854 }
Mike Stump11289f42009-09-09 15:08:12 +00002855 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002856 return ReplacingStmt;
2857}
2858
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002859Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002860 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Mike Stump11289f42009-09-09 15:08:12 +00002861
Steve Naroff574440f2007-10-24 22:48:43 +00002862 // Now do the actual rewrite.
Chris Lattner2e0d2602008-01-31 19:37:57 +00002863 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00002864
2865 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002866 return ReplacingStmt;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002867}
2868
Steve Naroffd9803712009-04-29 16:37:50 +00002869// typedef struct objc_object Protocol;
2870QualType RewriteObjC::getProtocolType() {
2871 if (!ProtocolTypeDecl) {
John McCallbcd03502009-12-07 02:54:59 +00002872 TypeSourceInfo *TInfo
2873 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroffd9803712009-04-29 16:37:50 +00002874 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002875 SourceLocation(),
Steve Naroffd9803712009-04-29 16:37:50 +00002876 &Context->Idents.get("Protocol"),
John McCallbcd03502009-12-07 02:54:59 +00002877 TInfo);
Steve Naroffd9803712009-04-29 16:37:50 +00002878 }
2879 return Context->getTypeDeclType(ProtocolTypeDecl);
2880}
2881
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00002882/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroffd9803712009-04-29 16:37:50 +00002883/// a synthesized/forward data reference (to the protocol's metadata).
2884/// The forward references (and metadata) are generated in
2885/// RewriteObjC::HandleTranslationUnit().
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002886Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroffd9803712009-04-29 16:37:50 +00002887 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
2888 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump11289f42009-09-09 15:08:12 +00002889 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Douglas Gregored6c7442009-11-23 11:41:28 +00002890 ID, getProtocolType(), 0, VarDecl::Extern);
Steve Naroffd9803712009-04-29 16:37:50 +00002891 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), SourceLocation());
2892 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
2893 Context->getPointerType(DRE->getType()),
2894 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00002895 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
2896 CastExpr::CK_Unknown,
2897 DerefExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00002898 ReplaceStmt(Exp, castExpr);
2899 ProtocolExprDecls.insert(Exp->getProtocol());
Mike Stump11289f42009-09-09 15:08:12 +00002900 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffd9803712009-04-29 16:37:50 +00002901 return castExpr;
Mike Stump11289f42009-09-09 15:08:12 +00002902
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00002903}
2904
Mike Stump11289f42009-09-09 15:08:12 +00002905bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002906 const char *endBuf) {
2907 while (startBuf < endBuf) {
2908 if (*startBuf == '#') {
2909 // Skip whitespace.
2910 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2911 ;
2912 if (!strncmp(startBuf, "if", strlen("if")) ||
2913 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2914 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2915 !strncmp(startBuf, "define", strlen("define")) ||
2916 !strncmp(startBuf, "undef", strlen("undef")) ||
2917 !strncmp(startBuf, "else", strlen("else")) ||
2918 !strncmp(startBuf, "elif", strlen("elif")) ||
2919 !strncmp(startBuf, "endif", strlen("endif")) ||
2920 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2921 !strncmp(startBuf, "include", strlen("include")) ||
2922 !strncmp(startBuf, "import", strlen("import")) ||
2923 !strncmp(startBuf, "include_next", strlen("include_next")))
2924 return true;
2925 }
2926 startBuf++;
2927 }
2928 return false;
2929}
2930
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002931/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002932/// an objective-c class with ivars.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002933void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002934 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002935 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Mike Stump11289f42009-09-09 15:08:12 +00002936 assert(CDecl->getNameAsCString() &&
Douglas Gregor77324f32008-11-17 14:58:09 +00002937 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00002938 // Do not synthesize more than once.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002939 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00002940 return;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002941 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattner8d1c04f2008-03-16 21:08:55 +00002942 int NumIvars = CDecl->ivar_size();
Steve Naroffdde78982007-11-14 19:25:57 +00002943 SourceLocation LocStart = CDecl->getLocStart();
2944 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00002945
Steve Naroffdde78982007-11-14 19:25:57 +00002946 const char *startBuf = SM->getCharacterData(LocStart);
2947 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump11289f42009-09-09 15:08:12 +00002948
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00002949 // If no ivars and no root or if its root, directly or indirectly,
2950 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattner8d1c04f2008-03-16 21:08:55 +00002951 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2952 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner184e65d2009-04-14 23:22:57 +00002953 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Chris Lattner9cc55f52008-01-31 19:51:04 +00002954 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00002955 return;
2956 }
Mike Stump11289f42009-09-09 15:08:12 +00002957
2958 // FIXME: This has potential of causing problem. If
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002959 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00002960 Result += "\nstruct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002961 Result += CDecl->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +00002962 if (LangOpts.Microsoft)
2963 Result += "_IMPL";
Steve Naroffdc5b6b22008-03-12 00:25:36 +00002964
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002965 if (NumIvars > 0) {
Steve Naroffdde78982007-11-14 19:25:57 +00002966 const char *cursor = strchr(startBuf, '{');
Mike Stump11289f42009-09-09 15:08:12 +00002967 assert((cursor && endBuf)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002968 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002969 // If the buffer contains preprocessor directives, we do more fine-grained
2970 // rewrites. This is intended to fix code that looks like (which occurs in
2971 // NSURL.h, for example):
2972 //
2973 // #ifdef XYZ
2974 // @interface Foo : NSObject
2975 // #else
2976 // @interface FooBar : NSObject
2977 // #endif
2978 // {
2979 // int i;
2980 // }
2981 // @end
2982 //
2983 // This clause is segregated to avoid breaking the common case.
2984 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump11289f42009-09-09 15:08:12 +00002985 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002986 CDecl->getClassLoc();
2987 const char *endHeader = SM->getCharacterData(L);
Chris Lattner184e65d2009-04-14 23:22:57 +00002988 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002989
Chris Lattnerf5b77512009-02-20 18:18:36 +00002990 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002991 // advance to the end of the referenced protocols.
2992 while (endHeader < cursor && *endHeader != '>') endHeader++;
2993 endHeader++;
2994 }
2995 // rewrite the original header
2996 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2997 } else {
2998 // rewrite the original header *without* disturbing the '{'
Steve Naroffb0e33902009-12-04 21:36:32 +00002999 ReplaceText(LocStart, cursor-startBuf, Result.c_str(), Result.size());
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003000 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003001 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroffdde78982007-11-14 19:25:57 +00003002 Result = "\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003003 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00003004 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003005 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00003006 Result += "_IVARS;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003007
Steve Naroffdde78982007-11-14 19:25:57 +00003008 // insert the super class structure definition.
Chris Lattner1780a852008-01-31 19:42:41 +00003009 SourceLocation OnePastCurly =
3010 LocStart.getFileLocWithOffset(cursor-startBuf+1);
3011 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Naroffdde78982007-11-14 19:25:57 +00003012 }
3013 cursor++; // past '{'
Mike Stump11289f42009-09-09 15:08:12 +00003014
Steve Naroffdde78982007-11-14 19:25:57 +00003015 // Now comment out any visibility specifiers.
3016 while (cursor < endBuf) {
3017 if (*cursor == '@') {
3018 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner174a8252007-11-14 22:57:51 +00003019 // Skip whitespace.
3020 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3021 /*scan*/;
3022
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003023 // FIXME: presence of @public, etc. inside comment results in
3024 // this transformation as well, which is still correct c-code.
Steve Naroffdde78982007-11-14 19:25:57 +00003025 if (!strncmp(cursor, "public", strlen("public")) ||
3026 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffaf91b9a2008-04-04 22:34:24 +00003027 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003028 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattner1780a852008-01-31 19:42:41 +00003029 InsertText(atLoc, "// ", 3);
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003030 }
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003031 // FIXME: If there are cases where '<' is used in ivar declaration part
3032 // of user code, then scan the ivar list and use needToScanForQualifiers
3033 // for type checking.
3034 else if (*cursor == '<') {
3035 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner1780a852008-01-31 19:42:41 +00003036 InsertText(atLoc, "/* ", 3);
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003037 cursor = strchr(cursor, '>');
3038 cursor++;
3039 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner1780a852008-01-31 19:42:41 +00003040 InsertText(atLoc, " */", 3);
Steve Naroff295570a2008-10-30 12:09:33 +00003041 } else if (*cursor == '^') { // rewrite block specifier.
3042 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
3043 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003044 }
Steve Naroffdde78982007-11-14 19:25:57 +00003045 cursor++;
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003046 }
Steve Naroffdde78982007-11-14 19:25:57 +00003047 // Don't forget to add a ';'!!
Chris Lattner1780a852008-01-31 19:42:41 +00003048 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Naroffdde78982007-11-14 19:25:57 +00003049 } else { // we don't have any instance variables - insert super struct.
Chris Lattner184e65d2009-04-14 23:22:57 +00003050 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Naroffdde78982007-11-14 19:25:57 +00003051 Result += " {\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003052 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00003053 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003054 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00003055 Result += "_IVARS;\n};\n";
Chris Lattner9cc55f52008-01-31 19:51:04 +00003056 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003057 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003058 // Mark this struct as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003059 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Naroff13e74872008-05-06 18:26:51 +00003060 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003061}
3062
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003063// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003064/// class methods.
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003065template<typename MethodIterator>
3066void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
3067 MethodIterator MethodEnd,
Fariborz Jahanian3df412a2007-10-25 00:14:44 +00003068 bool IsInstanceMethod,
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003069 const char *prefix,
Chris Lattner211f8b82007-10-25 17:07:24 +00003070 const char *ClassName,
3071 std::string &Result) {
Chris Lattner31bc07e2007-12-12 07:46:12 +00003072 if (MethodBegin == MethodEnd) return;
Mike Stump11289f42009-09-09 15:08:12 +00003073
Chris Lattner31bc07e2007-12-12 07:46:12 +00003074 if (!objc_impl_method) {
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003075 /* struct _objc_method {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003076 SEL _cmd;
3077 char *method_types;
3078 void *_imp;
3079 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003080 */
Chris Lattner211f8b82007-10-25 17:07:24 +00003081 Result += "\nstruct _objc_method {\n";
3082 Result += "\tSEL _cmd;\n";
3083 Result += "\tchar *method_types;\n";
3084 Result += "\tvoid *_imp;\n";
3085 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003086
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003087 objc_impl_method = true;
Fariborz Jahanian74a1cfa2007-10-19 00:36:46 +00003088 }
Mike Stump11289f42009-09-09 15:08:12 +00003089
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003090 // Build _objc_method_list for class's methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003091
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003092 /* struct {
3093 struct _objc_method_list *next_method;
3094 int method_count;
3095 struct _objc_method method_list[];
3096 }
3097 */
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003098 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003099 Result += "\nstatic struct {\n";
3100 Result += "\tstruct _objc_method_list *next_method;\n";
3101 Result += "\tint method_count;\n";
3102 Result += "\tstruct _objc_method method_list[";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003103 Result += utostr(NumMethods);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003104 Result += "];\n} _OBJC_";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003105 Result += prefix;
3106 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
3107 Result += "_METHODS_";
3108 Result += ClassName;
Steve Naroffb327e492008-03-12 17:18:30 +00003109 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003110 Result += IsInstanceMethod ? "inst" : "cls";
3111 Result += "_meth\")))= ";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003112 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003113
Chris Lattner31bc07e2007-12-12 07:46:12 +00003114 Result += "\t,{{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00003115 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattner31bc07e2007-12-12 07:46:12 +00003116 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003117 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattner31bc07e2007-12-12 07:46:12 +00003118 Result += "\", \"";
3119 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003120 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003121 Result += MethodInternalNames[*MethodBegin];
3122 Result += "}\n";
3123 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3124 Result += "\t ,{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00003125 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003126 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003127 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003128 Result += "\", \"";
3129 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003130 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003131 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanian56338352007-11-13 21:02:00 +00003132 Result += "}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003133 }
Chris Lattner31bc07e2007-12-12 07:46:12 +00003134 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003135}
3136
Steve Naroffd9803712009-04-29 16:37:50 +00003137/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner390d39a2008-07-21 21:32:27 +00003138void RewriteObjC::
Steve Naroffd9803712009-04-29 16:37:50 +00003139RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, const char *prefix,
3140 const char *ClassName, std::string &Result) {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003141 static bool objc_protocol_methods = false;
Steve Naroffd9803712009-04-29 16:37:50 +00003142
3143 // Output struct protocol_methods holder of method selector and type.
3144 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3145 /* struct protocol_methods {
3146 SEL _cmd;
3147 char *method_types;
3148 }
3149 */
3150 Result += "\nstruct _protocol_methods {\n";
3151 Result += "\tstruct objc_selector *_cmd;\n";
3152 Result += "\tchar *method_types;\n";
3153 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003154
Steve Naroffd9803712009-04-29 16:37:50 +00003155 objc_protocol_methods = true;
3156 }
3157 // Do not synthesize the protocol more than once.
3158 if (ObjCSynthesizedProtocols.count(PDecl))
3159 return;
Mike Stump11289f42009-09-09 15:08:12 +00003160
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003161 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3162 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3163 PDecl->instmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003164 /* struct _objc_protocol_method_list {
3165 int protocol_method_count;
3166 struct protocol_methods protocols[];
3167 }
Steve Naroff251084d2008-03-12 01:06:30 +00003168 */
Steve Naroffd9803712009-04-29 16:37:50 +00003169 Result += "\nstatic struct {\n";
3170 Result += "\tint protocol_method_count;\n";
3171 Result += "\tstruct _protocol_methods protocol_methods[";
3172 Result += utostr(NumMethods);
3173 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3174 Result += PDecl->getNameAsString();
3175 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3176 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003177
Steve Naroffd9803712009-04-29 16:37:50 +00003178 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003179 for (ObjCProtocolDecl::instmeth_iterator
3180 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003181 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003182 if (I == PDecl->instmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003183 Result += "\t ,{{(struct objc_selector *)\"";
3184 else
3185 Result += "\t ,{(struct objc_selector *)\"";
3186 Result += (*I)->getSelector().getAsString().c_str();
3187 std::string MethodTypeString;
3188 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3189 Result += "\", \"";
3190 Result += MethodTypeString;
3191 Result += "\"}\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003192 }
Steve Naroffd9803712009-04-29 16:37:50 +00003193 Result += "\t }\n};\n";
3194 }
Mike Stump11289f42009-09-09 15:08:12 +00003195
Steve Naroffd9803712009-04-29 16:37:50 +00003196 // Output class methods declared in this protocol.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003197 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3198 PDecl->classmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003199 if (NumMethods > 0) {
3200 /* struct _objc_protocol_method_list {
3201 int protocol_method_count;
3202 struct protocol_methods protocols[];
3203 }
3204 */
3205 Result += "\nstatic struct {\n";
3206 Result += "\tint protocol_method_count;\n";
3207 Result += "\tstruct _protocol_methods protocol_methods[";
3208 Result += utostr(NumMethods);
3209 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3210 Result += PDecl->getNameAsString();
3211 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3212 "{\n\t";
3213 Result += utostr(NumMethods);
3214 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003215
Steve Naroffd9803712009-04-29 16:37:50 +00003216 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003217 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003218 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003219 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003220 if (I == PDecl->classmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003221 Result += "\t ,{{(struct objc_selector *)\"";
3222 else
3223 Result += "\t ,{(struct objc_selector *)\"";
3224 Result += (*I)->getSelector().getAsString().c_str();
3225 std::string MethodTypeString;
3226 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3227 Result += "\", \"";
3228 Result += MethodTypeString;
3229 Result += "\"}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003230 }
Steve Naroffd9803712009-04-29 16:37:50 +00003231 Result += "\t }\n};\n";
3232 }
3233
3234 // Output:
3235 /* struct _objc_protocol {
3236 // Objective-C 1.0 extensions
3237 struct _objc_protocol_extension *isa;
3238 char *protocol_name;
3239 struct _objc_protocol **protocol_list;
3240 struct _objc_protocol_method_list *instance_methods;
3241 struct _objc_protocol_method_list *class_methods;
Mike Stump11289f42009-09-09 15:08:12 +00003242 };
Steve Naroffd9803712009-04-29 16:37:50 +00003243 */
3244 static bool objc_protocol = false;
3245 if (!objc_protocol) {
3246 Result += "\nstruct _objc_protocol {\n";
3247 Result += "\tstruct _objc_protocol_extension *isa;\n";
3248 Result += "\tchar *protocol_name;\n";
3249 Result += "\tstruct _objc_protocol **protocol_list;\n";
3250 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3251 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003252 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003253
Steve Naroffd9803712009-04-29 16:37:50 +00003254 objc_protocol = true;
Chris Lattner388f6e92008-07-21 21:33:21 +00003255 }
Mike Stump11289f42009-09-09 15:08:12 +00003256
Steve Naroffd9803712009-04-29 16:37:50 +00003257 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3258 Result += PDecl->getNameAsString();
3259 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3260 "{\n\t0, \"";
3261 Result += PDecl->getNameAsString();
3262 Result += "\", 0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003263 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003264 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3265 Result += PDecl->getNameAsString();
3266 Result += ", ";
3267 }
3268 else
3269 Result += "0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003270 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003271 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3272 Result += PDecl->getNameAsString();
3273 Result += "\n";
3274 }
3275 else
3276 Result += "0\n";
3277 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003278
Steve Naroffd9803712009-04-29 16:37:50 +00003279 // Mark this protocol as having been generated.
3280 if (!ObjCSynthesizedProtocols.insert(PDecl))
3281 assert(false && "protocol already synthesized");
3282
3283}
3284
3285void RewriteObjC::
3286RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
3287 const char *prefix, const char *ClassName,
3288 std::string &Result) {
3289 if (Protocols.empty()) return;
Mike Stump11289f42009-09-09 15:08:12 +00003290
Steve Naroffd9803712009-04-29 16:37:50 +00003291 for (unsigned i = 0; i != Protocols.size(); i++)
3292 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3293
Chris Lattner388f6e92008-07-21 21:33:21 +00003294 // Output the top lovel protocol meta-data for the class.
3295 /* struct _objc_protocol_list {
3296 struct _objc_protocol_list *next;
3297 int protocol_count;
3298 struct _objc_protocol *class_protocols[];
3299 }
3300 */
3301 Result += "\nstatic struct {\n";
3302 Result += "\tstruct _objc_protocol_list *next;\n";
3303 Result += "\tint protocol_count;\n";
3304 Result += "\tstruct _objc_protocol *class_protocols[";
3305 Result += utostr(Protocols.size());
3306 Result += "];\n} _OBJC_";
3307 Result += prefix;
3308 Result += "_PROTOCOLS_";
3309 Result += ClassName;
3310 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3311 "{\n\t0, ";
3312 Result += utostr(Protocols.size());
3313 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003314
Chris Lattner388f6e92008-07-21 21:33:21 +00003315 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003316 Result += Protocols[0]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003317 Result += " \n";
Mike Stump11289f42009-09-09 15:08:12 +00003318
Chris Lattner388f6e92008-07-21 21:33:21 +00003319 for (unsigned i = 1; i != Protocols.size(); i++) {
3320 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003321 Result += Protocols[i]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003322 Result += "\n";
3323 }
3324 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003325}
3326
Steve Naroffd9803712009-04-29 16:37:50 +00003327
Mike Stump11289f42009-09-09 15:08:12 +00003328/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003329/// implementation.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003330void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003331 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003332 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003333 // Find category declaration for this implementation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003334 ObjCCategoryDecl *CDecl;
Mike Stump11289f42009-09-09 15:08:12 +00003335 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003336 CDecl = CDecl->getNextClassCategory())
3337 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3338 break;
Mike Stump11289f42009-09-09 15:08:12 +00003339
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003340 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003341 FullCategoryName += '_';
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003342 FullCategoryName += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003343
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003344 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003345 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003346 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003347
3348 // If any of our property implementations have associated getters or
3349 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003350 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3351 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003352 Prop != PropEnd; ++Prop) {
3353 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3354 continue;
3355 if (!(*Prop)->getPropertyIvarDecl())
3356 continue;
3357 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3358 if (!PD)
3359 continue;
3360 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3361 InstanceMethods.push_back(Getter);
3362 if (PD->isReadOnly())
3363 continue;
3364 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3365 InstanceMethods.push_back(Setter);
3366 }
3367 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003368 true, "CATEGORY_", FullCategoryName.c_str(),
3369 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003370
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003371 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003372 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003373 false, "CATEGORY_", FullCategoryName.c_str(),
3374 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003375
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003376 // Protocols referenced in class declaration?
Fariborz Jahanian989e0392007-11-13 22:09:49 +00003377 // Null CDecl is case of a category implementation with no category interface
3378 if (CDecl)
Steve Naroffd9803712009-04-29 16:37:50 +00003379 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
3380 FullCategoryName.c_str(), Result);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003381 /* struct _objc_category {
3382 char *category_name;
3383 char *class_name;
3384 struct _objc_method_list *instance_methods;
3385 struct _objc_method_list *class_methods;
3386 struct _objc_protocol_list *protocols;
3387 // Objective-C 1.0 extensions
3388 uint32_t size; // sizeof (struct _objc_category)
Mike Stump11289f42009-09-09 15:08:12 +00003389 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003390 // @property decl.
Mike Stump11289f42009-09-09 15:08:12 +00003391 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003392 */
Mike Stump11289f42009-09-09 15:08:12 +00003393
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003394 static bool objc_category = false;
3395 if (!objc_category) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003396 Result += "\nstruct _objc_category {\n";
3397 Result += "\tchar *category_name;\n";
3398 Result += "\tchar *class_name;\n";
3399 Result += "\tstruct _objc_method_list *instance_methods;\n";
3400 Result += "\tstruct _objc_method_list *class_methods;\n";
3401 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003402 Result += "\tunsigned int size;\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003403 Result += "\tstruct _objc_property_list *instance_properties;\n";
3404 Result += "};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003405 objc_category = true;
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003406 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003407 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3408 Result += FullCategoryName;
Steve Naroffb327e492008-03-12 17:18:30 +00003409 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003410 Result += IDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003411 Result += "\"\n\t, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003412 Result += ClassDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003413 Result += "\"\n";
Mike Stump11289f42009-09-09 15:08:12 +00003414
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003415 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003416 Result += "\t, (struct _objc_method_list *)"
3417 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3418 Result += FullCategoryName;
3419 Result += "\n";
3420 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003421 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003422 Result += "\t, 0\n";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003423 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003424 Result += "\t, (struct _objc_method_list *)"
3425 "&_OBJC_CATEGORY_CLASS_METHODS_";
3426 Result += FullCategoryName;
3427 Result += "\n";
3428 }
3429 else
3430 Result += "\t, 0\n";
Mike Stump11289f42009-09-09 15:08:12 +00003431
Chris Lattnerf5b77512009-02-20 18:18:36 +00003432 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump11289f42009-09-09 15:08:12 +00003433 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003434 Result += FullCategoryName;
3435 Result += "\n";
3436 }
3437 else
3438 Result += "\t, 0\n";
3439 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003440}
3441
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003442/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3443/// ivar offset.
Mike Stump11289f42009-09-09 15:08:12 +00003444void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
3445 ObjCIvarDecl *ivar,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003446 std::string &Result) {
Steve Naroffde7d0f62008-07-16 18:22:22 +00003447 if (ivar->isBitField()) {
3448 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3449 // place all bitfields at offset 0.
3450 Result += "0";
3451 } else {
3452 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003453 Result += IDecl->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003454 if (LangOpts.Microsoft)
3455 Result += "_IMPL";
3456 Result += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003457 Result += ivar->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003458 Result += ")";
3459 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003460}
3461
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003462//===----------------------------------------------------------------------===//
3463// Meta Data Emission
3464//===----------------------------------------------------------------------===//
3465
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003466void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003467 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003468 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump11289f42009-09-09 15:08:12 +00003469
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003470 // Explictly declared @interface's are already synthesized.
Steve Naroffaac654a2009-04-20 20:09:33 +00003471 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump11289f42009-09-09 15:08:12 +00003472 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003473 // produce correct synthesis as yet.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003474 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003475 }
Mike Stump11289f42009-09-09 15:08:12 +00003476
Chris Lattner30d23e82007-12-12 07:56:42 +00003477 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003478 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump11289f42009-09-09 15:08:12 +00003479 ? IDecl->ivar_size()
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003480 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003481 if (NumIvars > 0) {
3482 static bool objc_ivar = false;
3483 if (!objc_ivar) {
3484 /* struct _objc_ivar {
3485 char *ivar_name;
3486 char *ivar_type;
3487 int ivar_offset;
Mike Stump11289f42009-09-09 15:08:12 +00003488 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003489 */
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003490 Result += "\nstruct _objc_ivar {\n";
3491 Result += "\tchar *ivar_name;\n";
3492 Result += "\tchar *ivar_type;\n";
3493 Result += "\tint ivar_offset;\n";
3494 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003495
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003496 objc_ivar = true;
3497 }
3498
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003499 /* struct {
3500 int ivar_count;
3501 struct _objc_ivar ivar_list[nIvars];
Mike Stump11289f42009-09-09 15:08:12 +00003502 };
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003503 */
Mike Stump11289f42009-09-09 15:08:12 +00003504 Result += "\nstatic struct {\n";
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003505 Result += "\tint ivar_count;\n";
3506 Result += "\tstruct _objc_ivar ivar_list[";
3507 Result += utostr(NumIvars);
3508 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003509 Result += IDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003510 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003511 "{\n\t";
3512 Result += utostr(NumIvars);
3513 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003514
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003515 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor5f662052009-04-23 03:23:08 +00003516 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003517 if (!IDecl->ivar_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00003518 for (ObjCImplementationDecl::ivar_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003519 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor5f662052009-04-23 03:23:08 +00003520 IV != IVEnd; ++IV)
3521 IVars.push_back(*IV);
3522 IVI = IVars.begin();
3523 IVE = IVars.end();
Chris Lattner30d23e82007-12-12 07:56:42 +00003524 } else {
3525 IVI = CDecl->ivar_begin();
3526 IVE = CDecl->ivar_end();
3527 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003528 Result += "\t,{{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003529 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003530 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003531 std::string TmpString, StrEncoding;
3532 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3533 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003534 Result += StrEncoding;
3535 Result += "\", ";
Chris Lattner30d23e82007-12-12 07:56:42 +00003536 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003537 Result += "}\n";
Chris Lattner30d23e82007-12-12 07:56:42 +00003538 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003539 Result += "\t ,{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003540 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003541 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003542 std::string TmpString, StrEncoding;
3543 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3544 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003545 Result += StrEncoding;
3546 Result += "\", ";
Chris Lattner30d23e82007-12-12 07:56:42 +00003547 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003548 Result += "}\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003549 }
Mike Stump11289f42009-09-09 15:08:12 +00003550
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003551 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003552 }
Mike Stump11289f42009-09-09 15:08:12 +00003553
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003554 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003555 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003556 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003557
3558 // If any of our property implementations have associated getters or
3559 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003560 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3561 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003562 Prop != PropEnd; ++Prop) {
3563 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3564 continue;
3565 if (!(*Prop)->getPropertyIvarDecl())
3566 continue;
3567 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3568 if (!PD)
3569 continue;
3570 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3571 InstanceMethods.push_back(Getter);
3572 if (PD->isReadOnly())
3573 continue;
3574 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3575 InstanceMethods.push_back(Setter);
3576 }
3577 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattner86d7d912008-11-24 03:54:41 +00003578 true, "", IDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003579
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003580 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003581 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner86d7d912008-11-24 03:54:41 +00003582 false, "", IDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003583
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003584 // Protocols referenced in class declaration?
Steve Naroffd9803712009-04-29 16:37:50 +00003585 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
3586 "CLASS", CDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003587
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003588 // Declaration of class/meta-class metadata
3589 /* struct _objc_class {
3590 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003591 const char *super_class_name;
3592 char *name;
3593 long version;
3594 long info;
3595 long instance_size;
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003596 struct _objc_ivar_list *ivars;
3597 struct _objc_method_list *methods;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003598 struct objc_cache *cache;
3599 struct objc_protocol_list *protocols;
3600 const char *ivar_layout;
3601 struct _objc_class_ext *ext;
Mike Stump11289f42009-09-09 15:08:12 +00003602 };
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003603 */
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003604 static bool objc_class = false;
3605 if (!objc_class) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003606 Result += "\nstruct _objc_class {\n";
3607 Result += "\tstruct _objc_class *isa;\n";
3608 Result += "\tconst char *super_class_name;\n";
3609 Result += "\tchar *name;\n";
3610 Result += "\tlong version;\n";
3611 Result += "\tlong info;\n";
3612 Result += "\tlong instance_size;\n";
3613 Result += "\tstruct _objc_ivar_list *ivars;\n";
3614 Result += "\tstruct _objc_method_list *methods;\n";
3615 Result += "\tstruct objc_cache *cache;\n";
3616 Result += "\tstruct _objc_protocol_list *protocols;\n";
3617 Result += "\tconst char *ivar_layout;\n";
3618 Result += "\tstruct _objc_class_ext *ext;\n";
3619 Result += "};\n";
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003620 objc_class = true;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003621 }
Mike Stump11289f42009-09-09 15:08:12 +00003622
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003623 // Meta-class metadata generation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003624 ObjCInterfaceDecl *RootClass = 0;
3625 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003626 while (SuperClass) {
3627 RootClass = SuperClass;
3628 SuperClass = SuperClass->getSuperClass();
3629 }
3630 SuperClass = CDecl->getSuperClass();
Mike Stump11289f42009-09-09 15:08:12 +00003631
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003632 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003633 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003634 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003635 "{\n\t(struct _objc_class *)\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003636 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003637 Result += "\"";
3638
3639 if (SuperClass) {
3640 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003641 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003642 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003643 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003644 Result += "\"";
3645 }
3646 else {
3647 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003648 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003649 Result += "\"";
3650 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003651 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003652 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003653 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003654 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff0b844f02008-03-11 18:14:26 +00003655 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003656 Result += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003657 Result += "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003658 }
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003659 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003660 Result += ", 0\n";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003661 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003662 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003663 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003664 Result += ",0,0\n";
3665 }
Fariborz Jahanian486f7182007-10-24 20:54:23 +00003666 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003667 Result += "\t,0,0,0,0\n";
3668 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003669
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003670 // class metadata generation.
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003671 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003672 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003673 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003674 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003675 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003676 if (SuperClass) {
3677 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003678 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003679 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003680 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003681 Result += "\"";
3682 }
3683 else {
3684 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003685 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003686 Result += "\"";
3687 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003688 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003689 Result += ", 0,1";
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003690 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003691 Result += ",0";
3692 else {
3693 // class has size. Must synthesize its size.
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00003694 Result += ",sizeof(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003695 Result += CDecl->getNameAsString();
Steve Naroff14a07462008-03-10 23:33:22 +00003696 if (LangOpts.Microsoft)
3697 Result += "_IMPL";
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003698 Result += ")";
3699 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003700 if (NumIvars > 0) {
Steve Naroff17978c42008-03-11 17:37:02 +00003701 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003702 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003703 Result += "\n\t";
3704 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003705 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003706 Result += ",0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003707 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003708 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003709 Result += CDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003710 Result += ", 0\n\t";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003711 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003712 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003713 Result += ",0,0";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003714 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003715 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003716 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003717 Result += ", 0,0\n";
3718 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003719 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003720 Result += ",0,0,0\n";
3721 Result += "};\n";
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003722}
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003723
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003724/// RewriteImplementations - This routine rewrites all method implementations
3725/// and emits meta-data.
3726
Steve Narofff8cfd162008-11-13 20:07:04 +00003727void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003728 int ClsDefCount = ClassImplementation.size();
3729 int CatDefCount = CategoryImplementation.size();
Mike Stump11289f42009-09-09 15:08:12 +00003730
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003731 // Rewrite implemented methods
3732 for (int i = 0; i < ClsDefCount; i++)
3733 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump11289f42009-09-09 15:08:12 +00003734
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00003735 for (int i = 0; i < CatDefCount; i++)
3736 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofff8cfd162008-11-13 20:07:04 +00003737}
Mike Stump11289f42009-09-09 15:08:12 +00003738
Steve Narofff8cfd162008-11-13 20:07:04 +00003739void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3740 int ClsDefCount = ClassImplementation.size();
3741 int CatDefCount = CategoryImplementation.size();
3742
Steve Naroff30ac2222008-05-07 21:23:49 +00003743 // This is needed for determining instance variable offsets.
Fariborz Jahanian9ab63492010-01-07 18:31:42 +00003744 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003745 // For each implemented class, write out all its meta data.
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003746 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003747 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump11289f42009-09-09 15:08:12 +00003748
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003749 // For each implemented category, write out all its meta data.
3750 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003751 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroffd9803712009-04-29 16:37:50 +00003752
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003753 // Write objc_symtab metadata
3754 /*
3755 struct _objc_symtab
3756 {
3757 long sel_ref_cnt;
3758 SEL *refs;
3759 short cls_def_cnt;
3760 short cat_def_cnt;
3761 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump11289f42009-09-09 15:08:12 +00003762 };
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003763 */
Mike Stump11289f42009-09-09 15:08:12 +00003764
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003765 Result += "\nstruct _objc_symtab {\n";
3766 Result += "\tlong sel_ref_cnt;\n";
3767 Result += "\tSEL *refs;\n";
3768 Result += "\tshort cls_def_cnt;\n";
3769 Result += "\tshort cat_def_cnt;\n";
3770 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3771 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00003772
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003773 Result += "static struct _objc_symtab "
Steve Naroffb327e492008-03-12 17:18:30 +00003774 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003775 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003776 + ", " + utostr(CatDefCount) + "\n";
3777 for (int i = 0; i < ClsDefCount; i++) {
3778 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003779 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003780 Result += "\n";
3781 }
Mike Stump11289f42009-09-09 15:08:12 +00003782
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003783 for (int i = 0; i < CatDefCount; i++) {
3784 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003785 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003786 Result += "_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003787 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003788 Result += "\n";
3789 }
Mike Stump11289f42009-09-09 15:08:12 +00003790
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003791 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00003792
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003793 // Write objc_module metadata
Mike Stump11289f42009-09-09 15:08:12 +00003794
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003795 /*
3796 struct _objc_module {
3797 long version;
3798 long size;
3799 const char *name;
3800 struct _objc_symtab *symtab;
3801 }
3802 */
Mike Stump11289f42009-09-09 15:08:12 +00003803
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003804 Result += "\nstruct _objc_module {\n";
3805 Result += "\tlong version;\n";
3806 Result += "\tlong size;\n";
3807 Result += "\tconst char *name;\n";
3808 Result += "\tstruct _objc_symtab *symtab;\n";
3809 Result += "};\n\n";
3810 Result += "static struct _objc_module "
Steve Naroffb327e492008-03-12 17:18:30 +00003811 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003812 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003813 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003814 Result += "};\n\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00003815
3816 if (LangOpts.Microsoft) {
Steve Naroffd9803712009-04-29 16:37:50 +00003817 if (ProtocolExprDecls.size()) {
3818 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
3819 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump11289f42009-09-09 15:08:12 +00003820 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00003821 E = ProtocolExprDecls.end(); I != E; ++I) {
3822 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
3823 Result += (*I)->getNameAsString();
3824 Result += " = &_OBJC_PROTOCOL_";
3825 Result += (*I)->getNameAsString();
3826 Result += ";\n";
3827 }
3828 Result += "#pragma data_seg(pop)\n\n";
3829 }
Steve Naroff945a3b12008-03-10 20:43:59 +00003830 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroffcab93d52008-05-07 00:06:16 +00003831 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00003832 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3833 Result += "&_OBJC_MODULES;\n";
3834 Result += "#pragma data_seg(pop)\n\n";
3835 }
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003836}
Chris Lattnera7c19fe2007-10-16 22:36:42 +00003837
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00003838void RewriteObjC::RewriteByRefString(std::string &ResultStr,
3839 const std::string &Name,
3840 ValueDecl *VD) {
3841 assert(BlockByRefDeclNo.count(VD) &&
3842 "RewriteByRefString: ByRef decl missing");
3843 ResultStr += "struct __Block_byref_" + Name +
3844 "_" + utostr(BlockByRefDeclNo[VD]) ;
3845}
3846
Steve Naroff677ab3a2008-10-27 17:20:55 +00003847std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3848 const char *funcName,
3849 std::string Tag) {
3850 const FunctionType *AFT = CE->getFunctionType();
3851 QualType RT = AFT->getResultType();
3852 std::string StructRef = "struct " + Tag;
3853 std::string S = "static " + RT.getAsString() + " __" +
3854 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00003855
Steve Naroff677ab3a2008-10-27 17:20:55 +00003856 BlockDecl *BD = CE->getBlockDecl();
Mike Stump11289f42009-09-09 15:08:12 +00003857
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003858 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump11289f42009-09-09 15:08:12 +00003859 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Narofff26a1d42009-02-02 17:19:26 +00003860 // block (to reference imported block decl refs).
3861 S += "(" + StructRef + " *__cself)";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003862 } else if (BD->param_empty()) {
3863 S += "(" + StructRef + " *__cself)";
3864 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003865 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003866 assert(FT && "SynthesizeBlockFunc: No function proto");
3867 S += '(';
3868 // first add the implicit argument.
3869 S += StructRef + " *__cself, ";
3870 std::string ParamStr;
3871 for (BlockDecl::param_iterator AI = BD->param_begin(),
3872 E = BD->param_end(); AI != E; ++AI) {
3873 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003874 ParamStr = (*AI)->getNameAsString();
Douglas Gregor7de59662009-05-29 20:38:28 +00003875 (*AI)->getType().getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003876 S += ParamStr;
3877 }
3878 if (FT->isVariadic()) {
3879 if (!BD->param_empty()) S += ", ";
3880 S += "...";
3881 }
3882 S += ')';
3883 }
3884 S += " {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003885
Steve Naroff677ab3a2008-10-27 17:20:55 +00003886 // Create local declarations to avoid rewriting all closure decl ref exprs.
3887 // First, emit a declaration for all "by ref" decls.
Mike Stump11289f42009-09-09 15:08:12 +00003888 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003889 E = BlockByRefDecls.end(); I != E; ++I) {
3890 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003891 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00003892 std::string TypeString;
3893 RewriteByRefString(TypeString, Name, (*I));
3894 TypeString += " *";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00003895 Name = TypeString + Name;
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003896 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump11289f42009-09-09 15:08:12 +00003897 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003898 // Next, emit a declaration for all "by copy" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00003899 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003900 E = BlockByCopyDecls.end(); I != E; ++I) {
3901 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003902 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003903 // Handle nested closure invocation. For example:
3904 //
3905 // void (^myImportedClosure)(void);
3906 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003907 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003908 // void (^anotherClosure)(void);
3909 // anotherClosure = ^(void) {
3910 // myImportedClosure(); // import and invoke the closure
3911 // };
3912 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003913 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00003914 S += "struct __block_impl *";
3915 else
Douglas Gregor7de59662009-05-29 20:38:28 +00003916 (*I)->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003917 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003918 }
3919 std::string RewrittenStr = RewrittenBlockExprs[CE];
3920 const char *cstr = RewrittenStr.c_str();
3921 while (*cstr++ != '{') ;
3922 S += cstr;
3923 S += "\n";
3924 return S;
3925}
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00003926
Steve Naroff677ab3a2008-10-27 17:20:55 +00003927std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3928 const char *funcName,
3929 std::string Tag) {
3930 std::string StructRef = "struct " + Tag;
3931 std::string S = "static void __";
Mike Stump11289f42009-09-09 15:08:12 +00003932
Steve Naroff677ab3a2008-10-27 17:20:55 +00003933 S += funcName;
3934 S += "_block_copy_" + utostr(i);
3935 S += "(" + StructRef;
3936 S += "*dst, " + StructRef;
3937 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00003938 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003939 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00003940 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003941 S += (*I)->getNameAsString();
Steve Naroff5ac4eac2008-12-11 20:51:38 +00003942 S += ", (void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003943 S += (*I)->getNameAsString();
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003944 if (BlockByRefDecls.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003945 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003946 else
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003947 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003948 }
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003949 S += "}\n";
3950
Steve Naroff677ab3a2008-10-27 17:20:55 +00003951 S += "\nstatic void __";
3952 S += funcName;
3953 S += "_block_dispose_" + utostr(i);
3954 S += "(" + StructRef;
3955 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00003956 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003957 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00003958 S += "_Block_object_dispose((void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003959 S += (*I)->getNameAsString();
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003960 if (BlockByRefDecls.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003961 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003962 else
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003963 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003964 }
Mike Stump11289f42009-09-09 15:08:12 +00003965 S += "}\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003966 return S;
3967}
3968
Steve Naroff30484702009-12-06 21:14:13 +00003969std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3970 std::string Desc) {
Steve Naroff295570a2008-10-30 12:09:33 +00003971 std::string S = "\nstruct " + Tag;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003972 std::string Constructor = " " + Tag;
Mike Stump11289f42009-09-09 15:08:12 +00003973
Steve Naroff677ab3a2008-10-27 17:20:55 +00003974 S += " {\n struct __block_impl impl;\n";
Steve Naroff30484702009-12-06 21:14:13 +00003975 S += " struct " + Desc;
3976 S += "* Desc;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003977
Steve Naroff30484702009-12-06 21:14:13 +00003978 Constructor += "(void *fp, "; // Invoke function pointer.
3979 Constructor += "struct " + Desc; // Descriptor pointer.
3980 Constructor += " *desc";
Mike Stump11289f42009-09-09 15:08:12 +00003981
Steve Naroff677ab3a2008-10-27 17:20:55 +00003982 if (BlockDeclRefs.size()) {
3983 // Output all "by copy" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00003984 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003985 E = BlockByCopyDecls.end(); I != E; ++I) {
3986 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003987 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003988 std::string ArgName = "_" + FieldName;
3989 // Handle nested closure invocation. For example:
3990 //
3991 // void (^myImportedBlock)(void);
3992 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003993 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003994 // void (^anotherBlock)(void);
3995 // anotherBlock = ^(void) {
3996 // myImportedBlock(); // import and invoke the closure
3997 // };
3998 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003999 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004000 S += "struct __block_impl *";
4001 Constructor += ", void *" + ArgName;
4002 } else {
Douglas Gregor7de59662009-05-29 20:38:28 +00004003 (*I)->getType().getAsStringInternal(FieldName, Context->PrintingPolicy);
4004 (*I)->getType().getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004005 Constructor += ", " + ArgName;
4006 }
4007 S += FieldName + ";\n";
4008 }
4009 // Output all "by ref" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00004010 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004011 E = BlockByRefDecls.end(); I != E; ++I) {
4012 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004013 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004014 std::string ArgName = "_" + FieldName;
4015 // Handle nested closure invocation. For example:
4016 //
4017 // void (^myImportedBlock)(void);
4018 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00004019 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00004020 // void (^anotherBlock)(void);
4021 // anotherBlock = ^(void) {
4022 // myImportedBlock(); // import and invoke the closure
4023 // };
4024 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00004025 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004026 S += "struct __block_impl *";
4027 Constructor += ", void *" + ArgName;
4028 } else {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004029 std::string TypeString;
4030 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004031 TypeString += " *";
4032 FieldName = TypeString + FieldName;
4033 ArgName = TypeString + ArgName;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004034 Constructor += ", " + ArgName;
4035 }
4036 S += FieldName + "; // by ref\n";
4037 }
4038 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00004039 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00004040 if (GlobalVarDecl)
4041 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4042 else
4043 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00004044 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump11289f42009-09-09 15:08:12 +00004045
Steve Naroff30484702009-12-06 21:14:13 +00004046 Constructor += " Desc = desc;\n";
Mike Stump11289f42009-09-09 15:08:12 +00004047
Steve Naroff677ab3a2008-10-27 17:20:55 +00004048 // Initialize all "by copy" arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004049 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004050 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004051 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004052 Constructor += " ";
Steve Naroffa5c0db82008-12-11 21:05:33 +00004053 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004054 Constructor += Name + " = (struct __block_impl *)_";
4055 else
4056 Constructor += Name + " = _";
4057 Constructor += Name + ";\n";
4058 }
4059 // Initialize all "by ref" arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004060 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004061 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004062 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004063 Constructor += " ";
Steve Naroffa5c0db82008-12-11 21:05:33 +00004064 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004065 Constructor += Name + " = (struct __block_impl *)_";
4066 else
4067 Constructor += Name + " = _";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004068 Constructor += Name + "->__forwarding;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004069 }
4070 } else {
4071 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00004072 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00004073 if (GlobalVarDecl)
4074 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4075 else
4076 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00004077 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4078 Constructor += " Desc = desc;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004079 }
4080 Constructor += " ";
4081 Constructor += "}\n";
4082 S += Constructor;
4083 S += "};\n";
4084 return S;
4085}
4086
Steve Naroff30484702009-12-06 21:14:13 +00004087std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
4088 std::string ImplTag, int i,
4089 const char *FunName,
4090 unsigned hasCopy) {
4091 std::string S = "\nstatic struct " + DescTag;
4092
4093 S += " {\n unsigned long reserved;\n";
4094 S += " unsigned long Block_size;\n";
4095 if (hasCopy) {
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00004096 S += " void (*copy)(struct ";
4097 S += ImplTag; S += "*, struct ";
4098 S += ImplTag; S += "*);\n";
4099
4100 S += " void (*dispose)(struct ";
4101 S += ImplTag; S += "*);\n";
Steve Naroff30484702009-12-06 21:14:13 +00004102 }
4103 S += "} ";
4104
4105 S += DescTag + "_DATA = { 0, sizeof(struct ";
4106 S += ImplTag + ")";
4107 if (hasCopy) {
4108 S += ", __" + std::string(FunName) + "_block_copy_" + utostr(i);
4109 S += ", __" + std::string(FunName) + "_block_dispose_" + utostr(i);
4110 }
4111 S += "};\n";
4112 return S;
4113}
4114
Steve Naroff677ab3a2008-10-27 17:20:55 +00004115void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004116 const char *FunName) {
4117 // Insert declaration for the function in which block literal is used.
Fariborz Jahanian5c26eee2010-01-15 18:14:52 +00004118 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004119 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004120 // Insert closures that were part of the function.
4121 for (unsigned i = 0; i < Blocks.size(); i++) {
4122
4123 CollectBlockDeclRefInfo(Blocks[i]);
4124
Steve Naroff30484702009-12-06 21:14:13 +00004125 std::string ImplTag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
4126 std::string DescTag = "__" + std::string(FunName) + "_block_desc_" + utostr(i);
Mike Stump11289f42009-09-09 15:08:12 +00004127
Steve Naroff30484702009-12-06 21:14:13 +00004128 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004129
4130 InsertText(FunLocStart, CI.c_str(), CI.size());
4131
Steve Naroff30484702009-12-06 21:14:13 +00004132 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump11289f42009-09-09 15:08:12 +00004133
Steve Naroff677ab3a2008-10-27 17:20:55 +00004134 InsertText(FunLocStart, CF.c_str(), CF.size());
4135
4136 if (ImportedBlockDecls.size()) {
Steve Naroff30484702009-12-06 21:14:13 +00004137 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004138 InsertText(FunLocStart, HF.c_str(), HF.size());
4139 }
Steve Naroff30484702009-12-06 21:14:13 +00004140 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4141 ImportedBlockDecls.size() > 0);
4142 InsertText(FunLocStart, BD.c_str(), BD.size());
Mike Stump11289f42009-09-09 15:08:12 +00004143
Steve Naroff677ab3a2008-10-27 17:20:55 +00004144 BlockDeclRefs.clear();
4145 BlockByRefDecls.clear();
4146 BlockByCopyDecls.clear();
4147 BlockCallExprs.clear();
4148 ImportedBlockDecls.clear();
4149 }
4150 Blocks.clear();
4151 RewrittenBlockExprs.clear();
4152}
4153
4154void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4155 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner86d7d912008-11-24 03:54:41 +00004156 const char *FuncName = FD->getNameAsCString();
Mike Stump11289f42009-09-09 15:08:12 +00004157
Steve Naroff677ab3a2008-10-27 17:20:55 +00004158 SynthesizeBlockLiterals(FunLocStart, FuncName);
4159}
4160
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00004161static void BuildUniqueMethodName(std::string &Name,
4162 ObjCMethodDecl *MD) {
4163 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4164 Name = IFace->getNameAsCString();
4165 Name += "__" + MD->getSelector().getAsString();
4166 // Convert colons to underscores.
4167 std::string::size_type loc = 0;
4168 while ((loc = Name.find(":", loc)) != std::string::npos)
4169 Name.replace(loc, 1, "_");
4170}
4171
Steve Naroff677ab3a2008-10-27 17:20:55 +00004172void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroff295570a2008-10-30 12:09:33 +00004173 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4174 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanianb5f99c32010-01-29 01:55:49 +00004175 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00004176 std::string FuncName;
4177 BuildUniqueMethodName(FuncName, MD);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004178 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
4179}
4180
4181void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
4182 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4183 CI != E; ++CI)
4184 if (*CI) {
4185 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4186 GetBlockDeclRefExprs(CBE->getBody());
4187 else
4188 GetBlockDeclRefExprs(*CI);
4189 }
4190 // Handle specific things.
4191 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
4192 // FIXME: Handle enums.
4193 if (!isa<FunctionDecl>(CDRE->getDecl()))
4194 BlockDeclRefs.push_back(CDRE);
4195 return;
4196}
4197
4198void RewriteObjC::GetBlockCallExprs(Stmt *S) {
4199 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4200 CI != E; ++CI)
4201 if (*CI) {
4202 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4203 GetBlockCallExprs(CBE->getBody());
4204 else
4205 GetBlockCallExprs(*CI);
4206 }
Mike Stump11289f42009-09-09 15:08:12 +00004207
Steve Naroff677ab3a2008-10-27 17:20:55 +00004208 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
4209 if (CE->getCallee()->getType()->isBlockPointerType()) {
4210 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
4211 }
4212 }
4213 return;
4214}
4215
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004216Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004217 // Navigate to relevant type information.
Steve Naroff677ab3a2008-10-27 17:20:55 +00004218 const BlockPointerType *CPT = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004219
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004220 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004221 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004222 } else if (const BlockDeclRefExpr *CDRE =
4223 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004224 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004225 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004226 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004227 }
4228 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4229 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4230 }
4231 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4232 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4233 else if (const ConditionalOperator *CEXPR =
4234 dyn_cast<ConditionalOperator>(BlockExp)) {
4235 Expr *LHSExp = CEXPR->getLHS();
4236 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4237 Expr *RHSExp = CEXPR->getRHS();
4238 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4239 Expr *CONDExp = CEXPR->getCond();
4240 ConditionalOperator *CondExpr =
4241 new (Context) ConditionalOperator(CONDExp,
4242 SourceLocation(), cast<Expr>(LHSStmt),
4243 SourceLocation(), cast<Expr>(RHSStmt),
4244 Exp->getType());
4245 return CondExpr;
Fariborz Jahanian6ab7ed42009-12-18 01:15:21 +00004246 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4247 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004248 } else {
4249 assert(1 && "RewriteBlockClass: Bad type");
4250 }
4251 assert(CPT && "RewriteBlockClass: Bad type");
John McCall9dd450b2009-09-21 23:43:11 +00004252 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004253 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004254 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004255 // FTP will be null for closures that don't take arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004256
Steve Naroff350b6652008-10-30 10:07:53 +00004257 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
4258 SourceLocation(),
4259 &Context->Idents.get("__block_impl"));
4260 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff677ab3a2008-10-27 17:20:55 +00004261
Steve Naroff350b6652008-10-30 10:07:53 +00004262 // Generate a funky cast.
4263 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00004264
Steve Naroff350b6652008-10-30 10:07:53 +00004265 // Push the block argument type.
4266 ArgTypes.push_back(PtrBlock);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004267 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004268 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff350b6652008-10-30 10:07:53 +00004269 E = FTP->arg_type_end(); I && (I != E); ++I) {
4270 QualType t = *I;
4271 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffa5c0db82008-12-11 21:05:33 +00004272 if (isTopLevelBlockPointerType(t)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004273 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroff350b6652008-10-30 10:07:53 +00004274 t = Context->getPointerType(BPT->getPointeeType());
4275 }
4276 ArgTypes.push_back(t);
4277 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004278 }
Steve Naroff350b6652008-10-30 10:07:53 +00004279 // Now do the pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00004280 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
Steve Naroff350b6652008-10-30 10:07:53 +00004281 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004282
Steve Naroff350b6652008-10-30 10:07:53 +00004283 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump11289f42009-09-09 15:08:12 +00004284
John McCall97513962010-01-15 18:39:57 +00004285 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4286 CastExpr::CK_Unknown,
4287 const_cast<Expr*>(BlockExp));
Steve Naroff350b6652008-10-30 10:07:53 +00004288 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00004289 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4290 BlkCast);
Steve Naroff350b6652008-10-30 10:07:53 +00004291 //PE->dump();
Mike Stump11289f42009-09-09 15:08:12 +00004292
Douglas Gregor91f84212008-12-11 16:49:14 +00004293 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00004294 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004295 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek5a201952009-02-07 01:47:29 +00004296 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4297 FD->getType());
Mike Stump11289f42009-09-09 15:08:12 +00004298
John McCall97513962010-01-15 18:39:57 +00004299 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4300 CastExpr::CK_Unknown, ME);
Ted Kremenek5a201952009-02-07 01:47:29 +00004301 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump11289f42009-09-09 15:08:12 +00004302
Steve Naroff350b6652008-10-30 10:07:53 +00004303 llvm::SmallVector<Expr*, 8> BlkExprs;
4304 // Add the implicit argument.
4305 BlkExprs.push_back(BlkCast);
4306 // Add the user arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004307 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004308 E = Exp->arg_end(); I != E; ++I) {
Steve Naroff350b6652008-10-30 10:07:53 +00004309 BlkExprs.push_back(*I);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004310 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004311 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4312 BlkExprs.size(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004313 Exp->getType(), SourceLocation());
Steve Naroff350b6652008-10-30 10:07:53 +00004314 return CE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004315}
4316
4317void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004318 Stmt *BlockCall = SynthesizeBlockCall(Exp, Exp->getCallee());
Steve Naroff350b6652008-10-30 10:07:53 +00004319 ReplaceStmt(Exp, BlockCall);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004320}
4321
Steve Naroffd9803712009-04-29 16:37:50 +00004322// We need to return the rewritten expression to handle cases where the
4323// BlockDeclRefExpr is embedded in another expression being rewritten.
4324// For example:
4325//
4326// int main() {
4327// __block Foo *f;
4328// __block int i;
Mike Stump11289f42009-09-09 15:08:12 +00004329//
Steve Naroffd9803712009-04-29 16:37:50 +00004330// void (^myblock)() = ^() {
4331// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4332// i = 77;
4333// };
4334//}
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004335Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanian25c07fa2009-12-23 19:26:34 +00004336 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004337 // for each DeclRefExp where BYREFVAR is name of the variable.
4338 ValueDecl *VD;
4339 bool isArrow = true;
4340 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4341 VD = BDRE->getDecl();
4342 else {
4343 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4344 isArrow = false;
4345 }
4346
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004347 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4348 &Context->Idents.get("__forwarding"),
4349 Context->VoidPtrTy, 0,
4350 /*BitWidth=*/0, /*Mutable=*/true);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004351 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4352 FD, SourceLocation(),
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004353 FD->getType());
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004354
4355 const char *Name = VD->getNameAsCString();
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004356 FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4357 &Context->Idents.get(Name),
4358 Context->VoidPtrTy, 0,
4359 /*BitWidth=*/0, /*Mutable=*/true);
4360 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004361 DeclRefExp->getType());
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004362
4363
4364
Steve Narofff26a1d42009-02-02 17:19:26 +00004365 // Need parens to enforce precedence.
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004366 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4367 ME);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004368 ReplaceStmt(DeclRefExp, PE);
Steve Naroffd9803712009-04-29 16:37:50 +00004369 return PE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004370}
4371
Steve Naroffc989a7b2008-11-03 23:29:32 +00004372void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4373 SourceLocation LocStart = CE->getLParenLoc();
4374 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofff4b992a2008-10-28 20:29:00 +00004375
4376 // Need to avoid trying to rewrite synthesized casts.
4377 if (LocStart.isInvalid())
4378 return;
Steve Naroff3e7ced12008-11-03 11:20:24 +00004379 // Need to avoid trying to rewrite casts contained in macros.
4380 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4381 return;
Mike Stump11289f42009-09-09 15:08:12 +00004382
Steve Naroff677ab3a2008-10-27 17:20:55 +00004383 const char *startBuf = SM->getCharacterData(LocStart);
4384 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00004385 QualType QT = CE->getType();
4386 const Type* TypePtr = QT->getAs<Type>();
4387 if (isa<TypeOfExprType>(TypePtr)) {
4388 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4389 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4390 std::string TypeAsString = "(";
4391 TypeAsString += QT.getAsString();
4392 TypeAsString += ")";
4393 ReplaceText(LocStart, endBuf-startBuf+1,
4394 TypeAsString.c_str(), TypeAsString.size());
4395 return;
4396 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004397 // advance the location to startArgList.
4398 const char *argPtr = startBuf;
Mike Stump11289f42009-09-09 15:08:12 +00004399
Steve Naroff677ab3a2008-10-27 17:20:55 +00004400 while (*argPtr++ && (argPtr < endBuf)) {
4401 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004402 case '^':
4403 // Replace the '^' with '*'.
4404 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
4405 ReplaceText(LocStart, 1, "*", 1);
4406 break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004407 }
4408 }
4409 return;
4410}
4411
4412void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4413 SourceLocation DeclLoc = FD->getLocation();
4414 unsigned parenCount = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004415
Steve Naroff677ab3a2008-10-27 17:20:55 +00004416 // We have 1 or more arguments that have closure pointers.
4417 const char *startBuf = SM->getCharacterData(DeclLoc);
4418 const char *startArgList = strchr(startBuf, '(');
Mike Stump11289f42009-09-09 15:08:12 +00004419
Steve Naroff677ab3a2008-10-27 17:20:55 +00004420 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004421
Steve Naroff677ab3a2008-10-27 17:20:55 +00004422 parenCount++;
4423 // advance the location to startArgList.
4424 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4425 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump11289f42009-09-09 15:08:12 +00004426
Steve Naroff677ab3a2008-10-27 17:20:55 +00004427 const char *argPtr = startArgList;
Mike Stump11289f42009-09-09 15:08:12 +00004428
Steve Naroff677ab3a2008-10-27 17:20:55 +00004429 while (*argPtr++ && parenCount) {
4430 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004431 case '^':
4432 // Replace the '^' with '*'.
4433 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
4434 ReplaceText(DeclLoc, 1, "*", 1);
4435 break;
4436 case '(':
4437 parenCount++;
4438 break;
4439 case ')':
4440 parenCount--;
4441 break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004442 }
4443 }
4444 return;
4445}
4446
4447bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004448 const FunctionProtoType *FTP;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004449 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004450 if (PT) {
John McCall9dd450b2009-09-21 23:43:11 +00004451 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004452 } else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004453 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004454 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall9dd450b2009-09-21 23:43:11 +00004455 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004456 }
4457 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004458 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004459 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +00004460 if (isTopLevelBlockPointerType(*I))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004461 return true;
4462 }
4463 return false;
4464}
4465
Ted Kremenek5a201952009-02-07 01:47:29 +00004466void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4467 const char *&RParen) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004468 const char *argPtr = strchr(Name, '(');
4469 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004470
Steve Naroff677ab3a2008-10-27 17:20:55 +00004471 LParen = argPtr; // output the start.
4472 argPtr++; // skip past the left paren.
4473 unsigned parenCount = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004474
Steve Naroff677ab3a2008-10-27 17:20:55 +00004475 while (*argPtr && parenCount) {
4476 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004477 case '(': parenCount++; break;
4478 case ')': parenCount--; break;
4479 default: break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004480 }
4481 if (parenCount) argPtr++;
4482 }
4483 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4484 RParen = argPtr; // output the end
4485}
4486
4487void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4488 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4489 RewriteBlockPointerFunctionArgs(FD);
4490 return;
Mike Stump11289f42009-09-09 15:08:12 +00004491 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004492 // Handle Variables and Typedefs.
4493 SourceLocation DeclLoc = ND->getLocation();
4494 QualType DeclT;
4495 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4496 DeclT = VD->getType();
4497 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4498 DeclT = TDD->getUnderlyingType();
4499 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4500 DeclT = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00004501 else
Steve Naroff677ab3a2008-10-27 17:20:55 +00004502 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump11289f42009-09-09 15:08:12 +00004503
Steve Naroff677ab3a2008-10-27 17:20:55 +00004504 const char *startBuf = SM->getCharacterData(DeclLoc);
4505 const char *endBuf = startBuf;
4506 // scan backward (from the decl location) for the end of the previous decl.
4507 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4508 startBuf--;
Mike Stump11289f42009-09-09 15:08:12 +00004509
Steve Naroff677ab3a2008-10-27 17:20:55 +00004510 // *startBuf != '^' if we are dealing with a pointer to function that
4511 // may take block argument types (which will be handled below).
4512 if (*startBuf == '^') {
4513 // Replace the '^' with '*', computing a negative offset.
4514 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
4515 ReplaceText(DeclLoc, 1, "*", 1);
4516 }
4517 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4518 // Replace the '^' with '*' for arguments.
4519 DeclLoc = ND->getLocation();
4520 startBuf = SM->getCharacterData(DeclLoc);
4521 const char *argListBegin, *argListEnd;
4522 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4523 while (argListBegin < argListEnd) {
4524 if (*argListBegin == '^') {
4525 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
4526 ReplaceText(CaretLoc, 1, "*", 1);
4527 }
4528 argListBegin++;
4529 }
4530 }
4531 return;
4532}
4533
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004534
4535/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4536/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4537/// struct Block_byref_id_object *src) {
4538/// _Block_object_assign (&_dest->object, _src->object,
4539/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4540/// [|BLOCK_FIELD_IS_WEAK]) // object
4541/// _Block_object_assign(&_dest->object, _src->object,
4542/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4543/// [|BLOCK_FIELD_IS_WEAK]) // block
4544/// }
4545/// And:
4546/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4547/// _Block_object_dispose(_src->object,
4548/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4549/// [|BLOCK_FIELD_IS_WEAK]) // object
4550/// _Block_object_dispose(_src->object,
4551/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4552/// [|BLOCK_FIELD_IS_WEAK]) // block
4553/// }
4554
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004555std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4556 int flag) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004557 std::string S;
Benjamin Kramere056cea2010-01-10 19:57:50 +00004558 if (CopyDestroyCache.count(flag))
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004559 return S;
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004560 CopyDestroyCache.insert(flag);
4561 S = "static void __Block_byref_id_object_copy_";
4562 S += utostr(flag);
4563 S += "(void *dst, void *src) {\n";
4564
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004565 // offset into the object pointer is computed as:
4566 // void * + void* + int + int + void* + void *
4567 unsigned IntSize =
4568 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4569 unsigned VoidPtrSize =
4570 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4571
4572 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/8;
4573 S += " _Block_object_assign((char*)dst + ";
4574 S += utostr(offset);
4575 S += ", *(void * *) ((char*)src + ";
4576 S += utostr(offset);
4577 S += "), ";
4578 S += utostr(flag);
4579 S += ");\n}\n";
4580
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004581 S += "static void __Block_byref_id_object_dispose_";
4582 S += utostr(flag);
4583 S += "(void *src) {\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004584 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4585 S += utostr(offset);
4586 S += "), ";
4587 S += utostr(flag);
4588 S += ");\n}\n";
4589 return S;
4590}
4591
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004592/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4593/// the declaration into:
4594/// struct __Block_byref_ND {
4595/// void *__isa; // NULL for everything except __weak pointers
4596/// struct __Block_byref_ND *__forwarding;
4597/// int32_t __flags;
4598/// int32_t __size;
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004599/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4600/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004601/// typex ND;
4602/// };
4603///
4604/// It then replaces declaration of ND variable with:
4605/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4606/// __size=sizeof(struct __Block_byref_ND),
4607/// ND=initializer-if-any};
4608///
4609///
4610void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004611 // Insert declaration for the function in which block literal is
4612 // used.
4613 if (CurFunctionDeclToDeclareForBlock)
4614 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004615 int flag = 0;
4616 int isa = 0;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004617 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4618 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian92368a12009-12-30 20:38:08 +00004619 SourceLocation X = ND->getLocEnd();
4620 X = SM->getInstantiationLoc(X);
4621 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004622 std::string Name(ND->getNameAsString());
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004623 std::string ByrefType;
4624 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004625 ByrefType += " {\n";
4626 ByrefType += " void *__isa;\n";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004627 RewriteByRefString(ByrefType, Name, ND);
4628 ByrefType += " *__forwarding;\n";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004629 ByrefType += " int __flags;\n";
4630 ByrefType += " int __size;\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004631 // Add void *__Block_byref_id_object_copy;
4632 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004633 QualType Ty = ND->getType();
4634 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4635 if (HasCopyAndDispose) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004636 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4637 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004638 }
4639
4640 Ty.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004641 ByrefType += " " + Name + ";\n";
4642 ByrefType += "};\n";
4643 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004644 SourceLocation FunLocStart;
4645 if (CurFunctionDef)
4646 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4647 else {
4648 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4649 FunLocStart = CurMethodDef->getLocStart();
4650 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004651 InsertText(FunLocStart, ByrefType.c_str(), ByrefType.size());
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004652 if (Ty.isObjCGCWeak()) {
4653 flag |= BLOCK_FIELD_IS_WEAK;
4654 isa = 1;
4655 }
4656
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004657 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004658 flag = BLOCK_BYREF_CALLER;
4659 QualType Ty = ND->getType();
4660 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4661 if (Ty->isBlockPointerType())
4662 flag |= BLOCK_FIELD_IS_BLOCK;
4663 else
4664 flag |= BLOCK_FIELD_IS_OBJECT;
4665 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004666 if (!HF.empty())
4667 InsertText(FunLocStart, HF.c_str(), HF.size());
4668 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004669
4670 // struct __Block_byref_ND ND =
4671 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4672 // initializer-if-any};
4673 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanianf7945432010-01-05 18:15:57 +00004674 unsigned flags = 0;
4675 if (HasCopyAndDispose)
4676 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004677 Name = ND->getNameAsString();
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004678 ByrefType.clear();
4679 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004680 std::string ForwardingCastType("(");
4681 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004682 if (!hasInit) {
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004683 ByrefType += " " + Name + " = {(void*)";
4684 ByrefType += utostr(isa);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004685 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004686 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004687 ByrefType += ", ";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004688 ByrefType += "sizeof(";
4689 RewriteByRefString(ByrefType, Name, ND);
4690 ByrefType += ")";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004691 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004692 ByrefType += ", __Block_byref_id_object_copy_";
4693 ByrefType += utostr(flag);
4694 ByrefType += ", __Block_byref_id_object_dispose_";
4695 ByrefType += utostr(flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004696 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004697 ByrefType += "};\n";
4698 ReplaceText(DeclLoc, endBuf-startBuf+Name.size(),
4699 ByrefType.c_str(), ByrefType.size());
4700 }
4701 else {
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004702 SourceLocation startLoc;
4703 Expr *E = ND->getInit();
4704 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4705 startLoc = ECE->getLParenLoc();
4706 else
4707 startLoc = E->getLocStart();
Fariborz Jahanianb8646ed2010-01-05 23:06:29 +00004708 startLoc = SM->getInstantiationLoc(startLoc);
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004709 endBuf = SM->getCharacterData(startLoc);
4710
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004711 ByrefType += " " + Name;
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004712 ByrefType += " = {(void*)";
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004713 ByrefType += utostr(isa);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004714 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004715 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004716 ByrefType += ", ";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004717 ByrefType += "sizeof(";
4718 RewriteByRefString(ByrefType, Name, ND);
4719 ByrefType += "), ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004720 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004721 ByrefType += "__Block_byref_id_object_copy_";
4722 ByrefType += utostr(flag);
4723 ByrefType += ", __Block_byref_id_object_dispose_";
4724 ByrefType += utostr(flag);
4725 ByrefType += ", ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004726 }
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004727 ReplaceText(DeclLoc, endBuf-startBuf,
4728 ByrefType.c_str(), ByrefType.size());
Steve Naroff13468372009-12-23 17:24:33 +00004729
4730 // Complete the newly synthesized compound expression by inserting a right
4731 // curly brace before the end of the declaration.
4732 // FIXME: This approach avoids rewriting the initializer expression. It
4733 // also assumes there is only one declarator. For example, the following
4734 // isn't currently supported by this routine (in general):
4735 //
4736 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4737 //
4738 const char *startBuf = SM->getCharacterData(startLoc);
4739 const char *semiBuf = strchr(startBuf, ';');
4740 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4741 SourceLocation semiLoc =
4742 startLoc.getFileLocWithOffset(semiBuf-startBuf);
4743
4744 InsertText(semiLoc, "}", 1);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004745 }
Fariborz Jahanian81203462009-12-22 00:48:54 +00004746 return;
4747}
4748
Mike Stump11289f42009-09-09 15:08:12 +00004749void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004750 // Add initializers for any closure decl refs.
4751 GetBlockDeclRefExprs(Exp->getBody());
4752 if (BlockDeclRefs.size()) {
4753 // Unique all "by copy" declarations.
4754 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4755 if (!BlockDeclRefs[i]->isByRef())
4756 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
4757 // Unique all "by ref" declarations.
4758 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4759 if (BlockDeclRefs[i]->isByRef()) {
4760 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
4761 }
4762 // Find any imported blocks...they will need special attention.
4763 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00004764 if (BlockDeclRefs[i]->isByRef() ||
4765 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4766 BlockDeclRefs[i]->getType()->isBlockPointerType()) {
Steve Naroff832d8902008-11-13 17:40:07 +00004767 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004768 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4769 }
4770 }
4771}
4772
Steve Narofff4b992a2008-10-28 20:29:00 +00004773FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
4774 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004775 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Mike Stump11289f42009-09-09 15:08:12 +00004776 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00004777 ID, FType, 0, FunctionDecl::Extern, false,
Douglas Gregor739ef0c2009-02-25 16:33:18 +00004778 false);
Steve Narofff4b992a2008-10-28 20:29:00 +00004779}
4780
Steve Naroffd8907b72008-10-29 18:15:37 +00004781Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004782 Blocks.push_back(Exp);
4783
4784 CollectBlockDeclRefInfo(Exp);
4785 std::string FuncName;
Mike Stump11289f42009-09-09 15:08:12 +00004786
Steve Narofff4b992a2008-10-28 20:29:00 +00004787 if (CurFunctionDef)
Chris Lattnere4b95692008-11-24 03:33:13 +00004788 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00004789 else if (CurMethodDef)
4790 BuildUniqueMethodName(FuncName, CurMethodDef);
4791 else if (GlobalVarDecl)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004792 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump11289f42009-09-09 15:08:12 +00004793
Steve Narofff4b992a2008-10-28 20:29:00 +00004794 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump11289f42009-09-09 15:08:12 +00004795
Steve Narofff4b992a2008-10-28 20:29:00 +00004796 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4797 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump11289f42009-09-09 15:08:12 +00004798
Steve Narofff4b992a2008-10-28 20:29:00 +00004799 // Get a pointer to the function type so we can cast appropriately.
4800 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
4801
4802 FunctionDecl *FD;
4803 Expr *NewRep;
Mike Stump11289f42009-09-09 15:08:12 +00004804
Steve Narofff4b992a2008-10-28 20:29:00 +00004805 // Simulate a contructor call...
4806 FD = SynthBlockInitFunctionDecl(Tag.c_str());
Ted Kremenek5a201952009-02-07 01:47:29 +00004807 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004808
Steve Narofff4b992a2008-10-28 20:29:00 +00004809 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00004810
Steve Naroffe2514232008-10-29 21:23:59 +00004811 // Initialize the block function.
Steve Narofff4b992a2008-10-28 20:29:00 +00004812 FD = SynthBlockInitFunctionDecl(Func.c_str());
Ted Kremenek5a201952009-02-07 01:47:29 +00004813 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
4814 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00004815 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4816 CastExpr::CK_Unknown, Arg);
Mike Stump11289f42009-09-09 15:08:12 +00004817 InitExprs.push_back(castExpr);
4818
Steve Naroff30484702009-12-06 21:14:13 +00004819 // Initialize the block descriptor.
4820 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump11289f42009-09-09 15:08:12 +00004821
Steve Naroff30484702009-12-06 21:14:13 +00004822 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
4823 &Context->Idents.get(DescData.c_str()),
4824 Context->VoidPtrTy, 0,
4825 VarDecl::Static);
4826 UnaryOperator *DescRefExpr = new (Context) UnaryOperator(
4827 new (Context) DeclRefExpr(NewVD,
4828 Context->VoidPtrTy, SourceLocation()),
4829 UnaryOperator::AddrOf,
4830 Context->getPointerType(Context->VoidPtrTy),
4831 SourceLocation());
4832 InitExprs.push_back(DescRefExpr);
4833
Steve Narofff4b992a2008-10-28 20:29:00 +00004834 // Add initializers for any closure decl refs.
4835 if (BlockDeclRefs.size()) {
Steve Naroffe2514232008-10-29 21:23:59 +00004836 Expr *Exp;
Steve Narofff4b992a2008-10-28 20:29:00 +00004837 // Output all "by copy" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00004838 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00004839 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004840 if (isObjCType((*I)->getType())) {
Steve Naroffe2514232008-10-29 21:23:59 +00004841 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner86d7d912008-11-24 03:54:41 +00004842 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004843 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroffa5c0db82008-12-11 21:05:33 +00004844 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Chris Lattner86d7d912008-11-24 03:54:41 +00004845 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004846 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
John McCall97513962010-01-15 18:39:57 +00004847 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4848 CastExpr::CK_Unknown, Arg);
Steve Narofff4b992a2008-10-28 20:29:00 +00004849 } else {
Chris Lattner86d7d912008-11-24 03:54:41 +00004850 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004851 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004852 }
Mike Stump11289f42009-09-09 15:08:12 +00004853 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00004854 }
4855 // Output all "by ref" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00004856 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00004857 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004858 ValueDecl *ND = (*I);
4859 std::string Name(ND->getNameAsString());
4860 std::string RecName;
4861 RewriteByRefString(RecName, Name, ND);
4862 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
4863 + sizeof("struct"));
4864 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
4865 SourceLocation(), II);
4866 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
4867 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
4868
Chris Lattner86d7d912008-11-24 03:54:41 +00004869 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004870 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4871 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00004872 Context->getPointerType(Exp->getType()),
Steve Naroffe2514232008-10-29 21:23:59 +00004873 SourceLocation());
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004874 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CastExpr::CK_Unknown, Exp);
Mike Stump11289f42009-09-09 15:08:12 +00004875 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00004876 }
4877 }
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00004878 if (ImportedBlockDecls.size()) {
4879 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4880 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff30484702009-12-06 21:14:13 +00004881 unsigned IntSize =
4882 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00004883 Expr *FlagExp = new (Context) IntegerLiteral(llvm::APInt(IntSize, flag),
4884 Context->IntTy, SourceLocation());
4885 InitExprs.push_back(FlagExp);
Steve Naroff30484702009-12-06 21:14:13 +00004886 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004887 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4888 FType, SourceLocation());
Ted Kremenek5a201952009-02-07 01:47:29 +00004889 NewRep = new (Context) UnaryOperator(NewRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00004890 Context->getPointerType(NewRep->getType()),
Steve Narofff4b992a2008-10-28 20:29:00 +00004891 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00004892 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CastExpr::CK_Unknown,
4893 NewRep);
Steve Narofff4b992a2008-10-28 20:29:00 +00004894 BlockDeclRefs.clear();
4895 BlockByRefDecls.clear();
4896 BlockByCopyDecls.clear();
4897 ImportedBlockDecls.clear();
4898 return NewRep;
4899}
4900
4901//===----------------------------------------------------------------------===//
4902// Function Body / Expression rewriting
4903//===----------------------------------------------------------------------===//
4904
Steve Naroff4588d0f2008-12-04 16:24:46 +00004905// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
4906// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
4907// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
4908// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
4909// Since the rewriter isn't capable of rewriting rewritten code, it's important
4910// we get this right.
4911void RewriteObjC::CollectPropertySetters(Stmt *S) {
4912 // Perform a bottom up traversal of all children.
4913 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4914 CI != E; ++CI)
4915 if (*CI)
4916 CollectPropertySetters(*CI);
4917
4918 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
4919 if (BinOp->isAssignmentOp()) {
4920 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
4921 PropSetters[PRE] = BinOp;
4922 }
4923 }
4924}
4925
Steve Narofff4b992a2008-10-28 20:29:00 +00004926Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump11289f42009-09-09 15:08:12 +00004927 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00004928 isa<DoStmt>(S) || isa<ForStmt>(S))
4929 Stmts.push_back(S);
4930 else if (isa<ObjCForCollectionStmt>(S)) {
4931 Stmts.push_back(S);
Chris Lattnerb71980f2010-01-09 21:45:57 +00004932 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofff4b992a2008-10-28 20:29:00 +00004933 }
Mike Stump11289f42009-09-09 15:08:12 +00004934
Steve Narofff4b992a2008-10-28 20:29:00 +00004935 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004936
Steve Narofff4b992a2008-10-28 20:29:00 +00004937 // Perform a bottom up rewrite of all children.
4938 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4939 CI != E; ++CI)
4940 if (*CI) {
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00004941 Stmt *newStmt;
4942 Stmt *S = (*CI);
4943 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
4944 Expr *OldBase = IvarRefExpr->getBase();
4945 bool replaced = false;
4946 newStmt = RewriteObjCNestedIvarRefExpr(S, replaced);
4947 if (replaced) {
4948 if (ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(newStmt))
4949 ReplaceStmt(OldBase, IRE->getBase());
4950 else
4951 ReplaceStmt(S, newStmt);
4952 }
4953 }
4954 else
4955 newStmt = RewriteFunctionBodyOrGlobalInitializer(S);
Mike Stump11289f42009-09-09 15:08:12 +00004956 if (newStmt)
Steve Narofff4b992a2008-10-28 20:29:00 +00004957 *CI = newStmt;
4958 }
Mike Stump11289f42009-09-09 15:08:12 +00004959
Steve Narofff4b992a2008-10-28 20:29:00 +00004960 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4961 // Rewrite the block body in place.
4962 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Mike Stump11289f42009-09-09 15:08:12 +00004963
Steve Narofff4b992a2008-10-28 20:29:00 +00004964 // Now we snarf the rewritten text and stash it away for later use.
Ted Kremenekdb2ef372010-01-07 18:00:35 +00004965 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroffd8907b72008-10-29 18:15:37 +00004966 RewrittenBlockExprs[BE] = Str;
Mike Stump11289f42009-09-09 15:08:12 +00004967
Steve Narofff4b992a2008-10-28 20:29:00 +00004968 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
4969 //blockTranscribed->dump();
Steve Naroffd8907b72008-10-29 18:15:37 +00004970 ReplaceStmt(S, blockTranscribed);
Steve Narofff4b992a2008-10-28 20:29:00 +00004971 return blockTranscribed;
4972 }
4973 // Handle specific things.
4974 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4975 return RewriteAtEncode(AtEncode);
Mike Stump11289f42009-09-09 15:08:12 +00004976
Steve Naroff4588d0f2008-12-04 16:24:46 +00004977 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
4978 BinaryOperator *BinOp = PropSetters[PropRefExpr];
4979 if (BinOp) {
4980 // Because the rewriter doesn't allow us to rewrite rewritten code,
4981 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroff08628db2008-12-09 12:56:34 +00004982 DisableReplaceStmt = true;
4983 // Save the source range. Even if we disable the replacement, the
4984 // rewritten node will have been inserted into the tree. If the synthesized
4985 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump11289f42009-09-09 15:08:12 +00004986 // self.errorHandler = handler ? handler :
Steve Naroff08628db2008-12-09 12:56:34 +00004987 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
4988 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroff4588d0f2008-12-04 16:24:46 +00004989 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroff08628db2008-12-09 12:56:34 +00004990 DisableReplaceStmt = false;
Steve Naroff22216db2008-12-04 23:50:32 +00004991 //
4992 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
4993 // we changed the RHS of BinOp, the rewriter would fail (since it needs
4994 // to see the original expression). Consider this example:
4995 //
4996 // Foo *obj1, *obj2;
4997 //
4998 // obj1.i = [obj2 rrrr];
4999 //
5000 // 'BinOp' for the previous expression looks like:
5001 //
5002 // (BinaryOperator 0x231ccf0 'int' '='
5003 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
5004 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
5005 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
5006 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
5007 //
5008 // 'newStmt' represents the rewritten message expression. For example:
5009 //
5010 // (CallExpr 0x231d300 'id':'struct objc_object *'
5011 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
5012 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
5013 // (CStyleCastExpr 0x231d220 'void *'
5014 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
5015 //
5016 // Note that 'newStmt' is passed to RewritePropertySetter so that it
5017 // can be used as the setter argument. ReplaceStmt() will still 'see'
5018 // the original RHS (since we haven't altered BinOp).
5019 //
Mike Stump11289f42009-09-09 15:08:12 +00005020 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff22216db2008-12-04 23:50:32 +00005021 // node. As a result, we now leak the original AST nodes.
5022 //
Steve Naroff08628db2008-12-09 12:56:34 +00005023 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroff4588d0f2008-12-04 16:24:46 +00005024 } else {
5025 return RewritePropertyGetter(PropRefExpr);
Steve Narofff326f402008-12-03 00:56:33 +00005026 }
5027 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005028 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5029 return RewriteAtSelector(AtSelector);
Mike Stump11289f42009-09-09 15:08:12 +00005030
Steve Narofff4b992a2008-10-28 20:29:00 +00005031 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5032 return RewriteObjCStringLiteral(AtString);
Mike Stump11289f42009-09-09 15:08:12 +00005033
Steve Narofff4b992a2008-10-28 20:29:00 +00005034 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00005035#if 0
Steve Narofff4b992a2008-10-28 20:29:00 +00005036 // Before we rewrite it, put the original message expression in a comment.
5037 SourceLocation startLoc = MessExpr->getLocStart();
5038 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00005039
Steve Narofff4b992a2008-10-28 20:29:00 +00005040 const char *startBuf = SM->getCharacterData(startLoc);
5041 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump11289f42009-09-09 15:08:12 +00005042
Steve Narofff4b992a2008-10-28 20:29:00 +00005043 std::string messString;
5044 messString += "// ";
5045 messString.append(startBuf, endBuf-startBuf+1);
5046 messString += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00005047
5048 // FIXME: Missing definition of
Steve Narofff4b992a2008-10-28 20:29:00 +00005049 // InsertText(clang::SourceLocation, char const*, unsigned int).
5050 // InsertText(startLoc, messString.c_str(), messString.size());
5051 // Tried this, but it didn't work either...
5052 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroff4588d0f2008-12-04 16:24:46 +00005053#endif
Steve Narofff4b992a2008-10-28 20:29:00 +00005054 return RewriteMessageExpr(MessExpr);
5055 }
Mike Stump11289f42009-09-09 15:08:12 +00005056
Steve Narofff4b992a2008-10-28 20:29:00 +00005057 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5058 return RewriteObjCTryStmt(StmtTry);
5059
5060 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5061 return RewriteObjCSynchronizedStmt(StmtTry);
5062
5063 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5064 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump11289f42009-09-09 15:08:12 +00005065
Steve Narofff4b992a2008-10-28 20:29:00 +00005066 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5067 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump11289f42009-09-09 15:08:12 +00005068
5069 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofff4b992a2008-10-28 20:29:00 +00005070 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump11289f42009-09-09 15:08:12 +00005071 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofff4b992a2008-10-28 20:29:00 +00005072 OrigStmtRange.getEnd());
5073 if (BreakStmt *StmtBreakStmt =
5074 dyn_cast<BreakStmt>(S))
5075 return RewriteBreakStmt(StmtBreakStmt);
5076 if (ContinueStmt *StmtContinueStmt =
5077 dyn_cast<ContinueStmt>(S))
5078 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump11289f42009-09-09 15:08:12 +00005079
5080 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofff4b992a2008-10-28 20:29:00 +00005081 // and cast exprs.
5082 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5083 // FIXME: What we're doing here is modifying the type-specifier that
5084 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump11289f42009-09-09 15:08:12 +00005085 // a separate type-specifier that we can rewrite.
Steve Naroffe70a52a2009-12-05 15:55:59 +00005086 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5087 // the context of an ObjCForCollectionStmt. For example:
5088 // NSArray *someArray;
5089 // for (id <FooProtocol> index in someArray) ;
5090 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5091 // and it depends on the original text locations/positions.
Benjamin Krameracc5fa12009-12-05 22:16:51 +00005092 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
Steve Naroffe70a52a2009-12-05 15:55:59 +00005093 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump11289f42009-09-09 15:08:12 +00005094
Steve Narofff4b992a2008-10-28 20:29:00 +00005095 // Blocks rewrite rules.
5096 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5097 DI != DE; ++DI) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +00005098 Decl *SD = *DI;
Steve Narofff4b992a2008-10-28 20:29:00 +00005099 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005100 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005101 RewriteBlockPointerDecl(ND);
Mike Stump11289f42009-09-09 15:08:12 +00005102 else if (ND->getType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005103 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00005104 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005105 if (VD->hasAttr<BlocksAttr>()) {
5106 static unsigned uniqueByrefDeclCount = 0;
5107 assert(!BlockByRefDeclNo.count(ND) &&
5108 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5109 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005110 RewriteByRefVar(VD);
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005111 }
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00005112 else
5113 RewriteTypeOfDecl(VD);
5114 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005115 }
5116 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005117 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005118 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00005119 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005120 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5121 }
5122 }
5123 }
Mike Stump11289f42009-09-09 15:08:12 +00005124
Steve Narofff4b992a2008-10-28 20:29:00 +00005125 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5126 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump11289f42009-09-09 15:08:12 +00005127
5128 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00005129 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5130 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump11289f42009-09-09 15:08:12 +00005131 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5132 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005133 && "Statement stack mismatch");
5134 Stmts.pop_back();
5135 }
5136 // Handle blocks rewriting.
5137 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
5138 if (BDRE->isByRef())
Steve Naroffd9803712009-04-29 16:37:50 +00005139 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofff4b992a2008-10-28 20:29:00 +00005140 }
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005141 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5142 ValueDecl *VD = DRE->getDecl();
5143 if (VD->hasAttr<BlocksAttr>())
5144 return RewriteBlockDeclRefExpr(DRE);
5145 }
5146
Steve Narofff4b992a2008-10-28 20:29:00 +00005147 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroff350b6652008-10-30 10:07:53 +00005148 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00005149 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroff350b6652008-10-30 10:07:53 +00005150 ReplaceStmt(S, BlockCall);
5151 return BlockCall;
5152 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005153 }
Steve Naroffc989a7b2008-11-03 23:29:32 +00005154 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005155 RewriteCastExpr(CE);
5156 }
5157#if 0
5158 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Ted Kremenek5a201952009-02-07 01:47:29 +00005159 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00005160 // Get the new text.
5161 std::string SStr;
5162 llvm::raw_string_ostream Buf(SStr);
Eli Friedman0905f142009-05-30 05:19:26 +00005163 Replacement->printPretty(Buf, *Context);
Steve Narofff4b992a2008-10-28 20:29:00 +00005164 const std::string &Str = Buf.str();
5165
5166 printf("CAST = %s\n", &Str[0]);
5167 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5168 delete S;
5169 return Replacement;
5170 }
5171#endif
5172 // Return this stmt unmodified.
5173 return S;
5174}
5175
Steve Naroffe70a52a2009-12-05 15:55:59 +00005176void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
5177 for (RecordDecl::field_iterator i = RD->field_begin(),
5178 e = RD->field_end(); i != e; ++i) {
5179 FieldDecl *FD = *i;
5180 if (isTopLevelBlockPointerType(FD->getType()))
5181 RewriteBlockPointerDecl(FD);
5182 if (FD->getType()->isObjCQualifiedIdType() ||
5183 FD->getType()->isObjCQualifiedInterfaceType())
5184 RewriteObjCQualifiedInterfaceTypes(FD);
5185 }
5186}
5187
Steve Narofff4b992a2008-10-28 20:29:00 +00005188/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5189/// main file of the input.
5190void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5191 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffb1368882008-12-17 00:20:22 +00005192 if (FD->isOverloadedOperator())
5193 return;
Mike Stump11289f42009-09-09 15:08:12 +00005194
Steve Narofff4b992a2008-10-28 20:29:00 +00005195 // Since function prototypes don't have ParmDecl's, we check the function
5196 // prototype. This enables us to rewrite function declarations and
5197 // definitions using the same code.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005198 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005199
Sebastian Redla7b98a72009-04-26 20:35:05 +00005200 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00005201 if (CompoundStmt *Body = FD->getCompoundBody()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005202 CurFunctionDef = FD;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00005203 CurFunctionDeclToDeclareForBlock = FD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005204 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005205 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00005206 Body =
5207 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5208 FD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005209 CurrentBody = 0;
5210 if (PropParentMap) {
5211 delete PropParentMap;
5212 PropParentMap = 0;
5213 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005214 // This synthesizes and inserts the block "impl" struct, invoke function,
5215 // and any copy/dispose helper functions.
5216 InsertBlockLiteralsWithinFunction(FD);
5217 CurFunctionDef = 0;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00005218 CurFunctionDeclToDeclareForBlock = 0;
Mike Stump11289f42009-09-09 15:08:12 +00005219 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005220 return;
5221 }
5222 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00005223 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005224 CurMethodDef = MD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005225 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005226 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00005227 Body =
5228 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5229 MD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005230 CurrentBody = 0;
5231 if (PropParentMap) {
5232 delete PropParentMap;
5233 PropParentMap = 0;
5234 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005235 InsertBlockLiteralsWithinMethod(MD);
5236 CurMethodDef = 0;
5237 }
5238 }
5239 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5240 ClassImplementation.push_back(CI);
5241 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5242 CategoryImplementation.push_back(CI);
5243 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
5244 RewriteForwardClassDecl(CD);
5245 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5246 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroffa5c0db82008-12-11 21:05:33 +00005247 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005248 RewriteBlockPointerDecl(VD);
Steve Naroffd8907b72008-10-29 18:15:37 +00005249 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005250 CheckFunctionPointerDecl(VD->getType(), VD);
5251 if (VD->getInit()) {
Steve Naroffc989a7b2008-11-03 23:29:32 +00005252 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005253 RewriteCastExpr(CE);
5254 }
5255 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00005256 } else if (VD->getType()->isRecordType()) {
5257 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5258 if (RD->isDefinition())
5259 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005260 }
Steve Naroffd8907b72008-10-29 18:15:37 +00005261 if (VD->getInit()) {
5262 GlobalVarDecl = VD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005263 CollectPropertySetters(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00005264 CurrentBody = VD->getInit();
Steve Naroffd8907b72008-10-29 18:15:37 +00005265 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00005266 CurrentBody = 0;
5267 if (PropParentMap) {
5268 delete PropParentMap;
5269 PropParentMap = 0;
5270 }
Mike Stump11289f42009-09-09 15:08:12 +00005271 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner86d7d912008-11-24 03:54:41 +00005272 VD->getNameAsCString());
Steve Naroffd8907b72008-10-29 18:15:37 +00005273 GlobalVarDecl = 0;
5274
5275 // This is needed for blocks.
Steve Naroffc989a7b2008-11-03 23:29:32 +00005276 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroffd8907b72008-10-29 18:15:37 +00005277 RewriteCastExpr(CE);
5278 }
5279 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005280 return;
5281 }
5282 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005283 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005284 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00005285 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005286 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
Steve Naroffe70a52a2009-12-05 15:55:59 +00005287 else if (TD->getUnderlyingType()->isRecordType()) {
5288 RecordDecl *RD = TD->getUnderlyingType()->getAs<RecordType>()->getDecl();
5289 if (RD->isDefinition())
5290 RewriteRecordBody(RD);
5291 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005292 return;
5293 }
5294 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroffe70a52a2009-12-05 15:55:59 +00005295 if (RD->isDefinition())
5296 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005297 return;
5298 }
5299 // Nothing yet.
5300}
5301
Chris Lattnercf169832009-03-28 04:11:33 +00005302void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005303 if (Diags.hasErrorOccurred())
5304 return;
Mike Stump11289f42009-09-09 15:08:12 +00005305
Steve Narofff4b992a2008-10-28 20:29:00 +00005306 RewriteInclude();
Mike Stump11289f42009-09-09 15:08:12 +00005307
Steve Naroffd9803712009-04-29 16:37:50 +00005308 // Here's a great place to add any extra declarations that may be needed.
5309 // Write out meta data for each @protocol(<expr>).
Mike Stump11289f42009-09-09 15:08:12 +00005310 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00005311 E = ProtocolExprDecls.end(); I != E; ++I)
5312 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5313
Mike Stump11289f42009-09-09 15:08:12 +00005314 InsertText(SM->getLocForStartOfFile(MainFileID),
Steve Narofff4b992a2008-10-28 20:29:00 +00005315 Preamble.c_str(), Preamble.size(), false);
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005316 if (ClassImplementation.size() || CategoryImplementation.size())
5317 RewriteImplementations();
Steve Naroffd9803712009-04-29 16:37:50 +00005318
Steve Narofff4b992a2008-10-28 20:29:00 +00005319 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5320 // we are done.
Mike Stump11289f42009-09-09 15:08:12 +00005321 if (const RewriteBuffer *RewriteBuf =
Steve Narofff4b992a2008-10-28 20:29:00 +00005322 Rewrite.getRewriteBufferFor(MainFileID)) {
5323 //printf("Changed:\n");
5324 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5325 } else {
5326 fprintf(stderr, "No changes\n");
5327 }
Steve Narofff8cfd162008-11-13 20:07:04 +00005328
Steve Naroffd9803712009-04-29 16:37:50 +00005329 if (ClassImplementation.size() || CategoryImplementation.size() ||
5330 ProtocolExprDecls.size()) {
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005331 // Rewrite Objective-c meta data*
5332 std::string ResultStr;
5333 SynthesizeMetaDataIntoBuffer(ResultStr);
5334 // Emit metadata.
5335 *OutFile << ResultStr;
5336 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005337 OutFile->flush();
5338}
5339