blob: d2fe599c76378960144754594502afd7afd27b60 [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.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +0000127 llvm::SmallVector<ValueDecl *, 8> BlockByCopyDecls;
128 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
129 llvm::SmallVector<ValueDecl *, 8> BlockByRefDecls;
130 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +0000131 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000132 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
133
134 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
135
Steve Naroff4588d0f2008-12-04 16:24:46 +0000136 // This maps a property to it's assignment statement.
137 llvm::DenseMap<ObjCPropertyRefExpr *, BinaryOperator *> PropSetters;
Steve Naroff1042ff32008-12-08 16:43:47 +0000138 // This maps a property to it's synthesied message expression.
139 // This allows us to rewrite chained getters (e.g. o.a.b.c).
140 llvm::DenseMap<ObjCPropertyRefExpr *, Stmt *> PropGetters;
Mike Stump11289f42009-09-09 15:08:12 +0000141
Steve Naroff22216db2008-12-04 23:50:32 +0000142 // This maps an original source AST to it's rewritten form. This allows
143 // us to avoid rewriting the same node twice (which is very uncommon).
144 // This is needed to support some of the exotic property rewriting.
145 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Narofff326f402008-12-03 00:56:33 +0000146
Steve Naroff677ab3a2008-10-27 17:20:55 +0000147 FunctionDecl *CurFunctionDef;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000148 FunctionDecl *CurFunctionDeclToDeclareForBlock;
Steve Naroffd8907b72008-10-29 18:15:37 +0000149 VarDecl *GlobalVarDecl;
Mike Stump11289f42009-09-09 15:08:12 +0000150
Steve Naroff08628db2008-12-09 12:56:34 +0000151 bool DisableReplaceStmt;
Mike Stump11289f42009-09-09 15:08:12 +0000152
Fariborz Jahanian93191af2007-10-18 19:23:00 +0000153 static const int OBJC_ABI_VERSION =7 ;
Chris Lattnere99c8322007-10-11 00:43:27 +0000154 public:
Ted Kremenek380df932008-05-31 20:11:04 +0000155 virtual void Initialize(ASTContext &context);
156
Chris Lattner3c799d72007-10-24 17:06:59 +0000157 // Top Level Driver code.
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000158 virtual void HandleTopLevelDecl(DeclGroupRef D) {
159 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I)
160 HandleTopLevelSingleDecl(*I);
161 }
162 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000163 void HandleDeclInMainFile(Decl *D);
Eli Friedman94cf21e2009-05-18 22:20:00 +0000164 RewriteObjC(std::string inFile, llvm::raw_ostream *OS,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000165 Diagnostic &D, const LangOptions &LOpts,
166 bool silenceMacroWarn);
Ted Kremenek6231e7e2008-08-08 04:15:52 +0000167
168 ~RewriteObjC() {}
Mike Stump11289f42009-09-09 15:08:12 +0000169
Chris Lattnercf169832009-03-28 04:11:33 +0000170 virtual void HandleTranslationUnit(ASTContext &C);
Mike Stump11289f42009-09-09 15:08:12 +0000171
Fariborz Jahaniana7e1dcd2010-02-05 16:43:40 +0000172 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff22216db2008-12-04 23:50:32 +0000173 Stmt *ReplacingStmt = ReplacedNodes[Old];
Mike Stump11289f42009-09-09 15:08:12 +0000174
Steve Naroff22216db2008-12-04 23:50:32 +0000175 if (ReplacingStmt)
176 return; // We can't rewrite the same node twice.
Chris Lattner2e0d2602008-01-31 19:37:57 +0000177
Steve Naroff08628db2008-12-09 12:56:34 +0000178 if (DisableReplaceStmt)
179 return; // Used when rewriting the assignment of a property setter.
180
Steve Naroff22216db2008-12-04 23:50:32 +0000181 // If replacement succeeded or warning disabled return with no warning.
Fariborz Jahaniana7e1dcd2010-02-05 16:43:40 +0000182 if (!Rewrite.ReplaceStmt(Old, New)) {
Steve Naroff22216db2008-12-04 23:50:32 +0000183 ReplacedNodes[Old] = New;
184 return;
185 }
186 if (SilenceRewriteMacroWarning)
187 return;
Chris Lattner8488c822008-11-18 07:04:44 +0000188 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
189 << Old->getSourceRange();
Chris Lattner2e0d2602008-01-31 19:37:57 +0000190 }
Steve Naroff08628db2008-12-09 12:56:34 +0000191
192 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
193 // Measaure the old text.
194 int Size = Rewrite.getRangeSize(SrcRange);
195 if (Size == -1) {
196 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
197 << Old->getSourceRange();
198 return;
199 }
200 // Get the new text.
201 std::string SStr;
202 llvm::raw_string_ostream S(SStr);
Chris Lattnerc61089a2009-06-30 01:26:17 +0000203 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
Steve Naroff08628db2008-12-09 12:56:34 +0000204 const std::string &Str = S.str();
205
206 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbardec484a2009-08-19 19:10:30 +0000207 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroff08628db2008-12-09 12:56:34 +0000208 ReplacedNodes[Old] = New;
209 return;
210 }
211 if (SilenceRewriteMacroWarning)
212 return;
213 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
214 << Old->getSourceRange();
215 }
216
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000217 void InsertText(SourceLocation Loc, llvm::StringRef Str,
Steve Naroff00a31762008-03-27 22:29:16 +0000218 bool InsertAfter = true) {
Chris Lattner9cc55f52008-01-31 19:51:04 +0000219 // If insertion succeeded or warning disabled return with no warning.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000220 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
Chris Lattner1780a852008-01-31 19:42:41 +0000221 SilenceRewriteMacroWarning)
222 return;
Mike Stump11289f42009-09-09 15:08:12 +0000223
Chris Lattner1780a852008-01-31 19:42:41 +0000224 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
225 }
Mike Stump11289f42009-09-09 15:08:12 +0000226
Chris Lattner9cc55f52008-01-31 19:51:04 +0000227 void RemoveText(SourceLocation Loc, unsigned StrLen) {
228 // If removal succeeded or warning disabled return with no warning.
229 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
230 return;
Mike Stump11289f42009-09-09 15:08:12 +0000231
Chris Lattner9cc55f52008-01-31 19:51:04 +0000232 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
233 }
Chris Lattner3c799d72007-10-24 17:06:59 +0000234
Chris Lattner9cc55f52008-01-31 19:51:04 +0000235 void ReplaceText(SourceLocation Start, unsigned OrigLength,
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000236 llvm::StringRef Str) {
Chris Lattner9cc55f52008-01-31 19:51:04 +0000237 // If removal succeeded or warning disabled return with no warning.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000238 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
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");
Mike Stump11289f42009-09-09 15:08:12 +0000690
Fariborz Jahanian137d6932008-01-19 01:03:17 +0000691 // Loop over the whole file, looking for includes.
Fariborz Jahanian80258362008-01-19 00:30:35 +0000692 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
693 if (*BufPtr == '#') {
694 if (++BufPtr == MainBufEnd)
695 return;
696 while (*BufPtr == ' ' || *BufPtr == '\t')
697 if (++BufPtr == MainBufEnd)
698 return;
699 if (!strncmp(BufPtr, "import", ImportLen)) {
700 // replace import with include
Mike Stump11289f42009-09-09 15:08:12 +0000701 SourceLocation ImportLoc =
Fariborz Jahanian80258362008-01-19 00:30:35 +0000702 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000703 ReplaceText(ImportLoc, ImportLen, "include");
Fariborz Jahanian80258362008-01-19 00:30:35 +0000704 BufPtr += ImportLen;
705 }
706 }
707 }
Chris Lattner0bd1c972007-10-16 21:07:07 +0000708}
709
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000710void RewriteObjC::RewriteTabs() {
Chris Lattner3c799d72007-10-24 17:06:59 +0000711 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
712 const char *MainBufStart = MainBuf.first;
713 const char *MainBufEnd = MainBuf.second;
Mike Stump11289f42009-09-09 15:08:12 +0000714
Chris Lattner3c799d72007-10-24 17:06:59 +0000715 // Loop over the whole file, looking for tabs.
716 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
717 if (*BufPtr != '\t')
718 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000719
Chris Lattner3c799d72007-10-24 17:06:59 +0000720 // Okay, we found a tab. This tab will turn into at least one character,
721 // but it depends on which 'virtual column' it is in. Compute that now.
722 unsigned VCol = 0;
723 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
724 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
725 ++VCol;
Mike Stump11289f42009-09-09 15:08:12 +0000726
Chris Lattner3c799d72007-10-24 17:06:59 +0000727 // Okay, now that we know the virtual column, we know how many spaces to
728 // insert. We assume 8-character tab-stops.
729 unsigned Spaces = 8-(VCol & 7);
Mike Stump11289f42009-09-09 15:08:12 +0000730
Chris Lattner3c799d72007-10-24 17:06:59 +0000731 // Get the location of the tab.
Chris Lattnerd32480d2009-01-17 06:22:33 +0000732 SourceLocation TabLoc = SM->getLocForStartOfFile(MainFileID);
733 TabLoc = TabLoc.getFileLocWithOffset(BufPtr-MainBufStart);
Mike Stump11289f42009-09-09 15:08:12 +0000734
Chris Lattner3c799d72007-10-24 17:06:59 +0000735 // Rewrite the single tab character into a sequence of spaces.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000736 ReplaceText(TabLoc, 1, llvm::StringRef(" ", Spaces));
Chris Lattner3c799d72007-10-24 17:06:59 +0000737 }
Chris Lattner16a0de42007-10-11 18:38:32 +0000738}
739
Steve Naroff9af94912008-12-02 15:48:25 +0000740static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
741 ObjCIvarDecl *OID) {
742 std::string S;
743 S = "((struct ";
744 S += ClassDecl->getIdentifier()->getName();
745 S += "_IMPL *)self)->";
Daniel Dunbar70e7ead2009-10-18 20:26:27 +0000746 S += OID->getName();
Steve Naroff9af94912008-12-02 15:48:25 +0000747 return S;
748}
749
Steve Naroffc038b3a2008-12-02 17:36:43 +0000750void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
751 ObjCImplementationDecl *IMD,
752 ObjCCategoryImplDecl *CID) {
Steve Naroffe1908e32008-12-01 20:33:01 +0000753 SourceLocation startLoc = PID->getLocStart();
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000754 InsertText(startLoc, "// ");
Steve Naroff9af94912008-12-02 15:48:25 +0000755 const char *startBuf = SM->getCharacterData(startLoc);
756 assert((*startBuf == '@') && "bogus @synthesize location");
757 const char *semiBuf = strchr(startBuf, ';');
758 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek5a201952009-02-07 01:47:29 +0000759 SourceLocation onePastSemiLoc =
760 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroff9af94912008-12-02 15:48:25 +0000761
762 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
763 return; // FIXME: is this correct?
Mike Stump11289f42009-09-09 15:08:12 +0000764
Steve Naroff9af94912008-12-02 15:48:25 +0000765 // Generate the 'getter' function.
Steve Naroff9af94912008-12-02 15:48:25 +0000766 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroff9af94912008-12-02 15:48:25 +0000767 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroff9af94912008-12-02 15:48:25 +0000768 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000769
Steve Naroff003d00e2008-12-02 16:05:55 +0000770 if (!OID)
771 return;
Mike Stump11289f42009-09-09 15:08:12 +0000772
Steve Naroff003d00e2008-12-02 16:05:55 +0000773 std::string Getr;
774 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
775 Getr += "{ ";
776 // Synthesize an explicit cast to gain access to the ivar.
Mike Stump11289f42009-09-09 15:08:12 +0000777 // FIXME: deal with code generation implications for various property
778 // attributes (copy, retain, nonatomic).
Steve Naroff06297042008-12-02 17:54:50 +0000779 // See objc-act.c:objc_synthesize_new_getter() for details.
Steve Naroff003d00e2008-12-02 16:05:55 +0000780 Getr += "return " + getIvarAccessString(ClassDecl, OID);
781 Getr += "; }";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000782 InsertText(onePastSemiLoc, Getr);
Steve Naroff9af94912008-12-02 15:48:25 +0000783 if (PD->isReadOnly())
784 return;
Mike Stump11289f42009-09-09 15:08:12 +0000785
Steve Naroff9af94912008-12-02 15:48:25 +0000786 // Generate the 'setter' function.
787 std::string Setr;
788 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroff9af94912008-12-02 15:48:25 +0000789 Setr += "{ ";
Steve Naroff003d00e2008-12-02 16:05:55 +0000790 // Synthesize an explicit cast to initialize the ivar.
Mike Stump11289f42009-09-09 15:08:12 +0000791 // FIXME: deal with code generation implications for various property
792 // attributes (copy, retain, nonatomic).
Steve Narofff326f402008-12-03 00:56:33 +0000793 // See objc-act.c:objc_synthesize_new_setter() for details.
Steve Naroff003d00e2008-12-02 16:05:55 +0000794 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000795 Setr += PD->getNameAsCString();
Steve Naroff003d00e2008-12-02 16:05:55 +0000796 Setr += "; }";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000797 InsertText(onePastSemiLoc, Setr);
Steve Naroffe1908e32008-12-01 20:33:01 +0000798}
Chris Lattner16a0de42007-10-11 18:38:32 +0000799
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000800void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattner3c799d72007-10-24 17:06:59 +0000801 // Get the start location and compute the semi location.
802 SourceLocation startLoc = ClassDecl->getLocation();
803 const char *startBuf = SM->getCharacterData(startLoc);
804 const char *semiPtr = strchr(startBuf, ';');
Mike Stump11289f42009-09-09 15:08:12 +0000805
Chris Lattner3c799d72007-10-24 17:06:59 +0000806 // Translate to typedef's that forward reference structs with the same name
807 // as the class. As a convenience, we include the original declaration
808 // as a comment.
809 std::string typedefString;
Fariborz Jahanian1c2cb6d2010-01-11 22:48:40 +0000810 typedefString += "// @class ";
811 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
812 I != E; ++I) {
813 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
814 typedefString += ForwardDecl->getNameAsString();
815 if (I+1 != E)
816 typedefString += ", ";
817 else
818 typedefString += ";\n";
819 }
820
Chris Lattner9ee23b72009-02-20 18:04:31 +0000821 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
822 I != E; ++I) {
Ted Kremenek9b124e12009-11-18 00:28:11 +0000823 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
Steve Naroff1b232132007-11-09 12:50:28 +0000824 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000825 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000826 typedefString += "\n";
827 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000828 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000829 typedefString += "\n";
Steve Naroff98eb8d12007-11-05 14:36:37 +0000830 typedefString += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000831 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000832 typedefString += ";\n#endif\n";
Steve Naroff574440f2007-10-24 22:48:43 +0000833 }
Mike Stump11289f42009-09-09 15:08:12 +0000834
Steve Naroff574440f2007-10-24 22:48:43 +0000835 // Replace the @class with typedefs corresponding to the classes.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000836 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
Chris Lattner3c799d72007-10-24 17:06:59 +0000837}
838
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000839void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahanianda8ec2b2010-01-21 17:36:00 +0000840 // When method is a synthesized one, such as a getter/setter there is
841 // nothing to rewrite.
842 if (Method->isSynthesized())
843 return;
Steve Naroff3ce37a62007-12-14 23:37:57 +0000844 SourceLocation LocStart = Method->getLocStart();
845 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000846
Chris Lattner88ea93e2009-02-04 01:06:56 +0000847 if (SM->getInstantiationLineNumber(LocEnd) >
848 SM->getInstantiationLineNumber(LocStart)) {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000849 InsertText(LocStart, "#if 0\n");
850 ReplaceText(LocEnd, 1, ";\n#endif\n");
Steve Naroff3ce37a62007-12-14 23:37:57 +0000851 } else {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000852 InsertText(LocStart, "// ");
Steve Naroff5448cf62007-10-30 13:30:57 +0000853 }
854}
855
Mike Stump11289f42009-09-09 15:08:12 +0000856void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahanianda8ec2b2010-01-21 17:36:00 +0000857 SourceLocation Loc = prop->getAtLoc();
Mike Stump11289f42009-09-09 15:08:12 +0000858
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000859 ReplaceText(Loc, 0, "// ");
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000860 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahaniane8a30162007-11-07 00:09:37 +0000861}
862
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000863void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000864 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000865
Steve Naroff5448cf62007-10-30 13:30:57 +0000866 // FIXME: handle category headers that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000867 ReplaceText(LocStart, 0, "// ");
Mike Stump11289f42009-09-09 15:08:12 +0000868
Fariborz Jahanian68ebe632010-02-10 01:15:09 +0000869 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
870 E = CatDecl->prop_end(); I != E; ++I)
871 RewriteProperty(*I);
872
Mike Stump11289f42009-09-09 15:08:12 +0000873 for (ObjCCategoryDecl::instmeth_iterator
874 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000875 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000876 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +0000877 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000878 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000879 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000880 RewriteMethodDeclaration(*I);
881
Steve Naroff5448cf62007-10-30 13:30:57 +0000882 // Lastly, comment out the @end.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000883 ReplaceText(CatDecl->getAtEndRange().getBegin(), 0, "// ");
Steve Naroff5448cf62007-10-30 13:30:57 +0000884}
885
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000886void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000887 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Mike Stump11289f42009-09-09 15:08:12 +0000888
Steve Narofff921385f2007-10-30 16:42:30 +0000889 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000890
Steve Narofff921385f2007-10-30 16:42:30 +0000891 // FIXME: handle protocol headers that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000892 ReplaceText(LocStart, 0, "// ");
Mike Stump11289f42009-09-09 15:08:12 +0000893
894 for (ObjCProtocolDecl::instmeth_iterator
895 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000896 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000897 RewriteMethodDeclaration(*I);
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000898 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000899 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000900 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000901 RewriteMethodDeclaration(*I);
902
Steve Narofff921385f2007-10-30 16:42:30 +0000903 // Lastly, comment out the @end.
Ted Kremenekc7c64312010-01-07 01:20:12 +0000904 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000905 ReplaceText(LocEnd, 0, "// ");
Steve Naroffa509f042007-11-14 15:03:57 +0000906
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000907 // Must comment out @optional/@required
908 const char *startBuf = SM->getCharacterData(LocStart);
909 const char *endBuf = SM->getCharacterData(LocEnd);
910 for (const char *p = startBuf; p < endBuf; p++) {
911 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
Steve Naroffa509f042007-11-14 15:03:57 +0000912 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000913 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
Mike Stump11289f42009-09-09 15:08:12 +0000914
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000915 }
916 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
Steve Naroffa509f042007-11-14 15:03:57 +0000917 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000918 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
Mike Stump11289f42009-09-09 15:08:12 +0000919
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000920 }
921 }
Steve Narofff921385f2007-10-30 16:42:30 +0000922}
923
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000924void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000925 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffc17b0562007-11-14 03:37:28 +0000926 if (LocStart.isInvalid())
927 assert(false && "Invalid SourceLocation");
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000928 // FIXME: handle forward protocol that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000929 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000930}
931
Mike Stump11289f42009-09-09 15:08:12 +0000932void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000933 std::string &ResultStr) {
Steve Naroff295570a2008-10-30 12:09:33 +0000934 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroffb067bbd2008-07-16 14:40:40 +0000935 const FunctionType *FPRetType = 0;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000936 ResultStr += "\nstatic ";
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000937 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanian24cb52c2007-12-17 21:03:50 +0000938 ResultStr += "id";
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000939 else if (OMD->getResultType()->isFunctionPointerType() ||
940 OMD->getResultType()->isBlockPointerType()) {
Steve Naroffb067bbd2008-07-16 14:40:40 +0000941 // needs special handling, since pointer-to-functions have special
942 // syntax (where a decaration models use).
943 QualType retType = OMD->getResultType();
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000944 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000945 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000946 PointeeTy = PT->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000947 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000948 PointeeTy = BPT->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +0000949 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000950 ResultStr += FPRetType->getResultType().getAsString();
951 ResultStr += "(*";
Steve Naroffb067bbd2008-07-16 14:40:40 +0000952 }
953 } else
Fariborz Jahanian24cb52c2007-12-17 21:03:50 +0000954 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian7262fca2008-01-10 01:39:52 +0000955 ResultStr += " ";
Mike Stump11289f42009-09-09 15:08:12 +0000956
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000957 // Unique method name
Fariborz Jahanian56338352007-11-13 21:02:00 +0000958 std::string NameStr;
Mike Stump11289f42009-09-09 15:08:12 +0000959
Douglas Gregorffca3a22009-01-09 17:18:27 +0000960 if (OMD->isInstanceMethod())
Fariborz Jahanian56338352007-11-13 21:02:00 +0000961 NameStr += "_I_";
962 else
963 NameStr += "_C_";
Mike Stump11289f42009-09-09 15:08:12 +0000964
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000965 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +0000966 NameStr += "_";
Mike Stump11289f42009-09-09 15:08:12 +0000967
968 if (ObjCCategoryImplDecl *CID =
Steve Naroff11b387f2009-01-08 19:41:02 +0000969 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000970 NameStr += CID->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +0000971 NameStr += "_";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000972 }
Mike Stump11289f42009-09-09 15:08:12 +0000973 // Append selector names, replacing ':' with '_'
Chris Lattnere4b95692008-11-24 03:33:13 +0000974 {
975 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000976 int len = selString.size();
977 for (int i = 0; i < len; i++)
978 if (selString[i] == ':')
979 selString[i] = '_';
Fariborz Jahanian56338352007-11-13 21:02:00 +0000980 NameStr += selString;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000981 }
Fariborz Jahanian56338352007-11-13 21:02:00 +0000982 // Remember this name for metadata emission
983 MethodInternalNames[OMD] = NameStr;
984 ResultStr += NameStr;
Mike Stump11289f42009-09-09 15:08:12 +0000985
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000986 // Rewrite arguments
987 ResultStr += "(";
Mike Stump11289f42009-09-09 15:08:12 +0000988
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000989 // invisible arguments
Douglas Gregorffca3a22009-01-09 17:18:27 +0000990 if (OMD->isInstanceMethod()) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000991 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000992 selfTy = Context->getPointerType(selfTy);
Steve Naroffdc5b6b22008-03-12 00:25:36 +0000993 if (!LangOpts.Microsoft) {
994 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
995 ResultStr += "struct ";
996 }
997 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000998 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +0000999 ResultStr += " *";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001000 }
1001 else
Steve Naroffd9803712009-04-29 16:37:50 +00001002 ResultStr += Context->getObjCClassType().getAsString();
Mike Stump11289f42009-09-09 15:08:12 +00001003
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001004 ResultStr += " self, ";
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001005 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001006 ResultStr += " _cmd";
Mike Stump11289f42009-09-09 15:08:12 +00001007
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001008 // Method arguments.
Chris Lattnera4997152009-02-20 18:43:26 +00001009 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1010 E = OMD->param_end(); PI != E; ++PI) {
1011 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001012 ResultStr += ", ";
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001013 if (PDecl->getType()->isObjCQualifiedIdType()) {
1014 ResultStr += "id ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001015 ResultStr += PDecl->getNameAsString();
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001016 } else {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001017 std::string Name = PDecl->getNameAsString();
Steve Naroffa5c0db82008-12-11 21:05:33 +00001018 if (isTopLevelBlockPointerType(PDecl->getType())) {
Steve Naroff44df6a22008-10-30 14:45:29 +00001019 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001020 const BlockPointerType *BPT = PDecl->getType()->getAs<BlockPointerType>();
Douglas Gregor7de59662009-05-29 20:38:28 +00001021 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name,
1022 Context->PrintingPolicy);
Steve Naroff44df6a22008-10-30 14:45:29 +00001023 } else
Douglas Gregor7de59662009-05-29 20:38:28 +00001024 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001025 ResultStr += Name;
1026 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001027 }
Fariborz Jahanianeab81cd2008-01-21 20:14:23 +00001028 if (OMD->isVariadic())
1029 ResultStr += ", ...";
Fariborz Jahanian7262fca2008-01-10 01:39:52 +00001030 ResultStr += ") ";
Mike Stump11289f42009-09-09 15:08:12 +00001031
Steve Naroffb067bbd2008-07-16 14:40:40 +00001032 if (FPRetType) {
1033 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump11289f42009-09-09 15:08:12 +00001034
Steve Naroffb067bbd2008-07-16 14:40:40 +00001035 // Now, emit the argument types (if any).
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001036 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroffb067bbd2008-07-16 14:40:40 +00001037 ResultStr += "(";
1038 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1039 if (i) ResultStr += ", ";
1040 std::string ParamStr = FT->getArgType(i).getAsString();
1041 ResultStr += ParamStr;
1042 }
1043 if (FT->isVariadic()) {
1044 if (FT->getNumArgs()) ResultStr += ", ";
1045 ResultStr += "...";
1046 }
1047 ResultStr += ")";
1048 } else {
1049 ResultStr += "()";
1050 }
1051 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001052}
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001053void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001054 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1055 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump11289f42009-09-09 15:08:12 +00001056
Fariborz Jahanian02d964b2010-02-15 21:11:41 +00001057 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
Mike Stump11289f42009-09-09 15:08:12 +00001058
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001059 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001060 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1061 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001062 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001063 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001064 ObjCMethodDecl *OMD = *I;
1065 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001066 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001067 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redla7b98a72009-04-26 20:35:05 +00001068
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001069 const char *startBuf = SM->getCharacterData(LocStart);
1070 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001071 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001072 }
Mike Stump11289f42009-09-09 15:08:12 +00001073
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001074 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001075 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1076 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001077 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001078 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001079 ObjCMethodDecl *OMD = *I;
1080 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001081 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001082 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +00001083
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001084 const char *startBuf = SM->getCharacterData(LocStart);
1085 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001086 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001087 }
Steve Naroffe1908e32008-12-01 20:33:01 +00001088 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001089 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001090 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001091 I != E; ++I) {
Steve Naroffc038b3a2008-12-02 17:36:43 +00001092 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffe1908e32008-12-01 20:33:01 +00001093 }
1094
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001095 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001096}
1097
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001098void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffc5484042007-10-30 02:23:23 +00001099 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001100 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff2f55b982007-11-01 03:35:41 +00001101 // we haven't seen a forward decl - generate a typedef.
Steve Naroff03f27672007-11-14 23:02:56 +00001102 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001103 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001104 ResultStr += "\n";
1105 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001106 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001107 ResultStr += "\n";
Steve Naroffa1e115e2008-03-10 23:16:54 +00001108 ResultStr += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001109 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001110 ResultStr += ";\n#endif\n";
Steve Naroff2f55b982007-11-01 03:35:41 +00001111 // Mark this typedef as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001112 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff2f55b982007-11-01 03:35:41 +00001113 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001114 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump11289f42009-09-09 15:08:12 +00001115
1116 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001117 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff0c0f5ba2009-01-11 01:06:09 +00001118 RewriteProperty(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001119 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001120 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001121 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001122 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001123 for (ObjCInterfaceDecl::classmeth_iterator
1124 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001125 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001126 RewriteMethodDeclaration(*I);
1127
Steve Naroff4cd61ac2007-10-30 03:43:13 +00001128 // Lastly, comment out the @end.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001129 ReplaceText(ClassDecl->getAtEndRange().getBegin(), 0, "// ");
Steve Naroff161a92b2007-10-26 20:53:56 +00001130}
1131
Steve Naroff08628db2008-12-09 12:56:34 +00001132Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1133 SourceRange SrcRange) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00001134 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1135 // This allows us to reuse all the fun and games in SynthMessageExpr().
1136 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1137 ObjCMessageExpr *MsgExpr;
1138 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1139 llvm::SmallVector<Expr *, 1> ExprVec;
1140 ExprVec.push_back(newStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001141
Steve Naroff1042ff32008-12-08 16:43:47 +00001142 Stmt *Receiver = PropRefExpr->getBase();
1143 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1144 if (PRE && PropGetters[PRE]) {
1145 // This allows us to handle chain/nested property getters.
1146 Receiver = PropGetters[PRE];
1147 }
Ted Kremenek2c809302010-02-11 22:41:21 +00001148 MsgExpr = new (Context) ObjCMessageExpr(*Context, dyn_cast<Expr>(Receiver),
Mike Stump11289f42009-09-09 15:08:12 +00001149 PDecl->getSetterName(), PDecl->getType(),
1150 PDecl->getSetterMethodDecl(),
1151 SourceLocation(), SourceLocation(),
Steve Naroff4588d0f2008-12-04 16:24:46 +00001152 &ExprVec[0], 1);
1153 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001154
Steve Naroff4588d0f2008-12-04 16:24:46 +00001155 // Now do the actual rewrite.
Steve Naroff08628db2008-12-09 12:56:34 +00001156 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffdf705772008-12-10 14:53:27 +00001157 //delete BinOp;
Ted Kremenek5a201952009-02-07 01:47:29 +00001158 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1159 // to things that stay around.
1160 Context->Deallocate(MsgExpr);
Steve Naroff4588d0f2008-12-04 16:24:46 +00001161 return ReplacingStmt;
Steve Narofff326f402008-12-03 00:56:33 +00001162}
1163
Steve Naroff4588d0f2008-12-04 16:24:46 +00001164Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Narofff326f402008-12-03 00:56:33 +00001165 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1166 // This allows us to reuse all the fun and games in SynthMessageExpr().
1167 ObjCMessageExpr *MsgExpr;
1168 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
Mike Stump11289f42009-09-09 15:08:12 +00001169
Steve Naroff1042ff32008-12-08 16:43:47 +00001170 Stmt *Receiver = PropRefExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00001171
Steve Naroff1042ff32008-12-08 16:43:47 +00001172 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1173 if (PRE && PropGetters[PRE]) {
1174 // This allows us to handle chain/nested property getters.
1175 Receiver = PropGetters[PRE];
1176 }
Ted Kremenek2c809302010-02-11 22:41:21 +00001177 MsgExpr = new (Context) ObjCMessageExpr(*Context, dyn_cast<Expr>(Receiver),
Mike Stump11289f42009-09-09 15:08:12 +00001178 PDecl->getGetterName(), PDecl->getType(),
1179 PDecl->getGetterMethodDecl(),
1180 SourceLocation(), SourceLocation(),
Steve Narofff326f402008-12-03 00:56:33 +00001181 0, 0);
1182
Steve Naroff22216db2008-12-04 23:50:32 +00001183 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001184
1185 if (!PropParentMap)
1186 PropParentMap = new ParentMap(CurrentBody);
1187
1188 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1189 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1190 // We stash away the ReplacingStmt since actually doing the
1191 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1192 PropGetters[PropRefExpr] = ReplacingStmt;
Ted Kremenek5a201952009-02-07 01:47:29 +00001193 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1194 // to things that stay around.
1195 Context->Deallocate(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001196 return PropRefExpr; // return the original...
1197 } else {
1198 ReplaceStmt(PropRefExpr, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001199 // delete PropRefExpr; elsewhere...
Ted Kremenek5a201952009-02-07 01:47:29 +00001200 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1201 // to things that stay around.
1202 Context->Deallocate(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001203 return ReplacingStmt;
1204 }
Steve Narofff326f402008-12-03 00:56:33 +00001205}
1206
Mike Stump11289f42009-09-09 15:08:12 +00001207Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001208 SourceLocation OrigStart,
1209 bool &replaced) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001210 ObjCIvarDecl *D = IV->getDecl();
Fariborz Jahanian0f3aecf2010-01-07 18:18:32 +00001211 const Expr *BaseExpr = IV->getBase();
Steve Naroff677ab3a2008-10-27 17:20:55 +00001212 if (CurMethodDef) {
Fariborz Jahanianf9e8c2b2010-01-26 18:28:51 +00001213 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001214 ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian0f3aecf2010-01-07 18:18:32 +00001215 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanianf0ed69c2010-01-26 20:37:44 +00001216 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
Steve Naroffb1c02372008-05-08 17:52:16 +00001217 // lookup which class implements the instance variable.
1218 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001219 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001220 clsDeclared);
Steve Naroffb1c02372008-05-08 17:52:16 +00001221 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001222
Steve Naroffb1c02372008-05-08 17:52:16 +00001223 // Synthesize an explicit cast to gain access to the ivar.
1224 std::string RecName = clsDeclared->getIdentifier()->getName();
1225 RecName += "_IMPL";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001226 IdentifierInfo *II = &Context->Idents.get(RecName);
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00001227 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001228 SourceLocation(), II);
Steve Naroffb1c02372008-05-08 17:52:16 +00001229 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1230 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall97513962010-01-15 18:39:57 +00001231 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
1232 CastExpr::CK_Unknown,
1233 IV->getBase());
Steve Naroffb1c02372008-05-08 17:52:16 +00001234 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001235 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1236 IV->getBase()->getLocEnd(),
1237 castExpr);
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001238 replaced = true;
Mike Stump11289f42009-09-09 15:08:12 +00001239 if (IV->isFreeIvar() &&
Steve Naroff677ab3a2008-10-27 17:20:55 +00001240 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001241 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1242 IV->getLocation(),
1243 D->getType());
Steve Naroff22216db2008-12-04 23:50:32 +00001244 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffb1c02372008-05-08 17:52:16 +00001245 return ME;
Steve Naroff05caa482007-11-15 11:33:00 +00001246 }
Fariborz Jahanian81310812010-01-28 01:41:20 +00001247 // Get the new text
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001248 // Cannot delete IV->getBase(), since PE points to it.
1249 // Replace the old base with the cast. This is important when doing
1250 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001251 IV->setBase(PE);
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001252 return IV;
Steve Naroff05caa482007-11-15 11:33:00 +00001253 }
Steve Naroff24840f62008-04-18 21:55:08 +00001254 } else { // we are outside a method.
Steve Naroff29ce4e52008-05-06 23:20:07 +00001255 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump11289f42009-09-09 15:08:12 +00001256
Steve Naroff29ce4e52008-05-06 23:20:07 +00001257 // Explicit ivar refs need to have a cast inserted.
1258 // FIXME: consider sharing some of this code with the code above.
Fariborz Jahanian12e2e862010-01-12 17:31:23 +00001259 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Fariborz Jahanian9146e442010-01-11 17:50:35 +00001260 ObjCInterfaceType *iFaceDecl =
1261 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001262 // lookup which class implements the instance variable.
1263 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001264 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001265 clsDeclared);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001266 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001267
Steve Naroff29ce4e52008-05-06 23:20:07 +00001268 // Synthesize an explicit cast to gain access to the ivar.
1269 std::string RecName = clsDeclared->getIdentifier()->getName();
1270 RecName += "_IMPL";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001271 IdentifierInfo *II = &Context->Idents.get(RecName);
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00001272 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001273 SourceLocation(), II);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001274 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1275 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall97513962010-01-15 18:39:57 +00001276 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
1277 CastExpr::CK_Unknown,
1278 IV->getBase());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001279 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001280 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner34873d22008-05-28 16:38:23 +00001281 IV->getBase()->getLocEnd(), castExpr);
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001282 replaced = true;
Steve Naroff29ce4e52008-05-06 23:20:07 +00001283 // Cannot delete IV->getBase(), since PE points to it.
1284 // Replace the old base with the cast. This is important when doing
1285 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001286 IV->setBase(PE);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001287 return IV;
1288 }
Steve Naroff05caa482007-11-15 11:33:00 +00001289 }
Steve Naroff24840f62008-04-18 21:55:08 +00001290 return IV;
Steve Narofff60782b2007-11-15 02:58:25 +00001291}
1292
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001293Stmt *RewriteObjC::RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced) {
1294 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1295 CI != E; ++CI) {
1296 if (*CI) {
1297 Stmt *newStmt = RewriteObjCNestedIvarRefExpr(*CI, replaced);
1298 if (newStmt)
1299 *CI = newStmt;
1300 }
1301 }
1302 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
1303 SourceRange OrigStmtRange = S->getSourceRange();
1304 Stmt *newStmt = RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin(),
1305 replaced);
1306 return newStmt;
Fariborz Jahanian31433382010-02-05 17:48:10 +00001307 }
1308 if (ObjCMessageExpr *MsgRefExpr = dyn_cast<ObjCMessageExpr>(S)) {
1309 Stmt *newStmt = SynthMessageExpr(MsgRefExpr);
1310 return newStmt;
1311 }
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001312 return S;
1313}
1314
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001315/// SynthCountByEnumWithState - To print:
1316/// ((unsigned int (*)
1317/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001318/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001319/// sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001320/// "countByEnumeratingWithState:objects:count:"),
1321/// &enumState,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001322/// (id *)items, (unsigned int)16)
1323///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001324void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001325 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1326 "id *, unsigned int))(void *)objc_msgSend)";
1327 buf += "\n\t\t";
1328 buf += "((id)l_collection,\n\t\t";
1329 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1330 buf += "\n\t\t";
1331 buf += "&enumState, "
1332 "(id *)items, (unsigned int)16)";
1333}
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001334
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001335/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1336/// statement to exit to its outer synthesized loop.
1337///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001338Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001339 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1340 return S;
1341 // replace break with goto __break_label
1342 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001343
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001344 SourceLocation startLoc = S->getLocStart();
1345 buf = "goto __break_label_";
1346 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001347 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001348
1349 return 0;
1350}
1351
1352/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1353/// statement to continue with its inner synthesized loop.
1354///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001355Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001356 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1357 return S;
1358 // replace continue with goto __continue_label
1359 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001360
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001361 SourceLocation startLoc = S->getLocStart();
1362 buf = "goto __continue_label_";
1363 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001364 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump11289f42009-09-09 15:08:12 +00001365
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001366 return 0;
1367}
1368
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001369/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001370/// It rewrites:
1371/// for ( type elem in collection) { stmts; }
Mike Stump11289f42009-09-09 15:08:12 +00001372
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001373/// Into:
1374/// {
Mike Stump11289f42009-09-09 15:08:12 +00001375/// type elem;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001376/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001377/// id items[16];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001378/// id l_collection = (id)collection;
Mike Stump11289f42009-09-09 15:08:12 +00001379/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001380/// objects:items count:16];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001381/// if (limit) {
1382/// unsigned long startMutations = *enumState.mutationsPtr;
1383/// do {
1384/// unsigned long counter = 0;
1385/// do {
Mike Stump11289f42009-09-09 15:08:12 +00001386/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001387/// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001388/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001389/// stmts;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001390/// __continue_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001391/// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001392/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001393/// objects:items count:16]);
1394/// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001395/// __break_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001396/// }
1397/// else
1398/// elem = nil;
1399/// }
1400///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001401Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattnera779d692008-01-31 05:10:40 +00001402 SourceLocation OrigEnd) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001403 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001404 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001405 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump11289f42009-09-09 15:08:12 +00001406 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001407 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001408
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001409 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001410 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001411 const char *elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001412 std::string elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001413 std::string buf;
1414 buf = "\n{\n\t";
1415 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1416 // type elem;
Chris Lattner529efc72009-03-28 06:33:19 +00001417 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek292b3842008-10-06 22:16:13 +00001418 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001419 if (ElementType->isObjCQualifiedIdType() ||
1420 ElementType->isObjCQualifiedInterfaceType())
1421 // Simply use 'id' for all qualified types.
1422 elementTypeAsString = "id";
1423 else
1424 elementTypeAsString = ElementType.getAsString();
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001425 buf += elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001426 buf += " ";
Chris Lattner86d7d912008-11-24 03:54:41 +00001427 elementName = D->getNameAsCString();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001428 buf += elementName;
1429 buf += ";\n\t";
1430 }
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001431 else {
1432 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner86d7d912008-11-24 03:54:41 +00001433 elementName = DR->getDecl()->getNameAsCString();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001434 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1435 if (VD->getType()->isObjCQualifiedIdType() ||
1436 VD->getType()->isObjCQualifiedInterfaceType())
1437 // Simply use 'id' for all qualified types.
1438 elementTypeAsString = "id";
1439 else
1440 elementTypeAsString = VD->getType().getAsString();
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001441 }
Mike Stump11289f42009-09-09 15:08:12 +00001442
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001443 // struct __objcFastEnumerationState enumState = { 0 };
1444 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1445 // id items[16];
1446 buf += "id items[16];\n\t";
1447 // id l_collection = (id)
1448 buf += "id l_collection = (id)";
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001449 // Find start location of 'collection' the hard way!
1450 const char *startCollectionBuf = startBuf;
1451 startCollectionBuf += 3; // skip 'for'
1452 startCollectionBuf = strchr(startCollectionBuf, '(');
1453 startCollectionBuf++; // skip '('
1454 // find 'in' and skip it.
1455 while (*startCollectionBuf != ' ' ||
1456 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1457 (*(startCollectionBuf+3) != ' ' &&
1458 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1459 startCollectionBuf++;
1460 startCollectionBuf += 3;
Mike Stump11289f42009-09-09 15:08:12 +00001461
1462 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001463 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001464 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001465 SourceLocation rightParenLoc = S->getRParenLoc();
1466 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1467 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001468 buf = ";\n\t";
Mike Stump11289f42009-09-09 15:08:12 +00001469
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001470 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1471 // objects:items count:16];
1472 // which is synthesized into:
Mike Stump11289f42009-09-09 15:08:12 +00001473 // unsigned int limit =
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001474 // ((unsigned int (*)
1475 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001476 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001477 // sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001478 // "countByEnumeratingWithState:objects:count:"),
1479 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001480 // (id *)items, (unsigned int)16);
1481 buf += "unsigned long limit =\n\t\t";
1482 SynthCountByEnumWithState(buf);
1483 buf += ";\n\t";
1484 /// if (limit) {
1485 /// unsigned long startMutations = *enumState.mutationsPtr;
1486 /// do {
1487 /// unsigned long counter = 0;
1488 /// do {
Mike Stump11289f42009-09-09 15:08:12 +00001489 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001490 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001491 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001492 buf += "if (limit) {\n\t";
1493 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1494 buf += "do {\n\t\t";
1495 buf += "unsigned long counter = 0;\n\t\t";
1496 buf += "do {\n\t\t\t";
1497 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1498 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1499 buf += elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001500 buf += " = (";
1501 buf += elementTypeAsString;
1502 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001503 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001504 ReplaceText(lparenLoc, 1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001505
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001506 /// __continue_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001507 /// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001508 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001509 /// objects:items count:16]);
1510 /// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001511 /// __break_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001512 /// }
1513 /// else
1514 /// elem = nil;
1515 /// }
Mike Stump11289f42009-09-09 15:08:12 +00001516 ///
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001517 buf = ";\n\t";
1518 buf += "__continue_label_";
1519 buf += utostr(ObjCBcLabelNo.back());
1520 buf += ": ;";
1521 buf += "\n\t\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001522 buf += "} while (counter < limit);\n\t";
1523 buf += "} while (limit = ";
1524 SynthCountByEnumWithState(buf);
1525 buf += ");\n\t";
1526 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001527 buf += " = ((";
1528 buf += elementTypeAsString;
1529 buf += ")0);\n\t";
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001530 buf += "__break_label_";
1531 buf += utostr(ObjCBcLabelNo.back());
1532 buf += ": ;\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001533 buf += "}\n\t";
1534 buf += "else\n\t\t";
1535 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001536 buf += " = ((";
1537 buf += elementTypeAsString;
1538 buf += ")0);\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001539 buf += "}\n";
Mike Stump11289f42009-09-09 15:08:12 +00001540
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001541 // Insert all these *after* the statement body.
Sebastian Redla7b98a72009-04-26 20:35:05 +00001542 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Narofff0ff8792008-07-21 18:26:02 +00001543 if (isa<CompoundStmt>(S->getBody())) {
1544 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001545 InsertText(endBodyLoc, buf);
Steve Narofff0ff8792008-07-21 18:26:02 +00001546 } else {
1547 /* Need to treat single statements specially. For example:
1548 *
1549 * for (A *a in b) if (stuff()) break;
1550 * for (A *a in b) xxxyy;
1551 *
1552 * The following code simply scans ahead to the semi to find the actual end.
1553 */
1554 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1555 const char *semiBuf = strchr(stmtBuf, ';');
1556 assert(semiBuf && "Can't find ';'");
1557 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001558 InsertText(endBodyLoc, buf);
Steve Narofff0ff8792008-07-21 18:26:02 +00001559 }
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001560 Stmts.pop_back();
1561 ObjCBcLabelNo.pop_back();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001562 return 0;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001563}
1564
Mike Stump11289f42009-09-09 15:08:12 +00001565/// RewriteObjCSynchronizedStmt -
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001566/// This routine rewrites @synchronized(expr) stmt;
1567/// into:
1568/// objc_sync_enter(expr);
1569/// @try stmt @finally { objc_sync_exit(expr); }
1570///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001571Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001572 // Get the start location and compute the semi location.
1573 SourceLocation startLoc = S->getLocStart();
1574 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001575
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001576 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump11289f42009-09-09 15:08:12 +00001577
1578 std::string buf;
Steve Naroffb2fc0522008-08-21 13:03:03 +00001579 buf = "objc_sync_enter((id)";
1580 const char *lparenBuf = startBuf;
1581 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001582 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001583 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1584 // the sync expression is typically a message expression that's already
Steve Naroffad7013b2008-08-19 13:04:19 +00001585 // been rewritten! (which implies the SourceLocation's are invalid).
1586 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001587 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffad7013b2008-08-19 13:04:19 +00001588 while (*endBuf != ')') endBuf--;
1589 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001590 buf = ");\n";
1591 // declare a new scope with two variables, _stack and _rethrow.
1592 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1593 buf += "int buf[18/*32-bit i386*/];\n";
1594 buf += "char *pointers[4];} _stack;\n";
1595 buf += "id volatile _rethrow = 0;\n";
1596 buf += "objc_exception_try_enter(&_stack);\n";
1597 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001598 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001599 startLoc = S->getSynchBody()->getLocEnd();
1600 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001601
Steve Naroffad7013b2008-08-19 13:04:19 +00001602 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001603 SourceLocation lastCurlyLoc = startLoc;
1604 buf = "}\nelse {\n";
1605 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroffd9803712009-04-29 16:37:50 +00001606 buf += "}\n";
1607 buf += "{ /* implicit finally clause */\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001608 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffec60b432009-12-05 21:43:12 +00001609
1610 std::string syncBuf;
1611 syncBuf += " objc_sync_exit(";
John McCall97513962010-01-15 18:39:57 +00001612 Expr *syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1613 CastExpr::CK_Unknown,
1614 S->getSynchExpr());
Ted Kremenek2d470fc2008-09-13 05:16:45 +00001615 std::string syncExprBufS;
1616 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00001617 syncExpr->printPretty(syncExprBuf, *Context, 0,
1618 PrintingPolicy(LangOpts));
Steve Naroffec60b432009-12-05 21:43:12 +00001619 syncBuf += syncExprBuf.str();
1620 syncBuf += ");";
1621
1622 buf += syncBuf;
1623 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001624 buf += "}\n";
1625 buf += "}";
Mike Stump11289f42009-09-09 15:08:12 +00001626
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001627 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffec60b432009-12-05 21:43:12 +00001628
1629 bool hasReturns = false;
1630 HasReturnStmts(S->getSynchBody(), hasReturns);
1631 if (hasReturns)
1632 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1633
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001634 return 0;
1635}
1636
Steve Naroffec60b432009-12-05 21:43:12 +00001637void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1638{
Steve Naroff6d6da252008-12-05 17:03:39 +00001639 // Perform a bottom up traversal of all children.
1640 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1641 CI != E; ++CI)
1642 if (*CI)
Steve Naroffec60b432009-12-05 21:43:12 +00001643 WarnAboutReturnGotoStmts(*CI);
Steve Naroff6d6da252008-12-05 17:03:39 +00001644
Steve Naroffec60b432009-12-05 21:43:12 +00001645 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump11289f42009-09-09 15:08:12 +00001646 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff6d6da252008-12-05 17:03:39 +00001647 TryFinallyContainsReturnDiag);
1648 }
1649 return;
1650}
1651
Steve Naroffec60b432009-12-05 21:43:12 +00001652void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1653{
1654 // 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)
1658 HasReturnStmts(*CI, hasReturns);
1659
1660 if (isa<ReturnStmt>(S))
1661 hasReturns = true;
1662 return;
1663}
1664
1665void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1666 // Perform a bottom up traversal of all children.
1667 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1668 CI != E; ++CI)
1669 if (*CI) {
1670 RewriteTryReturnStmts(*CI);
1671 }
1672 if (isa<ReturnStmt>(S)) {
1673 SourceLocation startLoc = S->getLocStart();
1674 const char *startBuf = SM->getCharacterData(startLoc);
1675
1676 const char *semiBuf = strchr(startBuf, ';');
1677 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1678 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1679
1680 std::string buf;
1681 buf = "{ objc_exception_try_exit(&_stack); return";
1682
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001683 ReplaceText(startLoc, 6, buf);
1684 InsertText(onePastSemiLoc, "}");
Steve Naroffec60b432009-12-05 21:43:12 +00001685 }
1686 return;
1687}
1688
1689void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1690 // Perform a bottom up traversal of all children.
1691 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1692 CI != E; ++CI)
1693 if (*CI) {
1694 RewriteSyncReturnStmts(*CI, syncExitBuf);
1695 }
1696 if (isa<ReturnStmt>(S)) {
1697 SourceLocation startLoc = S->getLocStart();
1698 const char *startBuf = SM->getCharacterData(startLoc);
1699
1700 const char *semiBuf = strchr(startBuf, ';');
1701 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1702 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1703
1704 std::string buf;
1705 buf = "{ objc_exception_try_exit(&_stack);";
1706 buf += syncExitBuf;
1707 buf += " return";
1708
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001709 ReplaceText(startLoc, 6, buf);
1710 InsertText(onePastSemiLoc, "}");
Steve Naroffec60b432009-12-05 21:43:12 +00001711 }
1712 return;
1713}
1714
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001715Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001716 // Get the start location and compute the semi location.
1717 SourceLocation startLoc = S->getLocStart();
1718 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001719
Steve Naroffbf478ec2007-11-07 04:08:17 +00001720 assert((*startBuf == '@') && "bogus @try location");
1721
1722 std::string buf;
1723 // declare a new scope with two variables, _stack and _rethrow.
1724 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1725 buf += "int buf[18/*32-bit i386*/];\n";
1726 buf += "char *pointers[4];} _stack;\n";
1727 buf += "id volatile _rethrow = 0;\n";
1728 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff16018582007-11-07 18:43:40 +00001729 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffbf478ec2007-11-07 04:08:17 +00001730
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001731 ReplaceText(startLoc, 4, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001732
Steve Naroffbf478ec2007-11-07 04:08:17 +00001733 startLoc = S->getTryBody()->getLocEnd();
1734 startBuf = SM->getCharacterData(startLoc);
1735
1736 assert((*startBuf == '}') && "bogus @try block");
Mike Stump11289f42009-09-09 15:08:12 +00001737
Steve Naroffbf478ec2007-11-07 04:08:17 +00001738 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffce2dca12008-07-16 15:31:30 +00001739 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1740 if (catchList) {
1741 startLoc = startLoc.getFileLocWithOffset(1);
1742 buf = " /* @catch begin */ else {\n";
1743 buf += " id _caught = objc_exception_extract(&_stack);\n";
1744 buf += " objc_exception_try_enter (&_stack);\n";
1745 buf += " if (_setjmp(_stack.buf))\n";
1746 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1747 buf += " else { /* @catch continue */";
Mike Stump11289f42009-09-09 15:08:12 +00001748
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001749 InsertText(startLoc, buf);
Steve Narofffac18fe2008-09-09 19:59:12 +00001750 } else { /* no catch list */
1751 buf = "}\nelse {\n";
1752 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1753 buf += "}";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001754 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffce2dca12008-07-16 15:31:30 +00001755 }
Steve Naroffbf478ec2007-11-07 04:08:17 +00001756 bool sawIdTypedCatch = false;
1757 Stmt *lastCatchBody = 0;
Steve Naroffbf478ec2007-11-07 04:08:17 +00001758 while (catchList) {
Steve Naroff371b8fb2009-03-03 19:52:17 +00001759 ParmVarDecl *catchDecl = catchList->getCatchParamDecl();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001760
Mike Stump11289f42009-09-09 15:08:12 +00001761 if (catchList == S->getCatchStmts())
Steve Naroffbf478ec2007-11-07 04:08:17 +00001762 buf = "if ("; // we are generating code for the first catch clause
1763 else
1764 buf = "else if (";
1765 startLoc = catchList->getLocStart();
1766 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001767
Steve Naroffbf478ec2007-11-07 04:08:17 +00001768 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump11289f42009-09-09 15:08:12 +00001769
Steve Naroffbf478ec2007-11-07 04:08:17 +00001770 const char *lParenLoc = strchr(startBuf, '(');
1771
Steve Naroffe6b7ffd2008-02-01 22:08:12 +00001772 if (catchList->hasEllipsis()) {
Steve Naroffedb5bc62008-02-01 20:02:07 +00001773 // Now rewrite the body...
1774 lastCatchBody = catchList->getCatchBody();
Steve Naroffedb5bc62008-02-01 20:02:07 +00001775 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1776 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001777 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1778 "bogus @catch paren location");
Steve Naroffedb5bc62008-02-01 20:02:07 +00001779 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001780
Steve Naroffedb5bc62008-02-01 20:02:07 +00001781 buf += "1) { id _tmp = _caught;";
Daniel Dunbardec484a2009-08-19 19:10:30 +00001782 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff371b8fb2009-03-03 19:52:17 +00001783 } else if (catchDecl) {
1784 QualType t = catchDecl->getType();
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001785 if (t == Context->getObjCIdType()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001786 buf += "1) { ";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001787 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroffbf478ec2007-11-07 04:08:17 +00001788 sawIdTypedCatch = true;
Fariborz Jahanian59516092010-01-12 01:22:23 +00001789 } else if (t->isObjCObjectPointerType()) {
1790 QualType InterfaceTy = t->getPointeeType();
1791 const ObjCInterfaceType *cls = // Should be a pointer to a class.
1792 InterfaceTy->getAs<ObjCInterfaceType>();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001793 if (cls) {
Steve Naroff16018582007-11-07 18:43:40 +00001794 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001795 buf += cls->getDecl()->getNameAsString();
Steve Naroff16018582007-11-07 18:43:40 +00001796 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001797 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroffbf478ec2007-11-07 04:08:17 +00001798 }
1799 }
1800 // Now rewrite the body...
1801 lastCatchBody = catchList->getCatchBody();
1802 SourceLocation rParenLoc = catchList->getRParenLoc();
1803 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1804 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1805 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1806 assert((*rParenBuf == ')') && "bogus @catch paren location");
1807 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001808
Mike Stump11289f42009-09-09 15:08:12 +00001809 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroffbf478ec2007-11-07 04:08:17 +00001810 // declares the @catch parameter).
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001811 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff371b8fb2009-03-03 19:52:17 +00001812 } else {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001813 assert(false && "@catch rewrite bug");
Steve Naroffa733c7f2007-11-07 15:32:26 +00001814 }
Steve Naroffedb5bc62008-02-01 20:02:07 +00001815 // make sure all the catch bodies get rewritten!
Steve Naroffbf478ec2007-11-07 04:08:17 +00001816 catchList = catchList->getNextCatchStmt();
1817 }
1818 // Complete the catch list...
1819 if (lastCatchBody) {
1820 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001821 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1822 "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001823
Steve Naroff4adbe312008-09-11 15:29:03 +00001824 // Insert the last (implicit) else clause *before* the right curly brace.
1825 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1826 buf = "} /* last catch end */\n";
1827 buf += "else {\n";
1828 buf += " _rethrow = _caught;\n";
1829 buf += " objc_exception_try_exit(&_stack);\n";
1830 buf += "} } /* @catch end */\n";
1831 if (!S->getFinallyStmt())
1832 buf += "}\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001833 InsertText(bodyLoc, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001834
Steve Naroffbf478ec2007-11-07 04:08:17 +00001835 // Set lastCurlyLoc
1836 lastCurlyLoc = lastCatchBody->getLocEnd();
1837 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001838 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001839 startLoc = finalStmt->getLocStart();
1840 startBuf = SM->getCharacterData(startLoc);
1841 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump11289f42009-09-09 15:08:12 +00001842
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001843 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump11289f42009-09-09 15:08:12 +00001844
Steve Naroffbf478ec2007-11-07 04:08:17 +00001845 Stmt *body = finalStmt->getFinallyBody();
1846 SourceLocation startLoc = body->getLocStart();
1847 SourceLocation endLoc = body->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001848 assert(*SM->getCharacterData(startLoc) == '{' &&
1849 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001850 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001851 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001852
Steve Naroffbf478ec2007-11-07 04:08:17 +00001853 startLoc = startLoc.getFileLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001854 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Steve Naroffbf478ec2007-11-07 04:08:17 +00001855 endLoc = endLoc.getFileLocWithOffset(-1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001856 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump11289f42009-09-09 15:08:12 +00001857
Steve Naroffbf478ec2007-11-07 04:08:17 +00001858 // Set lastCurlyLoc
1859 lastCurlyLoc = body->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00001860
Steve Naroff6d6da252008-12-05 17:03:39 +00001861 // Now check for any return/continue/go statements within the @try.
Steve Naroffec60b432009-12-05 21:43:12 +00001862 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff4adbe312008-09-11 15:29:03 +00001863 } else { /* no finally clause - make sure we synthesize an implicit one */
1864 buf = "{ /* implicit finally clause */\n";
1865 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1866 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1867 buf += "}";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001868 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffec60b432009-12-05 21:43:12 +00001869
1870 // Now check for any return/continue/go statements within the @try.
1871 // The implicit finally clause won't called if the @try contains any
1872 // jump statements.
1873 bool hasReturns = false;
1874 HasReturnStmts(S->getTryBody(), hasReturns);
1875 if (hasReturns)
1876 RewriteTryReturnStmts(S->getTryBody());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001877 }
1878 // Now emit the final closing curly brace...
1879 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001880 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001881 return 0;
1882}
1883
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001884Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001885 return 0;
1886}
1887
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001888Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001889 return 0;
1890}
1891
Mike Stump11289f42009-09-09 15:08:12 +00001892// This can't be done with ReplaceStmt(S, ThrowExpr), since
1893// the throw expression is typically a message expression that's already
Steve Naroffa733c7f2007-11-07 15:32:26 +00001894// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001895Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroffa733c7f2007-11-07 15:32:26 +00001896 // Get the start location and compute the semi location.
1897 SourceLocation startLoc = S->getLocStart();
1898 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001899
Steve Naroffa733c7f2007-11-07 15:32:26 +00001900 assert((*startBuf == '@') && "bogus @throw location");
1901
1902 std::string buf;
1903 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffc7d2df22008-01-19 00:42:38 +00001904 if (S->getThrowExpr())
1905 buf = "objc_exception_throw(";
1906 else // add an implicit argument
1907 buf = "objc_exception_throw(_caught";
Mike Stump11289f42009-09-09 15:08:12 +00001908
Steve Naroff29788342008-07-25 15:41:30 +00001909 // handle "@ throw" correctly.
1910 const char *wBuf = strchr(startBuf, 'w');
1911 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001912 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001913
Steve Naroffa733c7f2007-11-07 15:32:26 +00001914 const char *semiBuf = strchr(startBuf, ';');
1915 assert((*semiBuf == ';') && "@throw: can't find ';'");
1916 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001917 ReplaceText(semiLoc, 1, ");");
Steve Naroffa733c7f2007-11-07 15:32:26 +00001918 return 0;
1919}
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001920
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001921Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerc6d91c02007-10-17 22:35:30 +00001922 // Create a new string expression.
1923 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlssond8499822007-10-29 05:01:08 +00001924 std::string StrEncoding;
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00001925 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00001926 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
1927 StrEncoding.length(), false,StrType,
1928 SourceLocation());
Chris Lattner2e0d2602008-01-31 19:37:57 +00001929 ReplaceStmt(Exp, Replacement);
Mike Stump11289f42009-09-09 15:08:12 +00001930
Chris Lattner4431a1b2007-11-30 22:53:43 +00001931 // Replace this subexpr in the parent.
Steve Naroff22216db2008-12-04 23:50:32 +00001932 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattner69534692007-10-24 16:57:36 +00001933 return Replacement;
Chris Lattnera7c19fe2007-10-16 22:36:42 +00001934}
1935
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001936Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff2654e182008-12-22 22:16:07 +00001937 if (!SelGetUidFunctionDecl)
1938 SynthSelGetUidFunctionDecl();
Steve Naroffe4f9b232007-11-05 14:50:49 +00001939 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1940 // Create a call to sel_registerName("selName").
1941 llvm::SmallVector<Expr*, 8> SelExprs;
1942 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00001943 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00001944 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00001945 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00001946 false, argType, SourceLocation()));
Steve Naroffe4f9b232007-11-05 14:50:49 +00001947 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1948 &SelExprs[0], SelExprs.size());
Chris Lattner2e0d2602008-01-31 19:37:57 +00001949 ReplaceStmt(Exp, SelExp);
Steve Naroff22216db2008-12-04 23:50:32 +00001950 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffe4f9b232007-11-05 14:50:49 +00001951 return SelExp;
1952}
1953
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001954CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff574440f2007-10-24 22:48:43 +00001955 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001956 // Get the type, we will need to reference it in a couple spots.
Steve Naroff574440f2007-10-24 22:48:43 +00001957 QualType msgSendType = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001958
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001959 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek5a201952009-02-07 01:47:29 +00001960 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001961
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001962 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattner3c799d72007-10-24 17:06:59 +00001963 QualType pToFunc = Context->getPointerType(msgSendType);
Mike Stump11289f42009-09-09 15:08:12 +00001964 ImplicitCastExpr *ICE = new (Context) ImplicitCastExpr(pToFunc,
Anders Carlssona2615922009-07-31 00:48:10 +00001965 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00001966 DRE,
Douglas Gregora11693b2008-11-12 17:17:38 +00001967 /*isLvalue=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00001968
John McCall9dd450b2009-09-21 23:43:11 +00001969 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00001970
Ted Kremenekd7b4f402009-02-09 20:51:47 +00001971 return new (Context) CallExpr(*Context, ICE, args, nargs, FT->getResultType(),
1972 SourceLocation());
Steve Naroff574440f2007-10-24 22:48:43 +00001973}
1974
Steve Naroff50d42052007-11-01 13:24:47 +00001975static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1976 const char *&startRef, const char *&endRef) {
1977 while (startBuf < endBuf) {
1978 if (*startBuf == '<')
1979 startRef = startBuf; // mark the start.
1980 if (*startBuf == '>') {
Steve Naroff1b232132007-11-09 12:50:28 +00001981 if (startRef && *startRef == '<') {
1982 endRef = startBuf; // mark the end.
1983 return true;
1984 }
1985 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00001986 }
1987 startBuf++;
1988 }
1989 return false;
1990}
1991
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00001992static void scanToNextArgument(const char *&argRef) {
1993 int angle = 0;
1994 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1995 if (*argRef == '<')
1996 angle++;
1997 else if (*argRef == '>')
1998 angle--;
1999 argRef++;
2000 }
2001 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2002}
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002003
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002004bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian80c54b02010-02-03 21:29:28 +00002005 if (T->isObjCQualifiedIdType())
2006 return true;
Fariborz Jahanian06769f92010-02-02 18:35:07 +00002007 if (const PointerType *PT = T->getAs<PointerType>()) {
2008 if (PT->getPointeeType()->isObjCQualifiedIdType())
2009 return true;
2010 }
2011 if (T->isObjCObjectPointerType()) {
2012 T = T->getPointeeType();
2013 return T->isObjCQualifiedInterfaceType();
2014 }
2015 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00002016}
2017
Steve Naroff873bd842008-07-29 18:15:38 +00002018void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2019 QualType Type = E->getType();
2020 if (needToScanForQualifiers(Type)) {
Steve Naroffdbfc6932008-11-19 21:15:47 +00002021 SourceLocation Loc, EndLoc;
Mike Stump11289f42009-09-09 15:08:12 +00002022
Steve Naroffdbfc6932008-11-19 21:15:47 +00002023 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2024 Loc = ECE->getLParenLoc();
2025 EndLoc = ECE->getRParenLoc();
2026 } else {
2027 Loc = E->getLocStart();
2028 EndLoc = E->getLocEnd();
2029 }
2030 // This will defend against trying to rewrite synthesized expressions.
2031 if (Loc.isInvalid() || EndLoc.isInvalid())
2032 return;
2033
Steve Naroff873bd842008-07-29 18:15:38 +00002034 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffdbfc6932008-11-19 21:15:47 +00002035 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff873bd842008-07-29 18:15:38 +00002036 const char *startRef = 0, *endRef = 0;
2037 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2038 // Get the locations of the startRef, endRef.
2039 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
2040 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
2041 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002042 InsertText(LessLoc, "/*");
2043 InsertText(GreaterLoc, "*/");
Steve Naroff873bd842008-07-29 18:15:38 +00002044 }
2045 }
2046}
2047
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002048void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002049 SourceLocation Loc;
2050 QualType Type;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002051 const FunctionProtoType *proto = 0;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002052 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2053 Loc = VD->getLocation();
2054 Type = VD->getType();
2055 }
2056 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2057 Loc = FD->getLocation();
2058 // Check for ObjC 'id' and class types that have been adorned with protocol
2059 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall9dd450b2009-09-21 23:43:11 +00002060 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002061 assert(funcType && "missing function type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002062 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002063 if (!proto)
2064 return;
2065 Type = proto->getResultType();
2066 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00002067 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2068 Loc = FD->getLocation();
2069 Type = FD->getType();
2070 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002071 else
2072 return;
Mike Stump11289f42009-09-09 15:08:12 +00002073
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002074 if (needToScanForQualifiers(Type)) {
Steve Naroff50d42052007-11-01 13:24:47 +00002075 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002076
Steve Naroff50d42052007-11-01 13:24:47 +00002077 const char *endBuf = SM->getCharacterData(Loc);
2078 const char *startBuf = endBuf;
Steve Naroff930e0992008-05-31 05:02:17 +00002079 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroff50d42052007-11-01 13:24:47 +00002080 startBuf--; // scan backward (from the decl location) for return type.
2081 const char *startRef = 0, *endRef = 0;
2082 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2083 // Get the locations of the startRef, endRef.
2084 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2085 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2086 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002087 InsertText(LessLoc, "/*");
2088 InsertText(GreaterLoc, "*/");
Steve Naroff37e011c2007-10-31 04:38:33 +00002089 }
2090 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002091 if (!proto)
2092 return; // most likely, was a variable
Steve Naroff50d42052007-11-01 13:24:47 +00002093 // Now check arguments.
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002094 const char *startBuf = SM->getCharacterData(Loc);
2095 const char *startFuncBuf = startBuf;
Steve Naroff50d42052007-11-01 13:24:47 +00002096 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2097 if (needToScanForQualifiers(proto->getArgType(i))) {
2098 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002099
Steve Naroff50d42052007-11-01 13:24:47 +00002100 const char *endBuf = startBuf;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002101 // scan forward (from the decl location) for argument types.
2102 scanToNextArgument(endBuf);
Steve Naroff50d42052007-11-01 13:24:47 +00002103 const char *startRef = 0, *endRef = 0;
2104 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2105 // Get the locations of the startRef, endRef.
Mike Stump11289f42009-09-09 15:08:12 +00002106 SourceLocation LessLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002107 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump11289f42009-09-09 15:08:12 +00002108 SourceLocation GreaterLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002109 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroff50d42052007-11-01 13:24:47 +00002110 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002111 InsertText(LessLoc, "/*");
2112 InsertText(GreaterLoc, "*/");
Steve Naroff50d42052007-11-01 13:24:47 +00002113 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002114 startBuf = ++endBuf;
2115 }
2116 else {
Steve Naroffc884aa82008-08-06 15:58:23 +00002117 // If the function name is derived from a macro expansion, then the
2118 // argument buffer will not follow the name. Need to speak with Chris.
2119 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002120 startBuf++; // scan forward (from the decl location) for argument types.
2121 startBuf++;
2122 }
Steve Naroff50d42052007-11-01 13:24:47 +00002123 }
Steve Naroff37e011c2007-10-31 04:38:33 +00002124}
2125
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002126void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2127 QualType QT = ND->getType();
2128 const Type* TypePtr = QT->getAs<Type>();
2129 if (!isa<TypeOfExprType>(TypePtr))
2130 return;
2131 while (isa<TypeOfExprType>(TypePtr)) {
2132 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2133 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2134 TypePtr = QT->getAs<Type>();
2135 }
2136 // FIXME. This will not work for multiple declarators; as in:
2137 // __typeof__(a) b,c,d;
2138 std::string TypeAsString(QT.getAsString());
2139 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2140 const char *startBuf = SM->getCharacterData(DeclLoc);
2141 if (ND->getInit()) {
2142 std::string Name(ND->getNameAsString());
2143 TypeAsString += " " + Name + " = ";
2144 Expr *E = ND->getInit();
2145 SourceLocation startLoc;
2146 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2147 startLoc = ECE->getLParenLoc();
2148 else
2149 startLoc = E->getLocStart();
2150 startLoc = SM->getInstantiationLoc(startLoc);
2151 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002152 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002153 }
2154 else {
2155 SourceLocation X = ND->getLocEnd();
2156 X = SM->getInstantiationLoc(X);
2157 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002158 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002159 }
2160}
2161
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002162// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002163void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002164 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2165 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002166 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002167 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002168 &ArgTys[0], ArgTys.size(),
2169 false /*isVariadic*/, 0,
2170 false, false, 0, 0, false,
2171 CC_Default);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002172 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002173 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002174 SelGetUidIdent, getFuncType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002175 FunctionDecl::Extern, false);
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002176}
2177
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002178void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002179 // declared in <objc/objc.h>
Douglas Gregor1e21c192009-01-09 01:47:02 +00002180 if (FD->getIdentifier() &&
2181 strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002182 SelGetUidFunctionDecl = FD;
Steve Naroff37e011c2007-10-31 04:38:33 +00002183 return;
2184 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002185 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002186}
2187
Fariborz Jahaniana459c442010-02-12 17:52:31 +00002188static void RewriteBlockPointerType(std::string& Str, QualType Type) {
2189 std::string TypeString(Type.getAsString());
2190 const char *argPtr = TypeString.c_str();
2191 if (!strchr(argPtr, '^')) {
2192 Str += TypeString;
2193 return;
2194 }
2195 while (*argPtr) {
2196 Str += (*argPtr == '^' ? '*' : *argPtr);
2197 argPtr++;
2198 }
2199}
2200
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00002201// FIXME. Consolidate this routine with RewriteBlockPointerType.
2202static void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD) {
2203 QualType Type = VD->getType();
2204 std::string TypeString(Type.getAsString());
2205 const char *argPtr = TypeString.c_str();
2206 int paren = 0;
2207 while (*argPtr) {
2208 switch (*argPtr) {
2209 case '(':
2210 Str += *argPtr;
2211 paren++;
2212 break;
2213 case ')':
2214 Str += *argPtr;
2215 paren--;
2216 break;
2217 case '^':
2218 Str += '*';
2219 if (paren == 1)
2220 Str += VD->getNameAsString();
2221 break;
2222 default:
2223 Str += *argPtr;
2224 break;
2225 }
2226 argPtr++;
2227 }
2228}
2229
2230
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002231void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2232 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2233 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2234 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2235 if (!proto)
2236 return;
2237 QualType Type = proto->getResultType();
2238 std::string FdStr = Type.getAsString();
2239 FdStr += " ";
2240 FdStr += FD->getNameAsCString();
2241 FdStr += "(";
2242 unsigned numArgs = proto->getNumArgs();
2243 for (unsigned i = 0; i < numArgs; i++) {
2244 QualType ArgType = proto->getArgType(i);
Fariborz Jahaniana459c442010-02-12 17:52:31 +00002245 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002246 if (i+1 < numArgs)
2247 FdStr += ", ";
2248 }
2249 FdStr += ");\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002250 InsertText(FunLocStart, FdStr);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002251 CurFunctionDeclToDeclareForBlock = 0;
2252}
2253
Steve Naroff17978c42008-03-11 17:37:02 +00002254// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002255void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroff17978c42008-03-11 17:37:02 +00002256 if (SuperContructorFunctionDecl)
2257 return;
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002258 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroff17978c42008-03-11 17:37:02 +00002259 llvm::SmallVector<QualType, 16> ArgTys;
2260 QualType argT = Context->getObjCIdType();
2261 assert(!argT.isNull() && "Can't find 'id' type");
2262 ArgTys.push_back(argT);
2263 ArgTys.push_back(argT);
2264 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2265 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002266 false, 0,
2267 false, false, 0, 0, false,
2268 CC_Default);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002269 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002270 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002271 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002272 FunctionDecl::Extern, false);
Steve Naroff17978c42008-03-11 17:37:02 +00002273}
2274
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002275// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002276void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002277 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2278 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002279 QualType argT = Context->getObjCIdType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002280 assert(!argT.isNull() && "Can't find 'id' type");
2281 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002282 argT = Context->getObjCSelType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002283 assert(!argT.isNull() && "Can't find 'SEL' type");
2284 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002285 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002286 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002287 true /*isVariadic*/, 0,
2288 false, false, 0, 0, false,
2289 CC_Default);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002290 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002291 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002292 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002293 FunctionDecl::Extern, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002294}
2295
Steve Naroff7fa2f042007-11-15 10:28:18 +00002296// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002297void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002298 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2299 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002300 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002301 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002302 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002303 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2304 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2305 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002306 argT = Context->getObjCSelType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002307 assert(!argT.isNull() && "Can't find 'SEL' type");
2308 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002309 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff7fa2f042007-11-15 10:28:18 +00002310 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002311 true /*isVariadic*/, 0,
2312 false, false, 0, 0, false,
2313 CC_Default);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002314 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002315 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002316 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002317 FunctionDecl::Extern, false);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002318}
2319
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002320// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002321void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002322 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2323 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002324 QualType argT = Context->getObjCIdType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002325 assert(!argT.isNull() && "Can't find 'id' type");
2326 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002327 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002328 assert(!argT.isNull() && "Can't find 'SEL' type");
2329 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002330 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002331 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002332 true /*isVariadic*/, 0,
2333 false, false, 0, 0, false,
2334 CC_Default);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002335 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002336 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002337 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002338 FunctionDecl::Extern, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002339}
2340
Mike Stump11289f42009-09-09 15:08:12 +00002341// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002342// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002343void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump11289f42009-09-09 15:08:12 +00002344 IdentifierInfo *msgSendIdent =
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002345 &Context->Idents.get("objc_msgSendSuper_stret");
2346 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002347 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002348 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002349 &Context->Idents.get("objc_super"));
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002350 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2351 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2352 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002353 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002354 assert(!argT.isNull() && "Can't find 'SEL' type");
2355 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002356 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002357 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002358 true /*isVariadic*/, 0,
2359 false, false, 0, 0, false,
2360 CC_Default);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002361 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002362 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002363 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002364 FunctionDecl::Extern, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002365}
2366
Steve Naroff2e4e3852008-05-08 22:02:18 +00002367// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002368void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002369 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2370 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002371 QualType argT = Context->getObjCIdType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002372 assert(!argT.isNull() && "Can't find 'id' type");
2373 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002374 argT = Context->getObjCSelType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002375 assert(!argT.isNull() && "Can't find 'SEL' type");
2376 ArgTys.push_back(argT);
Steve Naroff2e4e3852008-05-08 22:02:18 +00002377 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002378 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002379 true /*isVariadic*/, 0,
2380 false, false, 0, 0, false,
2381 CC_Default);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002382 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002383 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002384 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002385 FunctionDecl::Extern, false);
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002386}
2387
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002388// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002389void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002390 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2391 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002392 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002393 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002394 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002395 false /*isVariadic*/, 0,
2396 false, false, 0, 0, false,
2397 CC_Default);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002398 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002399 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002400 getClassIdent, getClassType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002401 FunctionDecl::Extern, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002402}
2403
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002404// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002405void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002406 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2407 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002408 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002409 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002410 &ArgTys[0], ArgTys.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002411 false /*isVariadic*/, 0,
2412 false, false, 0, 0, false,
2413 CC_Default);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002414 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002415 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002416 getClassIdent, getClassType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002417 FunctionDecl::Extern, false);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002418}
2419
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002420Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffce8e8862008-03-15 00:55:56 +00002421 QualType strType = getConstantStringStructType();
2422
2423 std::string S = "__NSConstantStringImpl_";
Steve Naroffa6141f02008-05-31 03:35:42 +00002424
2425 std::string tmpName = InFileName;
2426 unsigned i;
2427 for (i=0; i < tmpName.length(); i++) {
2428 char c = tmpName.at(i);
2429 // replace any non alphanumeric characters with '_'.
2430 if (!isalpha(c) && (c < '0' || c > '9'))
2431 tmpName[i] = '_';
2432 }
2433 S += tmpName;
2434 S += "_";
Steve Naroffce8e8862008-03-15 00:55:56 +00002435 S += utostr(NumObjCStringLiterals++);
2436
Steve Naroff00a31762008-03-27 22:29:16 +00002437 Preamble += "static __NSConstantStringImpl " + S;
2438 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2439 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffce8e8862008-03-15 00:55:56 +00002440 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremenek2d470fc2008-09-13 05:16:45 +00002441 std::string prettyBufS;
2442 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00002443 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2444 PrintingPolicy(LangOpts));
Steve Naroff00a31762008-03-27 22:29:16 +00002445 Preamble += prettyBuf.str();
2446 Preamble += ",";
Steve Naroff94ed6dc2009-12-06 01:48:44 +00002447 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00002448
2449 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002450 &Context->Idents.get(S), strType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002451 VarDecl::Static);
Ted Kremenek5a201952009-02-07 01:47:29 +00002452 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
2453 Expr *Unop = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002454 Context->getPointerType(DRE->getType()),
Steve Naroffce8e8862008-03-15 00:55:56 +00002455 SourceLocation());
Steve Naroff265a6b92007-11-08 14:30:50 +00002456 // cast to NSConstantString *
John McCall97513962010-01-15 18:39:57 +00002457 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2458 CastExpr::CK_Unknown, Unop);
Chris Lattner2e0d2602008-01-31 19:37:57 +00002459 ReplaceStmt(Exp, cast);
Steve Naroff22216db2008-12-04 23:50:32 +00002460 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff265a6b92007-11-08 14:30:50 +00002461 return cast;
Steve Naroffa397efd2007-11-03 11:27:19 +00002462}
2463
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002464ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002465 // check if we are sending a message to 'super'
Douglas Gregorffca3a22009-01-09 17:18:27 +00002466 if (!CurMethodDef || !CurMethodDef->isInstanceMethod()) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002467
Douglas Gregor8ea1f532008-11-04 14:56:14 +00002468 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
Mike Stump11289f42009-09-09 15:08:12 +00002469 const ObjCObjectPointerType *OPT =
John McCall9dd450b2009-09-21 23:43:11 +00002470 Super->getType()->getAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00002471 assert(OPT);
2472 const ObjCInterfaceType *IT = OPT->getInterfaceType();
Chris Lattnera9b3cae2008-06-21 18:04:54 +00002473 return IT->getDecl();
2474 }
2475 return 0;
Steve Naroff7fa2f042007-11-15 10:28:18 +00002476}
2477
2478// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002479QualType RewriteObjC::getSuperStructType() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002480 if (!SuperStructDecl) {
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002481 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002482 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002483 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002484 QualType FieldTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00002485
Steve Naroff7fa2f042007-11-15 10:28:18 +00002486 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002487 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002488 // struct objc_class *super;
Mike Stump11289f42009-09-09 15:08:12 +00002489 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor91f84212008-12-11 16:49:14 +00002490
Steve Naroff7fa2f042007-11-15 10:28:18 +00002491 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002492 for (unsigned i = 0; i < 2; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002493 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2494 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002495 FieldTypes[i], 0,
2496 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002497 /*Mutable=*/false));
Douglas Gregor91f84212008-12-11 16:49:14 +00002498 }
Mike Stump11289f42009-09-09 15:08:12 +00002499
Douglas Gregord5058122010-02-11 01:19:42 +00002500 SuperStructDecl->completeDefinition();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002501 }
2502 return Context->getTagDeclType(SuperStructDecl);
2503}
2504
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002505QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffce8e8862008-03-15 00:55:56 +00002506 if (!ConstantStringDecl) {
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002507 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002508 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002509 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffce8e8862008-03-15 00:55:56 +00002510 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00002511
Steve Naroffce8e8862008-03-15 00:55:56 +00002512 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002513 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffce8e8862008-03-15 00:55:56 +00002514 // int flags;
Mike Stump11289f42009-09-09 15:08:12 +00002515 FieldTypes[1] = Context->IntTy;
Steve Naroffce8e8862008-03-15 00:55:56 +00002516 // char *str;
Mike Stump11289f42009-09-09 15:08:12 +00002517 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffce8e8862008-03-15 00:55:56 +00002518 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00002519 FieldTypes[3] = Context->LongTy;
Douglas Gregor91f84212008-12-11 16:49:14 +00002520
Steve Naroffce8e8862008-03-15 00:55:56 +00002521 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002522 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002523 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2524 ConstantStringDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00002525 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002526 FieldTypes[i], 0,
Douglas Gregor91f84212008-12-11 16:49:14 +00002527 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002528 /*Mutable=*/true));
Douglas Gregor91f84212008-12-11 16:49:14 +00002529 }
2530
Douglas Gregord5058122010-02-11 01:19:42 +00002531 ConstantStringDecl->completeDefinition();
Steve Naroffce8e8862008-03-15 00:55:56 +00002532 }
2533 return Context->getTagDeclType(ConstantStringDecl);
2534}
2535
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002536Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002537 if (!SelGetUidFunctionDecl)
2538 SynthSelGetUidFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002539 if (!MsgSendFunctionDecl)
2540 SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002541 if (!MsgSendSuperFunctionDecl)
2542 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002543 if (!MsgSendStretFunctionDecl)
2544 SynthMsgSendStretFunctionDecl();
2545 if (!MsgSendSuperStretFunctionDecl)
2546 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002547 if (!MsgSendFpretFunctionDecl)
2548 SynthMsgSendFpretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002549 if (!GetClassFunctionDecl)
2550 SynthGetClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002551 if (!GetMetaClassFunctionDecl)
2552 SynthGetMetaClassFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002553
Steve Naroff7fa2f042007-11-15 10:28:18 +00002554 // default to objc_msgSend().
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002555 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2556 // May need to use objc_msgSend_stret() as well.
2557 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroffd9803712009-04-29 16:37:50 +00002558 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2559 QualType resultType = mDecl->getResultType();
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002560 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002561 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002562 else if (resultType->isRealFloatingType())
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002563 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002564 }
Mike Stump11289f42009-09-09 15:08:12 +00002565
Steve Naroff574440f2007-10-24 22:48:43 +00002566 // Synthesize a call to objc_msgSend().
2567 llvm::SmallVector<Expr*, 8> MsgExprs;
2568 IdentifierInfo *clsName = Exp->getClassName();
Mike Stump11289f42009-09-09 15:08:12 +00002569
Steve Naroff574440f2007-10-24 22:48:43 +00002570 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2571 if (clsName) { // class message.
Steve Naroff6c79f972008-07-24 19:44:33 +00002572 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2573 // the 'super' idiom within a class method.
Daniel Dunbar07d07852009-10-18 21:17:35 +00002574 if (clsName->getName() == "super") {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002575 MsgSendFlavor = MsgSendSuperFunctionDecl;
2576 if (MsgSendStretFlavor)
2577 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2578 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002579
2580 ObjCInterfaceDecl *SuperDecl =
Steve Naroff677ab3a2008-10-27 17:20:55 +00002581 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002582
2583 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00002584
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002585 // set the receiver to self, the first argument to all methods.
Steve Naroffd9803712009-04-29 16:37:50 +00002586 InitExprs.push_back(
John McCall97513962010-01-15 18:39:57 +00002587 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2588 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002589 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroffd9803712009-04-29 16:37:50 +00002590 Context->getObjCIdType(),
John McCall97513962010-01-15 18:39:57 +00002591 SourceLocation()))
2592 ); // set the 'receiver'.
Steve Naroffd9803712009-04-29 16:37:50 +00002593
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002594 llvm::SmallVector<Expr*, 8> ClsExprs;
2595 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002596 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002597 SuperDecl->getIdentifier()->getNameStart(),
2598 SuperDecl->getIdentifier()->getLength(),
2599 false, argType, SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002600 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002601 &ClsExprs[0],
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002602 ClsExprs.size());
2603 // To turn off a warning, type-cast to 'id'
Douglas Gregore200adc2008-10-27 19:41:14 +00002604 InitExprs.push_back( // set 'super class', using objc_getClass().
John McCall97513962010-01-15 18:39:57 +00002605 NoTypeInfoCStyleCastExpr(Context,
2606 Context->getObjCIdType(),
2607 CastExpr::CK_Unknown, Cls));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002608 // struct objc_super
2609 QualType superType = getSuperStructType();
Steve Naroff0b844f02008-03-11 18:14:26 +00002610 Expr *SuperRep;
Mike Stump11289f42009-09-09 15:08:12 +00002611
Steve Naroff0b844f02008-03-11 18:14:26 +00002612 if (LangOpts.Microsoft) {
2613 SynthSuperContructorFunctionDecl();
2614 // Simulate a contructor call...
Mike Stump11289f42009-09-09 15:08:12 +00002615 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff0b844f02008-03-11 18:14:26 +00002616 superType, SourceLocation());
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002617 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002618 InitExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002619 superType, SourceLocation());
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002620 // The code for super is a little tricky to prevent collision with
2621 // the structure definition in the header. The rewriter has it's own
2622 // internal definition (__rw_objc_super) that is uses. This is why
2623 // we need the cast below. For example:
2624 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2625 //
Ted Kremenek5a201952009-02-07 01:47:29 +00002626 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002627 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002628 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00002629 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2630 Context->getPointerType(superType),
2631 CastExpr::CK_Unknown, SuperRep);
Mike Stump11289f42009-09-09 15:08:12 +00002632 } else {
Steve Naroff0b844f02008-03-11 18:14:26 +00002633 // (struct objc_super) { <exprs from above> }
Ted Kremenek013041e2010-02-19 01:50:18 +00002634 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2635 &InitExprs[0], InitExprs.size(),
2636 SourceLocation());
John McCalle15bbff2010-01-18 19:35:47 +00002637 TypeSourceInfo *superTInfo
2638 = Context->getTrivialTypeSourceInfo(superType);
John McCall5d7aa7f2010-01-19 22:33:45 +00002639 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2640 superType, ILE, false);
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002641 // struct objc_super *
Ted Kremenek5a201952009-02-07 01:47:29 +00002642 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002643 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002644 SourceLocation());
Steve Naroff0b844f02008-03-11 18:14:26 +00002645 }
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002646 MsgExprs.push_back(SuperRep);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002647 } else {
2648 llvm::SmallVector<Expr*, 8> ClsExprs;
2649 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002650 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002651 clsName->getNameStart(),
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002652 clsName->getLength(),
2653 false, argType,
2654 SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002655 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002656 &ClsExprs[0],
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002657 ClsExprs.size());
2658 MsgExprs.push_back(Cls);
2659 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002660 } else { // instance message.
2661 Expr *recExpr = Exp->getReceiver();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002662
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002663 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002664 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002665 if (MsgSendStretFlavor)
2666 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff7fa2f042007-11-15 10:28:18 +00002667 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002668
Steve Naroff7fa2f042007-11-15 10:28:18 +00002669 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00002670
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002671 InitExprs.push_back(
John McCall97513962010-01-15 18:39:57 +00002672 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2673 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002674 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroff97adf602008-07-16 22:35:27 +00002675 Context->getObjCIdType(),
John McCall97513962010-01-15 18:39:57 +00002676 SourceLocation()))
2677 ); // set the 'receiver'.
Mike Stump11289f42009-09-09 15:08:12 +00002678
Steve Naroff7fa2f042007-11-15 10:28:18 +00002679 llvm::SmallVector<Expr*, 8> ClsExprs;
2680 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002681 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002682 SuperDecl->getIdentifier()->getNameStart(),
2683 SuperDecl->getIdentifier()->getLength(),
2684 false, argType, SourceLocation()));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002685 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002686 &ClsExprs[0],
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002687 ClsExprs.size());
Fariborz Jahaniand5db92b2007-12-05 17:29:46 +00002688 // To turn off a warning, type-cast to 'id'
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002689 InitExprs.push_back(
Douglas Gregore200adc2008-10-27 19:41:14 +00002690 // set 'super class', using objc_getClass().
John McCall97513962010-01-15 18:39:57 +00002691 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2692 CastExpr::CK_Unknown, Cls));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002693 // struct objc_super
2694 QualType superType = getSuperStructType();
Steve Naroff17978c42008-03-11 17:37:02 +00002695 Expr *SuperRep;
Mike Stump11289f42009-09-09 15:08:12 +00002696
Steve Naroff17978c42008-03-11 17:37:02 +00002697 if (LangOpts.Microsoft) {
2698 SynthSuperContructorFunctionDecl();
2699 // Simulate a contructor call...
Mike Stump11289f42009-09-09 15:08:12 +00002700 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff17978c42008-03-11 17:37:02 +00002701 superType, SourceLocation());
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002702 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002703 InitExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002704 superType, SourceLocation());
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002705 // The code for super is a little tricky to prevent collision with
2706 // the structure definition in the header. The rewriter has it's own
2707 // internal definition (__rw_objc_super) that is uses. This is why
2708 // we need the cast below. For example:
2709 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2710 //
Ted Kremenek5a201952009-02-07 01:47:29 +00002711 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002712 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002713 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00002714 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2715 Context->getPointerType(superType),
2716 CastExpr::CK_Unknown, SuperRep);
Steve Naroff17978c42008-03-11 17:37:02 +00002717 } else {
2718 // (struct objc_super) { <exprs from above> }
Ted Kremenek013041e2010-02-19 01:50:18 +00002719 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2720 &InitExprs[0], InitExprs.size(),
2721 SourceLocation());
John McCalle15bbff2010-01-18 19:35:47 +00002722 TypeSourceInfo *superTInfo
2723 = Context->getTrivialTypeSourceInfo(superType);
John McCall5d7aa7f2010-01-19 22:33:45 +00002724 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2725 superType, ILE, false);
Steve Naroff17978c42008-03-11 17:37:02 +00002726 }
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002727 MsgExprs.push_back(SuperRep);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002728 } else {
Fariborz Jahanianff6a4552007-12-07 21:21:21 +00002729 // Remove all type-casts because it may contain objc-style types; e.g.
2730 // Foo<Proto> *.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002731 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanianff6a4552007-12-07 21:21:21 +00002732 recExpr = CE->getSubExpr();
John McCall97513962010-01-15 18:39:57 +00002733 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2734 CastExpr::CK_Unknown, recExpr);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002735 MsgExprs.push_back(recExpr);
2736 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002737 }
Steve Naroffa397efd2007-11-03 11:27:19 +00002738 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff574440f2007-10-24 22:48:43 +00002739 llvm::SmallVector<Expr*, 8> SelExprs;
2740 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002741 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00002742 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00002743 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00002744 false, argType, SourceLocation()));
Steve Naroff574440f2007-10-24 22:48:43 +00002745 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2746 &SelExprs[0], SelExprs.size());
2747 MsgExprs.push_back(SelExp);
Mike Stump11289f42009-09-09 15:08:12 +00002748
Steve Naroff574440f2007-10-24 22:48:43 +00002749 // Now push any user supplied arguments.
2750 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroffe7f18192007-11-14 23:54:14 +00002751 Expr *userExpr = Exp->getArg(i);
Steve Narofff60782b2007-11-15 02:58:25 +00002752 // Make all implicit casts explicit...ICE comes in handy:-)
2753 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2754 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregore200adc2008-10-27 19:41:14 +00002755 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002756 ? Context->getObjCIdType()
Douglas Gregore200adc2008-10-27 19:41:14 +00002757 : ICE->getType();
John McCall97513962010-01-15 18:39:57 +00002758 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CastExpr::CK_Unknown,
2759 userExpr);
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002760 }
2761 // Make id<P...> cast into an 'id' cast.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002762 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002763 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregorf19b2312008-10-28 15:36:24 +00002764 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002765 userExpr = CE->getSubExpr();
John McCall97513962010-01-15 18:39:57 +00002766 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2767 CastExpr::CK_Unknown, userExpr);
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002768 }
Mike Stump11289f42009-09-09 15:08:12 +00002769 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002770 MsgExprs.push_back(userExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00002771 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2772 // out the argument in the original expression (since we aren't deleting
2773 // the ObjCMessageExpr). See RewritePropertySetter() usage for more info.
2774 //Exp->setArg(i, 0);
Steve Naroff574440f2007-10-24 22:48:43 +00002775 }
Steve Narofff36987c2007-11-04 22:37:50 +00002776 // Generate the funky cast.
2777 CastExpr *cast;
2778 llvm::SmallVector<QualType, 8> ArgTypes;
2779 QualType returnType;
Mike Stump11289f42009-09-09 15:08:12 +00002780
Steve Narofff36987c2007-11-04 22:37:50 +00002781 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff44864e42007-11-15 10:43:57 +00002782 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2783 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2784 else
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002785 ArgTypes.push_back(Context->getObjCIdType());
2786 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattnera4997152009-02-20 18:43:26 +00002787 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Narofff36987c2007-11-04 22:37:50 +00002788 // Push any user argument types.
Chris Lattnera4997152009-02-20 18:43:26 +00002789 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2790 E = OMD->param_end(); PI != E; ++PI) {
2791 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump11289f42009-09-09 15:08:12 +00002792 ? Context->getObjCIdType()
Chris Lattnera4997152009-02-20 18:43:26 +00002793 : (*PI)->getType();
Steve Naroff52c65fa2008-10-29 14:49:46 +00002794 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffa5c0db82008-12-11 21:05:33 +00002795 if (isTopLevelBlockPointerType(t)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002796 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroff52c65fa2008-10-29 14:49:46 +00002797 t = Context->getPointerType(BPT->getPointeeType());
2798 }
Steve Naroff98eb8d12007-11-05 14:36:37 +00002799 ArgTypes.push_back(t);
2800 }
Chris Lattnera4997152009-02-20 18:43:26 +00002801 returnType = OMD->getResultType()->isObjCQualifiedIdType()
2802 ? Context->getObjCIdType() : OMD->getResultType();
Steve Narofff36987c2007-11-04 22:37:50 +00002803 } else {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002804 returnType = Context->getObjCIdType();
Steve Narofff36987c2007-11-04 22:37:50 +00002805 }
2806 // Get the type, we will need to reference it in a couple spots.
Steve Naroff7fa2f042007-11-15 10:28:18 +00002807 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002808
Steve Narofff36987c2007-11-04 22:37:50 +00002809 // Create a reference to the objc_msgSend() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00002810 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002811 SourceLocation());
Steve Narofff36987c2007-11-04 22:37:50 +00002812
Mike Stump11289f42009-09-09 15:08:12 +00002813 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Narofff36987c2007-11-04 22:37:50 +00002814 // If we don't do this cast, we get the following bizarre warning/note:
2815 // xx.m:13: warning: function called through a non-compatible type
2816 // xx.m:13: note: if this code is reached, the program will abort
John McCall97513962010-01-15 18:39:57 +00002817 cast = NoTypeInfoCStyleCastExpr(Context,
2818 Context->getPointerType(Context->VoidTy),
2819 CastExpr::CK_Unknown, DRE);
Mike Stump11289f42009-09-09 15:08:12 +00002820
Steve Narofff36987c2007-11-04 22:37:50 +00002821 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00002822 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00002823 &ArgTypes[0], ArgTypes.size(),
Steve Naroff327f0f42008-03-18 02:02:04 +00002824 // If we don't have a method decl, force a variadic cast.
Douglas Gregor36c569f2010-02-21 22:15:06 +00002825 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0,
2826 false, false, 0, 0, false,
2827 CC_Default);
Steve Narofff36987c2007-11-04 22:37:50 +00002828 castType = Context->getPointerType(castType);
John McCall97513962010-01-15 18:39:57 +00002829 cast = NoTypeInfoCStyleCastExpr(Context, castType, CastExpr::CK_Unknown,
2830 cast);
Steve Narofff36987c2007-11-04 22:37:50 +00002831
2832 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00002833 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump11289f42009-09-09 15:08:12 +00002834
John McCall9dd450b2009-09-21 23:43:11 +00002835 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002836 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002837 MsgExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002838 FT->getResultType(), SourceLocation());
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002839 Stmt *ReplacingStmt = CE;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002840 if (MsgSendStretFlavor) {
2841 // We have the method which returns a struct/union. Must also generate
2842 // call to objc_msgSend_stret and hang both varieties on a conditional
2843 // expression which dictate which one to envoke depending on size of
2844 // method's return type.
Mike Stump11289f42009-09-09 15:08:12 +00002845
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002846 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00002847 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002848 SourceLocation());
2849 // Need to cast objc_msgSend_stret to "void *" (see above comment).
John McCall97513962010-01-15 18:39:57 +00002850 cast = NoTypeInfoCStyleCastExpr(Context,
2851 Context->getPointerType(Context->VoidTy),
2852 CastExpr::CK_Unknown, STDRE);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002853 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00002854 castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00002855 &ArgTypes[0], ArgTypes.size(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002856 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0,
2857 false, false, 0, 0, false,
2858 CC_Default);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002859 castType = Context->getPointerType(castType);
John McCall97513962010-01-15 18:39:57 +00002860 cast = NoTypeInfoCStyleCastExpr(Context, castType, CastExpr::CK_Unknown,
2861 cast);
Mike Stump11289f42009-09-09 15:08:12 +00002862
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002863 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00002864 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump11289f42009-09-09 15:08:12 +00002865
John McCall9dd450b2009-09-21 23:43:11 +00002866 FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002867 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002868 MsgExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002869 FT->getResultType(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002870
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002871 // Build sizeof(returnType)
Mike Stump11289f42009-09-09 15:08:12 +00002872 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
John McCallbcd03502009-12-07 02:54:59 +00002873 Context->getTrivialTypeSourceInfo(returnType),
Sebastian Redl6f282892008-11-11 17:56:53 +00002874 Context->getSizeType(),
2875 SourceLocation(), SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002876 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2877 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2878 // For X86 it is more complicated and some kind of target specific routine
2879 // is needed to decide what to do.
Mike Stump11289f42009-09-09 15:08:12 +00002880 unsigned IntSize =
Chris Lattner37e05872008-03-05 18:54:05 +00002881 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Mike Stump11289f42009-09-09 15:08:12 +00002882 IntegerLiteral *limit = new (Context) IntegerLiteral(llvm::APInt(IntSize, 8),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002883 Context->IntTy,
2884 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002885 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
2886 BinaryOperator::LE,
2887 Context->IntTy,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002888 SourceLocation());
2889 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump11289f42009-09-09 15:08:12 +00002890 ConditionalOperator *CondExpr =
Douglas Gregor7e112b02009-08-26 14:37:04 +00002891 new (Context) ConditionalOperator(lessThanExpr,
2892 SourceLocation(), CE,
2893 SourceLocation(), STCE, returnType);
Ted Kremenek5a201952009-02-07 01:47:29 +00002894 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002895 }
Mike Stump11289f42009-09-09 15:08:12 +00002896 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002897 return ReplacingStmt;
2898}
2899
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002900Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002901 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Mike Stump11289f42009-09-09 15:08:12 +00002902
Steve Naroff574440f2007-10-24 22:48:43 +00002903 // Now do the actual rewrite.
Chris Lattner2e0d2602008-01-31 19:37:57 +00002904 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00002905
2906 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002907 return ReplacingStmt;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002908}
2909
Steve Naroffd9803712009-04-29 16:37:50 +00002910// typedef struct objc_object Protocol;
2911QualType RewriteObjC::getProtocolType() {
2912 if (!ProtocolTypeDecl) {
John McCallbcd03502009-12-07 02:54:59 +00002913 TypeSourceInfo *TInfo
2914 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroffd9803712009-04-29 16:37:50 +00002915 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002916 SourceLocation(),
Steve Naroffd9803712009-04-29 16:37:50 +00002917 &Context->Idents.get("Protocol"),
John McCallbcd03502009-12-07 02:54:59 +00002918 TInfo);
Steve Naroffd9803712009-04-29 16:37:50 +00002919 }
2920 return Context->getTypeDeclType(ProtocolTypeDecl);
2921}
2922
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00002923/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroffd9803712009-04-29 16:37:50 +00002924/// a synthesized/forward data reference (to the protocol's metadata).
2925/// The forward references (and metadata) are generated in
2926/// RewriteObjC::HandleTranslationUnit().
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002927Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroffd9803712009-04-29 16:37:50 +00002928 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
2929 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump11289f42009-09-09 15:08:12 +00002930 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Douglas Gregored6c7442009-11-23 11:41:28 +00002931 ID, getProtocolType(), 0, VarDecl::Extern);
Steve Naroffd9803712009-04-29 16:37:50 +00002932 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), SourceLocation());
2933 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
2934 Context->getPointerType(DRE->getType()),
2935 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00002936 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
2937 CastExpr::CK_Unknown,
2938 DerefExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00002939 ReplaceStmt(Exp, castExpr);
2940 ProtocolExprDecls.insert(Exp->getProtocol());
Mike Stump11289f42009-09-09 15:08:12 +00002941 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffd9803712009-04-29 16:37:50 +00002942 return castExpr;
Mike Stump11289f42009-09-09 15:08:12 +00002943
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00002944}
2945
Mike Stump11289f42009-09-09 15:08:12 +00002946bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002947 const char *endBuf) {
2948 while (startBuf < endBuf) {
2949 if (*startBuf == '#') {
2950 // Skip whitespace.
2951 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2952 ;
2953 if (!strncmp(startBuf, "if", strlen("if")) ||
2954 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2955 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2956 !strncmp(startBuf, "define", strlen("define")) ||
2957 !strncmp(startBuf, "undef", strlen("undef")) ||
2958 !strncmp(startBuf, "else", strlen("else")) ||
2959 !strncmp(startBuf, "elif", strlen("elif")) ||
2960 !strncmp(startBuf, "endif", strlen("endif")) ||
2961 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2962 !strncmp(startBuf, "include", strlen("include")) ||
2963 !strncmp(startBuf, "import", strlen("import")) ||
2964 !strncmp(startBuf, "include_next", strlen("include_next")))
2965 return true;
2966 }
2967 startBuf++;
2968 }
2969 return false;
2970}
2971
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002972/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002973/// an objective-c class with ivars.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002974void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002975 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002976 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Mike Stump11289f42009-09-09 15:08:12 +00002977 assert(CDecl->getNameAsCString() &&
Douglas Gregor77324f32008-11-17 14:58:09 +00002978 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00002979 // Do not synthesize more than once.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002980 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00002981 return;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002982 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattner8d1c04f2008-03-16 21:08:55 +00002983 int NumIvars = CDecl->ivar_size();
Steve Naroffdde78982007-11-14 19:25:57 +00002984 SourceLocation LocStart = CDecl->getLocStart();
2985 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00002986
Steve Naroffdde78982007-11-14 19:25:57 +00002987 const char *startBuf = SM->getCharacterData(LocStart);
2988 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump11289f42009-09-09 15:08:12 +00002989
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00002990 // If no ivars and no root or if its root, directly or indirectly,
2991 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattner8d1c04f2008-03-16 21:08:55 +00002992 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2993 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner184e65d2009-04-14 23:22:57 +00002994 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002995 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00002996 return;
2997 }
Mike Stump11289f42009-09-09 15:08:12 +00002998
2999 // FIXME: This has potential of causing problem. If
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003000 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003001 Result += "\nstruct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003002 Result += CDecl->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +00003003 if (LangOpts.Microsoft)
3004 Result += "_IMPL";
Steve Naroffdc5b6b22008-03-12 00:25:36 +00003005
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003006 if (NumIvars > 0) {
Steve Naroffdde78982007-11-14 19:25:57 +00003007 const char *cursor = strchr(startBuf, '{');
Mike Stump11289f42009-09-09 15:08:12 +00003008 assert((cursor && endBuf)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003009 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003010 // If the buffer contains preprocessor directives, we do more fine-grained
3011 // rewrites. This is intended to fix code that looks like (which occurs in
3012 // NSURL.h, for example):
3013 //
3014 // #ifdef XYZ
3015 // @interface Foo : NSObject
3016 // #else
3017 // @interface FooBar : NSObject
3018 // #endif
3019 // {
3020 // int i;
3021 // }
3022 // @end
3023 //
3024 // This clause is segregated to avoid breaking the common case.
3025 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump11289f42009-09-09 15:08:12 +00003026 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003027 CDecl->getClassLoc();
3028 const char *endHeader = SM->getCharacterData(L);
Chris Lattner184e65d2009-04-14 23:22:57 +00003029 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003030
Chris Lattnerf5b77512009-02-20 18:18:36 +00003031 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003032 // advance to the end of the referenced protocols.
3033 while (endHeader < cursor && *endHeader != '>') endHeader++;
3034 endHeader++;
3035 }
3036 // rewrite the original header
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003037 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003038 } else {
3039 // rewrite the original header *without* disturbing the '{'
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003040 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003041 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003042 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroffdde78982007-11-14 19:25:57 +00003043 Result = "\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003044 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00003045 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003046 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00003047 Result += "_IVARS;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003048
Steve Naroffdde78982007-11-14 19:25:57 +00003049 // insert the super class structure definition.
Chris Lattner1780a852008-01-31 19:42:41 +00003050 SourceLocation OnePastCurly =
3051 LocStart.getFileLocWithOffset(cursor-startBuf+1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003052 InsertText(OnePastCurly, Result);
Steve Naroffdde78982007-11-14 19:25:57 +00003053 }
3054 cursor++; // past '{'
Mike Stump11289f42009-09-09 15:08:12 +00003055
Steve Naroffdde78982007-11-14 19:25:57 +00003056 // Now comment out any visibility specifiers.
3057 while (cursor < endBuf) {
3058 if (*cursor == '@') {
3059 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner174a8252007-11-14 22:57:51 +00003060 // Skip whitespace.
3061 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3062 /*scan*/;
3063
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003064 // FIXME: presence of @public, etc. inside comment results in
3065 // this transformation as well, which is still correct c-code.
Steve Naroffdde78982007-11-14 19:25:57 +00003066 if (!strncmp(cursor, "public", strlen("public")) ||
3067 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffaf91b9a2008-04-04 22:34:24 +00003068 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003069 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003070 InsertText(atLoc, "// ");
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003071 }
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003072 // FIXME: If there are cases where '<' is used in ivar declaration part
3073 // of user code, then scan the ivar list and use needToScanForQualifiers
3074 // for type checking.
3075 else if (*cursor == '<') {
3076 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003077 InsertText(atLoc, "/* ");
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003078 cursor = strchr(cursor, '>');
3079 cursor++;
3080 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003081 InsertText(atLoc, " */");
Steve Naroff295570a2008-10-30 12:09:33 +00003082 } else if (*cursor == '^') { // rewrite block specifier.
3083 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003084 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003085 }
Steve Naroffdde78982007-11-14 19:25:57 +00003086 cursor++;
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003087 }
Steve Naroffdde78982007-11-14 19:25:57 +00003088 // Don't forget to add a ';'!!
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003089 InsertText(LocEnd.getFileLocWithOffset(1), ";");
Steve Naroffdde78982007-11-14 19:25:57 +00003090 } else { // we don't have any instance variables - insert super struct.
Chris Lattner184e65d2009-04-14 23:22:57 +00003091 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Naroffdde78982007-11-14 19:25:57 +00003092 Result += " {\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003093 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00003094 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003095 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00003096 Result += "_IVARS;\n};\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003097 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003098 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003099 // Mark this struct as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003100 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Naroff13e74872008-05-06 18:26:51 +00003101 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003102}
3103
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003104// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003105/// class methods.
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003106template<typename MethodIterator>
3107void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
3108 MethodIterator MethodEnd,
Fariborz Jahanian3df412a2007-10-25 00:14:44 +00003109 bool IsInstanceMethod,
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003110 const char *prefix,
Chris Lattner211f8b82007-10-25 17:07:24 +00003111 const char *ClassName,
3112 std::string &Result) {
Chris Lattner31bc07e2007-12-12 07:46:12 +00003113 if (MethodBegin == MethodEnd) return;
Mike Stump11289f42009-09-09 15:08:12 +00003114
Chris Lattner31bc07e2007-12-12 07:46:12 +00003115 if (!objc_impl_method) {
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003116 /* struct _objc_method {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003117 SEL _cmd;
3118 char *method_types;
3119 void *_imp;
3120 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003121 */
Chris Lattner211f8b82007-10-25 17:07:24 +00003122 Result += "\nstruct _objc_method {\n";
3123 Result += "\tSEL _cmd;\n";
3124 Result += "\tchar *method_types;\n";
3125 Result += "\tvoid *_imp;\n";
3126 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003127
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003128 objc_impl_method = true;
Fariborz Jahanian74a1cfa2007-10-19 00:36:46 +00003129 }
Mike Stump11289f42009-09-09 15:08:12 +00003130
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003131 // Build _objc_method_list for class's methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003132
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003133 /* struct {
3134 struct _objc_method_list *next_method;
3135 int method_count;
3136 struct _objc_method method_list[];
3137 }
3138 */
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003139 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003140 Result += "\nstatic struct {\n";
3141 Result += "\tstruct _objc_method_list *next_method;\n";
3142 Result += "\tint method_count;\n";
3143 Result += "\tstruct _objc_method method_list[";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003144 Result += utostr(NumMethods);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003145 Result += "];\n} _OBJC_";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003146 Result += prefix;
3147 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
3148 Result += "_METHODS_";
3149 Result += ClassName;
Steve Naroffb327e492008-03-12 17:18:30 +00003150 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003151 Result += IsInstanceMethod ? "inst" : "cls";
3152 Result += "_meth\")))= ";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003153 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003154
Chris Lattner31bc07e2007-12-12 07:46:12 +00003155 Result += "\t,{{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00003156 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattner31bc07e2007-12-12 07:46:12 +00003157 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003158 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattner31bc07e2007-12-12 07:46:12 +00003159 Result += "\", \"";
3160 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003161 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003162 Result += MethodInternalNames[*MethodBegin];
3163 Result += "}\n";
3164 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3165 Result += "\t ,{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00003166 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003167 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003168 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003169 Result += "\", \"";
3170 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003171 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003172 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanian56338352007-11-13 21:02:00 +00003173 Result += "}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003174 }
Chris Lattner31bc07e2007-12-12 07:46:12 +00003175 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003176}
3177
Steve Naroffd9803712009-04-29 16:37:50 +00003178/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner390d39a2008-07-21 21:32:27 +00003179void RewriteObjC::
Steve Naroffd9803712009-04-29 16:37:50 +00003180RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, const char *prefix,
3181 const char *ClassName, std::string &Result) {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003182 static bool objc_protocol_methods = false;
Steve Naroffd9803712009-04-29 16:37:50 +00003183
3184 // Output struct protocol_methods holder of method selector and type.
3185 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3186 /* struct protocol_methods {
3187 SEL _cmd;
3188 char *method_types;
3189 }
3190 */
3191 Result += "\nstruct _protocol_methods {\n";
3192 Result += "\tstruct objc_selector *_cmd;\n";
3193 Result += "\tchar *method_types;\n";
3194 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003195
Steve Naroffd9803712009-04-29 16:37:50 +00003196 objc_protocol_methods = true;
3197 }
3198 // Do not synthesize the protocol more than once.
3199 if (ObjCSynthesizedProtocols.count(PDecl))
3200 return;
Mike Stump11289f42009-09-09 15:08:12 +00003201
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003202 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3203 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3204 PDecl->instmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003205 /* struct _objc_protocol_method_list {
3206 int protocol_method_count;
3207 struct protocol_methods protocols[];
3208 }
Steve Naroff251084d2008-03-12 01:06:30 +00003209 */
Steve Naroffd9803712009-04-29 16:37:50 +00003210 Result += "\nstatic struct {\n";
3211 Result += "\tint protocol_method_count;\n";
3212 Result += "\tstruct _protocol_methods protocol_methods[";
3213 Result += utostr(NumMethods);
3214 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3215 Result += PDecl->getNameAsString();
3216 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3217 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003218
Steve Naroffd9803712009-04-29 16:37:50 +00003219 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003220 for (ObjCProtocolDecl::instmeth_iterator
3221 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003222 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003223 if (I == PDecl->instmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003224 Result += "\t ,{{(struct objc_selector *)\"";
3225 else
3226 Result += "\t ,{(struct objc_selector *)\"";
3227 Result += (*I)->getSelector().getAsString().c_str();
3228 std::string MethodTypeString;
3229 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3230 Result += "\", \"";
3231 Result += MethodTypeString;
3232 Result += "\"}\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003233 }
Steve Naroffd9803712009-04-29 16:37:50 +00003234 Result += "\t }\n};\n";
3235 }
Mike Stump11289f42009-09-09 15:08:12 +00003236
Steve Naroffd9803712009-04-29 16:37:50 +00003237 // Output class methods declared in this protocol.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003238 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3239 PDecl->classmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003240 if (NumMethods > 0) {
3241 /* struct _objc_protocol_method_list {
3242 int protocol_method_count;
3243 struct protocol_methods protocols[];
3244 }
3245 */
3246 Result += "\nstatic struct {\n";
3247 Result += "\tint protocol_method_count;\n";
3248 Result += "\tstruct _protocol_methods protocol_methods[";
3249 Result += utostr(NumMethods);
3250 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3251 Result += PDecl->getNameAsString();
3252 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3253 "{\n\t";
3254 Result += utostr(NumMethods);
3255 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003256
Steve Naroffd9803712009-04-29 16:37:50 +00003257 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003258 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003259 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003260 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003261 if (I == PDecl->classmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003262 Result += "\t ,{{(struct objc_selector *)\"";
3263 else
3264 Result += "\t ,{(struct objc_selector *)\"";
3265 Result += (*I)->getSelector().getAsString().c_str();
3266 std::string MethodTypeString;
3267 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3268 Result += "\", \"";
3269 Result += MethodTypeString;
3270 Result += "\"}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003271 }
Steve Naroffd9803712009-04-29 16:37:50 +00003272 Result += "\t }\n};\n";
3273 }
3274
3275 // Output:
3276 /* struct _objc_protocol {
3277 // Objective-C 1.0 extensions
3278 struct _objc_protocol_extension *isa;
3279 char *protocol_name;
3280 struct _objc_protocol **protocol_list;
3281 struct _objc_protocol_method_list *instance_methods;
3282 struct _objc_protocol_method_list *class_methods;
Mike Stump11289f42009-09-09 15:08:12 +00003283 };
Steve Naroffd9803712009-04-29 16:37:50 +00003284 */
3285 static bool objc_protocol = false;
3286 if (!objc_protocol) {
3287 Result += "\nstruct _objc_protocol {\n";
3288 Result += "\tstruct _objc_protocol_extension *isa;\n";
3289 Result += "\tchar *protocol_name;\n";
3290 Result += "\tstruct _objc_protocol **protocol_list;\n";
3291 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3292 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003293 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003294
Steve Naroffd9803712009-04-29 16:37:50 +00003295 objc_protocol = true;
Chris Lattner388f6e92008-07-21 21:33:21 +00003296 }
Mike Stump11289f42009-09-09 15:08:12 +00003297
Steve Naroffd9803712009-04-29 16:37:50 +00003298 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3299 Result += PDecl->getNameAsString();
3300 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3301 "{\n\t0, \"";
3302 Result += PDecl->getNameAsString();
3303 Result += "\", 0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003304 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003305 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3306 Result += PDecl->getNameAsString();
3307 Result += ", ";
3308 }
3309 else
3310 Result += "0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003311 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003312 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3313 Result += PDecl->getNameAsString();
3314 Result += "\n";
3315 }
3316 else
3317 Result += "0\n";
3318 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003319
Steve Naroffd9803712009-04-29 16:37:50 +00003320 // Mark this protocol as having been generated.
3321 if (!ObjCSynthesizedProtocols.insert(PDecl))
3322 assert(false && "protocol already synthesized");
3323
3324}
3325
3326void RewriteObjC::
3327RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
3328 const char *prefix, const char *ClassName,
3329 std::string &Result) {
3330 if (Protocols.empty()) return;
Mike Stump11289f42009-09-09 15:08:12 +00003331
Steve Naroffd9803712009-04-29 16:37:50 +00003332 for (unsigned i = 0; i != Protocols.size(); i++)
3333 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3334
Chris Lattner388f6e92008-07-21 21:33:21 +00003335 // Output the top lovel protocol meta-data for the class.
3336 /* struct _objc_protocol_list {
3337 struct _objc_protocol_list *next;
3338 int protocol_count;
3339 struct _objc_protocol *class_protocols[];
3340 }
3341 */
3342 Result += "\nstatic struct {\n";
3343 Result += "\tstruct _objc_protocol_list *next;\n";
3344 Result += "\tint protocol_count;\n";
3345 Result += "\tstruct _objc_protocol *class_protocols[";
3346 Result += utostr(Protocols.size());
3347 Result += "];\n} _OBJC_";
3348 Result += prefix;
3349 Result += "_PROTOCOLS_";
3350 Result += ClassName;
3351 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3352 "{\n\t0, ";
3353 Result += utostr(Protocols.size());
3354 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003355
Chris Lattner388f6e92008-07-21 21:33:21 +00003356 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003357 Result += Protocols[0]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003358 Result += " \n";
Mike Stump11289f42009-09-09 15:08:12 +00003359
Chris Lattner388f6e92008-07-21 21:33:21 +00003360 for (unsigned i = 1; i != Protocols.size(); i++) {
3361 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003362 Result += Protocols[i]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003363 Result += "\n";
3364 }
3365 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003366}
3367
Steve Naroffd9803712009-04-29 16:37:50 +00003368
Mike Stump11289f42009-09-09 15:08:12 +00003369/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003370/// implementation.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003371void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003372 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003373 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003374 // Find category declaration for this implementation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003375 ObjCCategoryDecl *CDecl;
Mike Stump11289f42009-09-09 15:08:12 +00003376 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003377 CDecl = CDecl->getNextClassCategory())
3378 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3379 break;
Mike Stump11289f42009-09-09 15:08:12 +00003380
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003381 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003382 FullCategoryName += '_';
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003383 FullCategoryName += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003384
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003385 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003386 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003387 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003388
3389 // If any of our property implementations have associated getters or
3390 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003391 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3392 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003393 Prop != PropEnd; ++Prop) {
3394 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3395 continue;
3396 if (!(*Prop)->getPropertyIvarDecl())
3397 continue;
3398 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3399 if (!PD)
3400 continue;
3401 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3402 InstanceMethods.push_back(Getter);
3403 if (PD->isReadOnly())
3404 continue;
3405 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3406 InstanceMethods.push_back(Setter);
3407 }
3408 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003409 true, "CATEGORY_", FullCategoryName.c_str(),
3410 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003411
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003412 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003413 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003414 false, "CATEGORY_", FullCategoryName.c_str(),
3415 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003416
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003417 // Protocols referenced in class declaration?
Fariborz Jahanian989e0392007-11-13 22:09:49 +00003418 // Null CDecl is case of a category implementation with no category interface
3419 if (CDecl)
Steve Naroffd9803712009-04-29 16:37:50 +00003420 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
3421 FullCategoryName.c_str(), Result);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003422 /* struct _objc_category {
3423 char *category_name;
3424 char *class_name;
3425 struct _objc_method_list *instance_methods;
3426 struct _objc_method_list *class_methods;
3427 struct _objc_protocol_list *protocols;
3428 // Objective-C 1.0 extensions
3429 uint32_t size; // sizeof (struct _objc_category)
Mike Stump11289f42009-09-09 15:08:12 +00003430 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003431 // @property decl.
Mike Stump11289f42009-09-09 15:08:12 +00003432 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003433 */
Mike Stump11289f42009-09-09 15:08:12 +00003434
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003435 static bool objc_category = false;
3436 if (!objc_category) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003437 Result += "\nstruct _objc_category {\n";
3438 Result += "\tchar *category_name;\n";
3439 Result += "\tchar *class_name;\n";
3440 Result += "\tstruct _objc_method_list *instance_methods;\n";
3441 Result += "\tstruct _objc_method_list *class_methods;\n";
3442 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003443 Result += "\tunsigned int size;\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003444 Result += "\tstruct _objc_property_list *instance_properties;\n";
3445 Result += "};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003446 objc_category = true;
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003447 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003448 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3449 Result += FullCategoryName;
Steve Naroffb327e492008-03-12 17:18:30 +00003450 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003451 Result += IDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003452 Result += "\"\n\t, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003453 Result += ClassDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003454 Result += "\"\n";
Mike Stump11289f42009-09-09 15:08:12 +00003455
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003456 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003457 Result += "\t, (struct _objc_method_list *)"
3458 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3459 Result += FullCategoryName;
3460 Result += "\n";
3461 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003462 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003463 Result += "\t, 0\n";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003464 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003465 Result += "\t, (struct _objc_method_list *)"
3466 "&_OBJC_CATEGORY_CLASS_METHODS_";
3467 Result += FullCategoryName;
3468 Result += "\n";
3469 }
3470 else
3471 Result += "\t, 0\n";
Mike Stump11289f42009-09-09 15:08:12 +00003472
Chris Lattnerf5b77512009-02-20 18:18:36 +00003473 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump11289f42009-09-09 15:08:12 +00003474 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003475 Result += FullCategoryName;
3476 Result += "\n";
3477 }
3478 else
3479 Result += "\t, 0\n";
3480 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003481}
3482
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003483/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3484/// ivar offset.
Mike Stump11289f42009-09-09 15:08:12 +00003485void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
3486 ObjCIvarDecl *ivar,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003487 std::string &Result) {
Steve Naroffde7d0f62008-07-16 18:22:22 +00003488 if (ivar->isBitField()) {
3489 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3490 // place all bitfields at offset 0.
3491 Result += "0";
3492 } else {
3493 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003494 Result += IDecl->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003495 if (LangOpts.Microsoft)
3496 Result += "_IMPL";
3497 Result += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003498 Result += ivar->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003499 Result += ")";
3500 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003501}
3502
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003503//===----------------------------------------------------------------------===//
3504// Meta Data Emission
3505//===----------------------------------------------------------------------===//
3506
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003507void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003508 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003509 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump11289f42009-09-09 15:08:12 +00003510
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003511 // Explictly declared @interface's are already synthesized.
Steve Naroffaac654a2009-04-20 20:09:33 +00003512 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump11289f42009-09-09 15:08:12 +00003513 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003514 // produce correct synthesis as yet.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003515 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003516 }
Mike Stump11289f42009-09-09 15:08:12 +00003517
Chris Lattner30d23e82007-12-12 07:56:42 +00003518 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003519 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump11289f42009-09-09 15:08:12 +00003520 ? IDecl->ivar_size()
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003521 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003522 if (NumIvars > 0) {
3523 static bool objc_ivar = false;
3524 if (!objc_ivar) {
3525 /* struct _objc_ivar {
3526 char *ivar_name;
3527 char *ivar_type;
3528 int ivar_offset;
Mike Stump11289f42009-09-09 15:08:12 +00003529 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003530 */
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003531 Result += "\nstruct _objc_ivar {\n";
3532 Result += "\tchar *ivar_name;\n";
3533 Result += "\tchar *ivar_type;\n";
3534 Result += "\tint ivar_offset;\n";
3535 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003536
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003537 objc_ivar = true;
3538 }
3539
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003540 /* struct {
3541 int ivar_count;
3542 struct _objc_ivar ivar_list[nIvars];
Mike Stump11289f42009-09-09 15:08:12 +00003543 };
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003544 */
Mike Stump11289f42009-09-09 15:08:12 +00003545 Result += "\nstatic struct {\n";
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003546 Result += "\tint ivar_count;\n";
3547 Result += "\tstruct _objc_ivar ivar_list[";
3548 Result += utostr(NumIvars);
3549 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003550 Result += IDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003551 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003552 "{\n\t";
3553 Result += utostr(NumIvars);
3554 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003555
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003556 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor5f662052009-04-23 03:23:08 +00003557 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003558 if (!IDecl->ivar_empty()) {
Fariborz Jahanianaef66222010-02-19 00:31:17 +00003559 for (ObjCInterfaceDecl::ivar_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003560 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor5f662052009-04-23 03:23:08 +00003561 IV != IVEnd; ++IV)
3562 IVars.push_back(*IV);
Fariborz Jahanianaef66222010-02-19 00:31:17 +00003563 IVI = IDecl->ivar_begin();
3564 IVE = IDecl->ivar_end();
Chris Lattner30d23e82007-12-12 07:56:42 +00003565 } else {
3566 IVI = CDecl->ivar_begin();
3567 IVE = CDecl->ivar_end();
3568 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003569 Result += "\t,{{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003570 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003571 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003572 std::string TmpString, StrEncoding;
3573 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3574 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003575 Result += StrEncoding;
3576 Result += "\", ";
Chris Lattner30d23e82007-12-12 07:56:42 +00003577 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003578 Result += "}\n";
Chris Lattner30d23e82007-12-12 07:56:42 +00003579 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003580 Result += "\t ,{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003581 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003582 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003583 std::string TmpString, StrEncoding;
3584 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3585 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003586 Result += StrEncoding;
3587 Result += "\", ";
Chris Lattner30d23e82007-12-12 07:56:42 +00003588 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003589 Result += "}\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003590 }
Mike Stump11289f42009-09-09 15:08:12 +00003591
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003592 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003593 }
Mike Stump11289f42009-09-09 15:08:12 +00003594
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003595 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003596 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003597 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003598
3599 // If any of our property implementations have associated getters or
3600 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003601 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3602 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003603 Prop != PropEnd; ++Prop) {
3604 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3605 continue;
3606 if (!(*Prop)->getPropertyIvarDecl())
3607 continue;
3608 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3609 if (!PD)
3610 continue;
3611 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3612 InstanceMethods.push_back(Getter);
3613 if (PD->isReadOnly())
3614 continue;
3615 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3616 InstanceMethods.push_back(Setter);
3617 }
3618 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattner86d7d912008-11-24 03:54:41 +00003619 true, "", IDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003620
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003621 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003622 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner86d7d912008-11-24 03:54:41 +00003623 false, "", IDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003624
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003625 // Protocols referenced in class declaration?
Steve Naroffd9803712009-04-29 16:37:50 +00003626 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
3627 "CLASS", CDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003628
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003629 // Declaration of class/meta-class metadata
3630 /* struct _objc_class {
3631 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003632 const char *super_class_name;
3633 char *name;
3634 long version;
3635 long info;
3636 long instance_size;
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003637 struct _objc_ivar_list *ivars;
3638 struct _objc_method_list *methods;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003639 struct objc_cache *cache;
3640 struct objc_protocol_list *protocols;
3641 const char *ivar_layout;
3642 struct _objc_class_ext *ext;
Mike Stump11289f42009-09-09 15:08:12 +00003643 };
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003644 */
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003645 static bool objc_class = false;
3646 if (!objc_class) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003647 Result += "\nstruct _objc_class {\n";
3648 Result += "\tstruct _objc_class *isa;\n";
3649 Result += "\tconst char *super_class_name;\n";
3650 Result += "\tchar *name;\n";
3651 Result += "\tlong version;\n";
3652 Result += "\tlong info;\n";
3653 Result += "\tlong instance_size;\n";
3654 Result += "\tstruct _objc_ivar_list *ivars;\n";
3655 Result += "\tstruct _objc_method_list *methods;\n";
3656 Result += "\tstruct objc_cache *cache;\n";
3657 Result += "\tstruct _objc_protocol_list *protocols;\n";
3658 Result += "\tconst char *ivar_layout;\n";
3659 Result += "\tstruct _objc_class_ext *ext;\n";
3660 Result += "};\n";
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003661 objc_class = true;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003662 }
Mike Stump11289f42009-09-09 15:08:12 +00003663
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003664 // Meta-class metadata generation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003665 ObjCInterfaceDecl *RootClass = 0;
3666 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003667 while (SuperClass) {
3668 RootClass = SuperClass;
3669 SuperClass = SuperClass->getSuperClass();
3670 }
3671 SuperClass = CDecl->getSuperClass();
Mike Stump11289f42009-09-09 15:08:12 +00003672
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003673 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003674 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003675 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003676 "{\n\t(struct _objc_class *)\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003677 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003678 Result += "\"";
3679
3680 if (SuperClass) {
3681 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003682 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003683 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003684 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003685 Result += "\"";
3686 }
3687 else {
3688 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003689 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003690 Result += "\"";
3691 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003692 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003693 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003694 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003695 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff0b844f02008-03-11 18:14:26 +00003696 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003697 Result += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003698 Result += "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003699 }
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003700 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003701 Result += ", 0\n";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003702 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003703 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003704 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003705 Result += ",0,0\n";
3706 }
Fariborz Jahanian486f7182007-10-24 20:54:23 +00003707 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003708 Result += "\t,0,0,0,0\n";
3709 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003710
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003711 // class metadata generation.
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003712 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003713 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003714 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003715 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003716 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003717 if (SuperClass) {
3718 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003719 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003720 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003721 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003722 Result += "\"";
3723 }
3724 else {
3725 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003726 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003727 Result += "\"";
3728 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003729 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003730 Result += ", 0,1";
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003731 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003732 Result += ",0";
3733 else {
3734 // class has size. Must synthesize its size.
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00003735 Result += ",sizeof(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003736 Result += CDecl->getNameAsString();
Steve Naroff14a07462008-03-10 23:33:22 +00003737 if (LangOpts.Microsoft)
3738 Result += "_IMPL";
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003739 Result += ")";
3740 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003741 if (NumIvars > 0) {
Steve Naroff17978c42008-03-11 17:37:02 +00003742 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003743 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003744 Result += "\n\t";
3745 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003746 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003747 Result += ",0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003748 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003749 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003750 Result += CDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003751 Result += ", 0\n\t";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003752 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003753 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003754 Result += ",0,0";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003755 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003756 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003757 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003758 Result += ", 0,0\n";
3759 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003760 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003761 Result += ",0,0,0\n";
3762 Result += "};\n";
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003763}
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003764
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003765/// RewriteImplementations - This routine rewrites all method implementations
3766/// and emits meta-data.
3767
Steve Narofff8cfd162008-11-13 20:07:04 +00003768void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003769 int ClsDefCount = ClassImplementation.size();
3770 int CatDefCount = CategoryImplementation.size();
Mike Stump11289f42009-09-09 15:08:12 +00003771
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003772 // Rewrite implemented methods
3773 for (int i = 0; i < ClsDefCount; i++)
3774 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump11289f42009-09-09 15:08:12 +00003775
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00003776 for (int i = 0; i < CatDefCount; i++)
3777 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofff8cfd162008-11-13 20:07:04 +00003778}
Mike Stump11289f42009-09-09 15:08:12 +00003779
Steve Narofff8cfd162008-11-13 20:07:04 +00003780void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3781 int ClsDefCount = ClassImplementation.size();
3782 int CatDefCount = CategoryImplementation.size();
3783
Steve Naroff30ac2222008-05-07 21:23:49 +00003784 // This is needed for determining instance variable offsets.
Fariborz Jahanian9ab63492010-01-07 18:31:42 +00003785 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003786 // For each implemented class, write out all its meta data.
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003787 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003788 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump11289f42009-09-09 15:08:12 +00003789
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003790 // For each implemented category, write out all its meta data.
3791 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003792 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroffd9803712009-04-29 16:37:50 +00003793
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003794 // Write objc_symtab metadata
3795 /*
3796 struct _objc_symtab
3797 {
3798 long sel_ref_cnt;
3799 SEL *refs;
3800 short cls_def_cnt;
3801 short cat_def_cnt;
3802 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump11289f42009-09-09 15:08:12 +00003803 };
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003804 */
Mike Stump11289f42009-09-09 15:08:12 +00003805
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003806 Result += "\nstruct _objc_symtab {\n";
3807 Result += "\tlong sel_ref_cnt;\n";
3808 Result += "\tSEL *refs;\n";
3809 Result += "\tshort cls_def_cnt;\n";
3810 Result += "\tshort cat_def_cnt;\n";
3811 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3812 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00003813
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003814 Result += "static struct _objc_symtab "
Steve Naroffb327e492008-03-12 17:18:30 +00003815 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003816 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003817 + ", " + utostr(CatDefCount) + "\n";
3818 for (int i = 0; i < ClsDefCount; i++) {
3819 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003820 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003821 Result += "\n";
3822 }
Mike Stump11289f42009-09-09 15:08:12 +00003823
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003824 for (int i = 0; i < CatDefCount; i++) {
3825 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003826 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003827 Result += "_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003828 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003829 Result += "\n";
3830 }
Mike Stump11289f42009-09-09 15:08:12 +00003831
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003832 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00003833
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003834 // Write objc_module metadata
Mike Stump11289f42009-09-09 15:08:12 +00003835
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003836 /*
3837 struct _objc_module {
3838 long version;
3839 long size;
3840 const char *name;
3841 struct _objc_symtab *symtab;
3842 }
3843 */
Mike Stump11289f42009-09-09 15:08:12 +00003844
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003845 Result += "\nstruct _objc_module {\n";
3846 Result += "\tlong version;\n";
3847 Result += "\tlong size;\n";
3848 Result += "\tconst char *name;\n";
3849 Result += "\tstruct _objc_symtab *symtab;\n";
3850 Result += "};\n\n";
3851 Result += "static struct _objc_module "
Steve Naroffb327e492008-03-12 17:18:30 +00003852 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003853 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003854 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003855 Result += "};\n\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00003856
3857 if (LangOpts.Microsoft) {
Steve Naroffd9803712009-04-29 16:37:50 +00003858 if (ProtocolExprDecls.size()) {
3859 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
3860 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump11289f42009-09-09 15:08:12 +00003861 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00003862 E = ProtocolExprDecls.end(); I != E; ++I) {
3863 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
3864 Result += (*I)->getNameAsString();
3865 Result += " = &_OBJC_PROTOCOL_";
3866 Result += (*I)->getNameAsString();
3867 Result += ";\n";
3868 }
3869 Result += "#pragma data_seg(pop)\n\n";
3870 }
Steve Naroff945a3b12008-03-10 20:43:59 +00003871 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroffcab93d52008-05-07 00:06:16 +00003872 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00003873 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3874 Result += "&_OBJC_MODULES;\n";
3875 Result += "#pragma data_seg(pop)\n\n";
3876 }
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003877}
Chris Lattnera7c19fe2007-10-16 22:36:42 +00003878
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00003879void RewriteObjC::RewriteByRefString(std::string &ResultStr,
3880 const std::string &Name,
3881 ValueDecl *VD) {
3882 assert(BlockByRefDeclNo.count(VD) &&
3883 "RewriteByRefString: ByRef decl missing");
3884 ResultStr += "struct __Block_byref_" + Name +
3885 "_" + utostr(BlockByRefDeclNo[VD]) ;
3886}
3887
Steve Naroff677ab3a2008-10-27 17:20:55 +00003888std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3889 const char *funcName,
3890 std::string Tag) {
3891 const FunctionType *AFT = CE->getFunctionType();
3892 QualType RT = AFT->getResultType();
3893 std::string StructRef = "struct " + Tag;
3894 std::string S = "static " + RT.getAsString() + " __" +
3895 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00003896
Steve Naroff677ab3a2008-10-27 17:20:55 +00003897 BlockDecl *BD = CE->getBlockDecl();
Mike Stump11289f42009-09-09 15:08:12 +00003898
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003899 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump11289f42009-09-09 15:08:12 +00003900 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Narofff26a1d42009-02-02 17:19:26 +00003901 // block (to reference imported block decl refs).
3902 S += "(" + StructRef + " *__cself)";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003903 } else if (BD->param_empty()) {
3904 S += "(" + StructRef + " *__cself)";
3905 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003906 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003907 assert(FT && "SynthesizeBlockFunc: No function proto");
3908 S += '(';
3909 // first add the implicit argument.
3910 S += StructRef + " *__cself, ";
3911 std::string ParamStr;
3912 for (BlockDecl::param_iterator AI = BD->param_begin(),
3913 E = BD->param_end(); AI != E; ++AI) {
3914 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003915 ParamStr = (*AI)->getNameAsString();
Douglas Gregor7de59662009-05-29 20:38:28 +00003916 (*AI)->getType().getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003917 S += ParamStr;
3918 }
3919 if (FT->isVariadic()) {
3920 if (!BD->param_empty()) S += ", ";
3921 S += "...";
3922 }
3923 S += ')';
3924 }
3925 S += " {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003926
Steve Naroff677ab3a2008-10-27 17:20:55 +00003927 // Create local declarations to avoid rewriting all closure decl ref exprs.
3928 // First, emit a declaration for all "by ref" decls.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00003929 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003930 E = BlockByRefDecls.end(); I != E; ++I) {
3931 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003932 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00003933 std::string TypeString;
3934 RewriteByRefString(TypeString, Name, (*I));
3935 TypeString += " *";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00003936 Name = TypeString + Name;
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003937 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump11289f42009-09-09 15:08:12 +00003938 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003939 // Next, emit a declaration for all "by copy" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00003940 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003941 E = BlockByCopyDecls.end(); I != E; ++I) {
3942 S += " ";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003943 // Handle nested closure invocation. For example:
3944 //
3945 // void (^myImportedClosure)(void);
3946 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003947 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003948 // void (^anotherClosure)(void);
3949 // anotherClosure = ^(void) {
3950 // myImportedClosure(); // import and invoke the closure
3951 // };
3952 //
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00003953 if (isTopLevelBlockPointerType((*I)->getType())) {
3954 RewriteBlockPointerTypeVariable(S, (*I));
3955 S += " = (";
3956 RewriteBlockPointerType(S, (*I)->getType());
3957 S += ")";
3958 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3959 }
3960 else {
Fariborz Jahanianb6a68c02010-02-16 17:26:03 +00003961 std::string Name = (*I)->getNameAsString();
Douglas Gregor7de59662009-05-29 20:38:28 +00003962 (*I)->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00003963 S += Name + " = __cself->" +
3964 (*I)->getNameAsString() + "; // bound by copy\n";
3965 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003966 }
3967 std::string RewrittenStr = RewrittenBlockExprs[CE];
3968 const char *cstr = RewrittenStr.c_str();
3969 while (*cstr++ != '{') ;
3970 S += cstr;
3971 S += "\n";
3972 return S;
3973}
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00003974
Steve Naroff677ab3a2008-10-27 17:20:55 +00003975std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3976 const char *funcName,
3977 std::string Tag) {
3978 std::string StructRef = "struct " + Tag;
3979 std::string S = "static void __";
Mike Stump11289f42009-09-09 15:08:12 +00003980
Steve Naroff677ab3a2008-10-27 17:20:55 +00003981 S += funcName;
3982 S += "_block_copy_" + utostr(i);
3983 S += "(" + StructRef;
3984 S += "*dst, " + StructRef;
3985 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00003986 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003987 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00003988 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003989 S += (*I)->getNameAsString();
Steve Naroff5ac4eac2008-12-11 20:51:38 +00003990 S += ", (void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003991 S += (*I)->getNameAsString();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00003992 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003993 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003994 else
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003995 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003996 }
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003997 S += "}\n";
3998
Steve Naroff677ab3a2008-10-27 17:20:55 +00003999 S += "\nstatic void __";
4000 S += funcName;
4001 S += "_block_dispose_" + utostr(i);
4002 S += "(" + StructRef;
4003 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00004004 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004005 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00004006 S += "_Block_object_dispose((void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004007 S += (*I)->getNameAsString();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004008 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00004009 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00004010 else
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00004011 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004012 }
Mike Stump11289f42009-09-09 15:08:12 +00004013 S += "}\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004014 return S;
4015}
4016
Steve Naroff30484702009-12-06 21:14:13 +00004017std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4018 std::string Desc) {
Steve Naroff295570a2008-10-30 12:09:33 +00004019 std::string S = "\nstruct " + Tag;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004020 std::string Constructor = " " + Tag;
Mike Stump11289f42009-09-09 15:08:12 +00004021
Steve Naroff677ab3a2008-10-27 17:20:55 +00004022 S += " {\n struct __block_impl impl;\n";
Steve Naroff30484702009-12-06 21:14:13 +00004023 S += " struct " + Desc;
4024 S += "* Desc;\n";
Mike Stump11289f42009-09-09 15:08:12 +00004025
Steve Naroff30484702009-12-06 21:14:13 +00004026 Constructor += "(void *fp, "; // Invoke function pointer.
4027 Constructor += "struct " + Desc; // Descriptor pointer.
4028 Constructor += " *desc";
Mike Stump11289f42009-09-09 15:08:12 +00004029
Steve Naroff677ab3a2008-10-27 17:20:55 +00004030 if (BlockDeclRefs.size()) {
4031 // Output all "by copy" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004032 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004033 E = BlockByCopyDecls.end(); I != E; ++I) {
4034 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004035 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004036 std::string ArgName = "_" + FieldName;
4037 // Handle nested closure invocation. For example:
4038 //
4039 // void (^myImportedBlock)(void);
4040 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00004041 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00004042 // void (^anotherBlock)(void);
4043 // anotherBlock = ^(void) {
4044 // myImportedBlock(); // import and invoke the closure
4045 // };
4046 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00004047 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004048 S += "struct __block_impl *";
4049 Constructor += ", void *" + ArgName;
4050 } else {
Douglas Gregor7de59662009-05-29 20:38:28 +00004051 (*I)->getType().getAsStringInternal(FieldName, Context->PrintingPolicy);
4052 (*I)->getType().getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004053 Constructor += ", " + ArgName;
4054 }
4055 S += FieldName + ";\n";
4056 }
4057 // Output all "by ref" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004058 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004059 E = BlockByRefDecls.end(); I != E; ++I) {
4060 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004061 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004062 std::string ArgName = "_" + FieldName;
4063 // Handle nested closure invocation. For example:
4064 //
4065 // void (^myImportedBlock)(void);
4066 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00004067 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00004068 // void (^anotherBlock)(void);
4069 // anotherBlock = ^(void) {
4070 // myImportedBlock(); // import and invoke the closure
4071 // };
4072 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00004073 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004074 S += "struct __block_impl *";
4075 Constructor += ", void *" + ArgName;
4076 } else {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004077 std::string TypeString;
4078 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004079 TypeString += " *";
4080 FieldName = TypeString + FieldName;
4081 ArgName = TypeString + ArgName;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004082 Constructor += ", " + ArgName;
4083 }
4084 S += FieldName + "; // by ref\n";
4085 }
4086 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00004087 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00004088 if (GlobalVarDecl)
4089 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4090 else
4091 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00004092 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump11289f42009-09-09 15:08:12 +00004093
Steve Naroff30484702009-12-06 21:14:13 +00004094 Constructor += " Desc = desc;\n";
Mike Stump11289f42009-09-09 15:08:12 +00004095
Steve Naroff677ab3a2008-10-27 17:20:55 +00004096 // Initialize all "by copy" arguments.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004097 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004098 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004099 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004100 Constructor += " ";
Steve Naroffa5c0db82008-12-11 21:05:33 +00004101 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004102 Constructor += Name + " = (struct __block_impl *)_";
4103 else
4104 Constructor += Name + " = _";
4105 Constructor += Name + ";\n";
4106 }
4107 // Initialize all "by ref" arguments.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004108 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004109 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004110 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004111 Constructor += " ";
Steve Naroffa5c0db82008-12-11 21:05:33 +00004112 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004113 Constructor += Name + " = (struct __block_impl *)_";
4114 else
4115 Constructor += Name + " = _";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004116 Constructor += Name + "->__forwarding;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004117 }
4118 } else {
4119 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00004120 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00004121 if (GlobalVarDecl)
4122 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4123 else
4124 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00004125 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4126 Constructor += " Desc = desc;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004127 }
4128 Constructor += " ";
4129 Constructor += "}\n";
4130 S += Constructor;
4131 S += "};\n";
4132 return S;
4133}
4134
Steve Naroff30484702009-12-06 21:14:13 +00004135std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
4136 std::string ImplTag, int i,
4137 const char *FunName,
4138 unsigned hasCopy) {
4139 std::string S = "\nstatic struct " + DescTag;
4140
4141 S += " {\n unsigned long reserved;\n";
4142 S += " unsigned long Block_size;\n";
4143 if (hasCopy) {
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00004144 S += " void (*copy)(struct ";
4145 S += ImplTag; S += "*, struct ";
4146 S += ImplTag; S += "*);\n";
4147
4148 S += " void (*dispose)(struct ";
4149 S += ImplTag; S += "*);\n";
Steve Naroff30484702009-12-06 21:14:13 +00004150 }
4151 S += "} ";
4152
4153 S += DescTag + "_DATA = { 0, sizeof(struct ";
4154 S += ImplTag + ")";
4155 if (hasCopy) {
4156 S += ", __" + std::string(FunName) + "_block_copy_" + utostr(i);
4157 S += ", __" + std::string(FunName) + "_block_dispose_" + utostr(i);
4158 }
4159 S += "};\n";
4160 return S;
4161}
4162
Steve Naroff677ab3a2008-10-27 17:20:55 +00004163void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004164 const char *FunName) {
4165 // Insert declaration for the function in which block literal is used.
Fariborz Jahanian5c26eee2010-01-15 18:14:52 +00004166 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004167 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004168 // Insert closures that were part of the function.
4169 for (unsigned i = 0; i < Blocks.size(); i++) {
4170
4171 CollectBlockDeclRefInfo(Blocks[i]);
4172
Steve Naroff30484702009-12-06 21:14:13 +00004173 std::string ImplTag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
4174 std::string DescTag = "__" + std::string(FunName) + "_block_desc_" + utostr(i);
Mike Stump11289f42009-09-09 15:08:12 +00004175
Steve Naroff30484702009-12-06 21:14:13 +00004176 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004177
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004178 InsertText(FunLocStart, CI);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004179
Steve Naroff30484702009-12-06 21:14:13 +00004180 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump11289f42009-09-09 15:08:12 +00004181
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004182 InsertText(FunLocStart, CF);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004183
4184 if (ImportedBlockDecls.size()) {
Steve Naroff30484702009-12-06 21:14:13 +00004185 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004186 InsertText(FunLocStart, HF);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004187 }
Steve Naroff30484702009-12-06 21:14:13 +00004188 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4189 ImportedBlockDecls.size() > 0);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004190 InsertText(FunLocStart, BD);
Mike Stump11289f42009-09-09 15:08:12 +00004191
Steve Naroff677ab3a2008-10-27 17:20:55 +00004192 BlockDeclRefs.clear();
4193 BlockByRefDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004194 BlockByRefDeclsPtrSet.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004195 BlockByCopyDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004196 BlockByCopyDeclsPtrSet.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004197 BlockCallExprs.clear();
4198 ImportedBlockDecls.clear();
4199 }
4200 Blocks.clear();
4201 RewrittenBlockExprs.clear();
4202}
4203
4204void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4205 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner86d7d912008-11-24 03:54:41 +00004206 const char *FuncName = FD->getNameAsCString();
Mike Stump11289f42009-09-09 15:08:12 +00004207
Steve Naroff677ab3a2008-10-27 17:20:55 +00004208 SynthesizeBlockLiterals(FunLocStart, FuncName);
4209}
4210
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00004211static void BuildUniqueMethodName(std::string &Name,
4212 ObjCMethodDecl *MD) {
4213 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4214 Name = IFace->getNameAsCString();
4215 Name += "__" + MD->getSelector().getAsString();
4216 // Convert colons to underscores.
4217 std::string::size_type loc = 0;
4218 while ((loc = Name.find(":", loc)) != std::string::npos)
4219 Name.replace(loc, 1, "_");
4220}
4221
Steve Naroff677ab3a2008-10-27 17:20:55 +00004222void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroff295570a2008-10-30 12:09:33 +00004223 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4224 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanianb5f99c32010-01-29 01:55:49 +00004225 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00004226 std::string FuncName;
4227 BuildUniqueMethodName(FuncName, MD);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004228 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
4229}
4230
4231void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
4232 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4233 CI != E; ++CI)
4234 if (*CI) {
4235 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4236 GetBlockDeclRefExprs(CBE->getBody());
4237 else
4238 GetBlockDeclRefExprs(*CI);
4239 }
4240 // Handle specific things.
4241 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
4242 // FIXME: Handle enums.
4243 if (!isa<FunctionDecl>(CDRE->getDecl()))
4244 BlockDeclRefs.push_back(CDRE);
4245 return;
4246}
4247
4248void RewriteObjC::GetBlockCallExprs(Stmt *S) {
4249 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4250 CI != E; ++CI)
4251 if (*CI) {
4252 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4253 GetBlockCallExprs(CBE->getBody());
4254 else
4255 GetBlockCallExprs(*CI);
4256 }
Mike Stump11289f42009-09-09 15:08:12 +00004257
Steve Naroff677ab3a2008-10-27 17:20:55 +00004258 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
4259 if (CE->getCallee()->getType()->isBlockPointerType()) {
4260 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
4261 }
4262 }
4263 return;
4264}
4265
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004266Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004267 // Navigate to relevant type information.
Steve Naroff677ab3a2008-10-27 17:20:55 +00004268 const BlockPointerType *CPT = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004269
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004270 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004271 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004272 } else if (const BlockDeclRefExpr *CDRE =
4273 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004274 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004275 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004276 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004277 }
4278 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4279 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4280 }
4281 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4282 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4283 else if (const ConditionalOperator *CEXPR =
4284 dyn_cast<ConditionalOperator>(BlockExp)) {
4285 Expr *LHSExp = CEXPR->getLHS();
4286 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4287 Expr *RHSExp = CEXPR->getRHS();
4288 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4289 Expr *CONDExp = CEXPR->getCond();
4290 ConditionalOperator *CondExpr =
4291 new (Context) ConditionalOperator(CONDExp,
4292 SourceLocation(), cast<Expr>(LHSStmt),
4293 SourceLocation(), cast<Expr>(RHSStmt),
4294 Exp->getType());
4295 return CondExpr;
Fariborz Jahanian6ab7ed42009-12-18 01:15:21 +00004296 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4297 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004298 } else {
4299 assert(1 && "RewriteBlockClass: Bad type");
4300 }
4301 assert(CPT && "RewriteBlockClass: Bad type");
John McCall9dd450b2009-09-21 23:43:11 +00004302 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004303 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004304 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004305 // FTP will be null for closures that don't take arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004306
Steve Naroff350b6652008-10-30 10:07:53 +00004307 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
4308 SourceLocation(),
4309 &Context->Idents.get("__block_impl"));
4310 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff677ab3a2008-10-27 17:20:55 +00004311
Steve Naroff350b6652008-10-30 10:07:53 +00004312 // Generate a funky cast.
4313 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00004314
Steve Naroff350b6652008-10-30 10:07:53 +00004315 // Push the block argument type.
4316 ArgTypes.push_back(PtrBlock);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004317 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004318 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff350b6652008-10-30 10:07:53 +00004319 E = FTP->arg_type_end(); I && (I != E); ++I) {
4320 QualType t = *I;
4321 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffa5c0db82008-12-11 21:05:33 +00004322 if (isTopLevelBlockPointerType(t)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004323 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroff350b6652008-10-30 10:07:53 +00004324 t = Context->getPointerType(BPT->getPointeeType());
4325 }
4326 ArgTypes.push_back(t);
4327 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004328 }
Steve Naroff350b6652008-10-30 10:07:53 +00004329 // Now do the pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00004330 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00004331 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0,
4332 false, false, 0, 0,
4333 false, CC_Default);
Mike Stump11289f42009-09-09 15:08:12 +00004334
Steve Naroff350b6652008-10-30 10:07:53 +00004335 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump11289f42009-09-09 15:08:12 +00004336
John McCall97513962010-01-15 18:39:57 +00004337 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4338 CastExpr::CK_Unknown,
4339 const_cast<Expr*>(BlockExp));
Steve Naroff350b6652008-10-30 10:07:53 +00004340 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00004341 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4342 BlkCast);
Steve Naroff350b6652008-10-30 10:07:53 +00004343 //PE->dump();
Mike Stump11289f42009-09-09 15:08:12 +00004344
Douglas Gregor91f84212008-12-11 16:49:14 +00004345 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00004346 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004347 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek5a201952009-02-07 01:47:29 +00004348 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4349 FD->getType());
Mike Stump11289f42009-09-09 15:08:12 +00004350
John McCall97513962010-01-15 18:39:57 +00004351 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4352 CastExpr::CK_Unknown, ME);
Ted Kremenek5a201952009-02-07 01:47:29 +00004353 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump11289f42009-09-09 15:08:12 +00004354
Steve Naroff350b6652008-10-30 10:07:53 +00004355 llvm::SmallVector<Expr*, 8> BlkExprs;
4356 // Add the implicit argument.
4357 BlkExprs.push_back(BlkCast);
4358 // Add the user arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004359 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004360 E = Exp->arg_end(); I != E; ++I) {
Steve Naroff350b6652008-10-30 10:07:53 +00004361 BlkExprs.push_back(*I);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004362 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004363 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4364 BlkExprs.size(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004365 Exp->getType(), SourceLocation());
Steve Naroff350b6652008-10-30 10:07:53 +00004366 return CE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004367}
4368
4369void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004370 Stmt *BlockCall = SynthesizeBlockCall(Exp, Exp->getCallee());
Steve Naroff350b6652008-10-30 10:07:53 +00004371 ReplaceStmt(Exp, BlockCall);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004372}
4373
Steve Naroffd9803712009-04-29 16:37:50 +00004374// We need to return the rewritten expression to handle cases where the
4375// BlockDeclRefExpr is embedded in another expression being rewritten.
4376// For example:
4377//
4378// int main() {
4379// __block Foo *f;
4380// __block int i;
Mike Stump11289f42009-09-09 15:08:12 +00004381//
Steve Naroffd9803712009-04-29 16:37:50 +00004382// void (^myblock)() = ^() {
4383// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4384// i = 77;
4385// };
4386//}
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004387Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanian25c07fa2009-12-23 19:26:34 +00004388 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004389 // for each DeclRefExp where BYREFVAR is name of the variable.
4390 ValueDecl *VD;
4391 bool isArrow = true;
4392 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4393 VD = BDRE->getDecl();
4394 else {
4395 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4396 isArrow = false;
4397 }
4398
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004399 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4400 &Context->Idents.get("__forwarding"),
4401 Context->VoidPtrTy, 0,
4402 /*BitWidth=*/0, /*Mutable=*/true);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004403 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4404 FD, SourceLocation(),
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004405 FD->getType());
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004406
4407 const char *Name = VD->getNameAsCString();
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004408 FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4409 &Context->Idents.get(Name),
4410 Context->VoidPtrTy, 0,
4411 /*BitWidth=*/0, /*Mutable=*/true);
4412 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004413 DeclRefExp->getType());
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004414
4415
4416
Steve Narofff26a1d42009-02-02 17:19:26 +00004417 // Need parens to enforce precedence.
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004418 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4419 ME);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004420 ReplaceStmt(DeclRefExp, PE);
Steve Naroffd9803712009-04-29 16:37:50 +00004421 return PE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004422}
4423
Steve Naroffc989a7b2008-11-03 23:29:32 +00004424void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4425 SourceLocation LocStart = CE->getLParenLoc();
4426 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofff4b992a2008-10-28 20:29:00 +00004427
4428 // Need to avoid trying to rewrite synthesized casts.
4429 if (LocStart.isInvalid())
4430 return;
Steve Naroff3e7ced12008-11-03 11:20:24 +00004431 // Need to avoid trying to rewrite casts contained in macros.
4432 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4433 return;
Mike Stump11289f42009-09-09 15:08:12 +00004434
Steve Naroff677ab3a2008-10-27 17:20:55 +00004435 const char *startBuf = SM->getCharacterData(LocStart);
4436 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00004437 QualType QT = CE->getType();
4438 const Type* TypePtr = QT->getAs<Type>();
4439 if (isa<TypeOfExprType>(TypePtr)) {
4440 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4441 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4442 std::string TypeAsString = "(";
Fariborz Jahanianf5067912010-02-18 01:20:22 +00004443 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00004444 TypeAsString += ")";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004445 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00004446 return;
4447 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004448 // advance the location to startArgList.
4449 const char *argPtr = startBuf;
Mike Stump11289f42009-09-09 15:08:12 +00004450
Steve Naroff677ab3a2008-10-27 17:20:55 +00004451 while (*argPtr++ && (argPtr < endBuf)) {
4452 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004453 case '^':
4454 // Replace the '^' with '*'.
4455 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004456 ReplaceText(LocStart, 1, "*");
Mike Stump281d6d72010-01-20 02:03:14 +00004457 break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004458 }
4459 }
4460 return;
4461}
4462
4463void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4464 SourceLocation DeclLoc = FD->getLocation();
4465 unsigned parenCount = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004466
Steve Naroff677ab3a2008-10-27 17:20:55 +00004467 // We have 1 or more arguments that have closure pointers.
4468 const char *startBuf = SM->getCharacterData(DeclLoc);
4469 const char *startArgList = strchr(startBuf, '(');
Mike Stump11289f42009-09-09 15:08:12 +00004470
Steve Naroff677ab3a2008-10-27 17:20:55 +00004471 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004472
Steve Naroff677ab3a2008-10-27 17:20:55 +00004473 parenCount++;
4474 // advance the location to startArgList.
4475 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4476 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump11289f42009-09-09 15:08:12 +00004477
Steve Naroff677ab3a2008-10-27 17:20:55 +00004478 const char *argPtr = startArgList;
Mike Stump11289f42009-09-09 15:08:12 +00004479
Steve Naroff677ab3a2008-10-27 17:20:55 +00004480 while (*argPtr++ && parenCount) {
4481 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004482 case '^':
4483 // Replace the '^' with '*'.
4484 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004485 ReplaceText(DeclLoc, 1, "*");
Mike Stump281d6d72010-01-20 02:03:14 +00004486 break;
4487 case '(':
4488 parenCount++;
4489 break;
4490 case ')':
4491 parenCount--;
4492 break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004493 }
4494 }
4495 return;
4496}
4497
4498bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004499 const FunctionProtoType *FTP;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004500 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004501 if (PT) {
John McCall9dd450b2009-09-21 23:43:11 +00004502 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004503 } else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004504 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004505 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall9dd450b2009-09-21 23:43:11 +00004506 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004507 }
4508 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004509 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004510 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +00004511 if (isTopLevelBlockPointerType(*I))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004512 return true;
4513 }
4514 return false;
4515}
4516
Ted Kremenek5a201952009-02-07 01:47:29 +00004517void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4518 const char *&RParen) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004519 const char *argPtr = strchr(Name, '(');
4520 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004521
Steve Naroff677ab3a2008-10-27 17:20:55 +00004522 LParen = argPtr; // output the start.
4523 argPtr++; // skip past the left paren.
4524 unsigned parenCount = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004525
Steve Naroff677ab3a2008-10-27 17:20:55 +00004526 while (*argPtr && parenCount) {
4527 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004528 case '(': parenCount++; break;
4529 case ')': parenCount--; break;
4530 default: break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004531 }
4532 if (parenCount) argPtr++;
4533 }
4534 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4535 RParen = argPtr; // output the end
4536}
4537
4538void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4539 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4540 RewriteBlockPointerFunctionArgs(FD);
4541 return;
Mike Stump11289f42009-09-09 15:08:12 +00004542 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004543 // Handle Variables and Typedefs.
4544 SourceLocation DeclLoc = ND->getLocation();
4545 QualType DeclT;
4546 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4547 DeclT = VD->getType();
4548 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4549 DeclT = TDD->getUnderlyingType();
4550 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4551 DeclT = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00004552 else
Steve Naroff677ab3a2008-10-27 17:20:55 +00004553 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump11289f42009-09-09 15:08:12 +00004554
Steve Naroff677ab3a2008-10-27 17:20:55 +00004555 const char *startBuf = SM->getCharacterData(DeclLoc);
4556 const char *endBuf = startBuf;
4557 // scan backward (from the decl location) for the end of the previous decl.
4558 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4559 startBuf--;
Mike Stump11289f42009-09-09 15:08:12 +00004560
Steve Naroff677ab3a2008-10-27 17:20:55 +00004561 // *startBuf != '^' if we are dealing with a pointer to function that
4562 // may take block argument types (which will be handled below).
4563 if (*startBuf == '^') {
4564 // Replace the '^' with '*', computing a negative offset.
4565 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004566 ReplaceText(DeclLoc, 1, "*");
Steve Naroff677ab3a2008-10-27 17:20:55 +00004567 }
4568 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4569 // Replace the '^' with '*' for arguments.
4570 DeclLoc = ND->getLocation();
4571 startBuf = SM->getCharacterData(DeclLoc);
4572 const char *argListBegin, *argListEnd;
4573 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4574 while (argListBegin < argListEnd) {
4575 if (*argListBegin == '^') {
4576 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004577 ReplaceText(CaretLoc, 1, "*");
Steve Naroff677ab3a2008-10-27 17:20:55 +00004578 }
4579 argListBegin++;
4580 }
4581 }
4582 return;
4583}
4584
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004585
4586/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4587/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4588/// struct Block_byref_id_object *src) {
4589/// _Block_object_assign (&_dest->object, _src->object,
4590/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4591/// [|BLOCK_FIELD_IS_WEAK]) // object
4592/// _Block_object_assign(&_dest->object, _src->object,
4593/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4594/// [|BLOCK_FIELD_IS_WEAK]) // block
4595/// }
4596/// And:
4597/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4598/// _Block_object_dispose(_src->object,
4599/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4600/// [|BLOCK_FIELD_IS_WEAK]) // object
4601/// _Block_object_dispose(_src->object,
4602/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4603/// [|BLOCK_FIELD_IS_WEAK]) // block
4604/// }
4605
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004606std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4607 int flag) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004608 std::string S;
Benjamin Kramere056cea2010-01-10 19:57:50 +00004609 if (CopyDestroyCache.count(flag))
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004610 return S;
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004611 CopyDestroyCache.insert(flag);
4612 S = "static void __Block_byref_id_object_copy_";
4613 S += utostr(flag);
4614 S += "(void *dst, void *src) {\n";
4615
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004616 // offset into the object pointer is computed as:
4617 // void * + void* + int + int + void* + void *
4618 unsigned IntSize =
4619 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4620 unsigned VoidPtrSize =
4621 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4622
4623 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/8;
4624 S += " _Block_object_assign((char*)dst + ";
4625 S += utostr(offset);
4626 S += ", *(void * *) ((char*)src + ";
4627 S += utostr(offset);
4628 S += "), ";
4629 S += utostr(flag);
4630 S += ");\n}\n";
4631
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004632 S += "static void __Block_byref_id_object_dispose_";
4633 S += utostr(flag);
4634 S += "(void *src) {\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004635 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4636 S += utostr(offset);
4637 S += "), ";
4638 S += utostr(flag);
4639 S += ");\n}\n";
4640 return S;
4641}
4642
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004643/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4644/// the declaration into:
4645/// struct __Block_byref_ND {
4646/// void *__isa; // NULL for everything except __weak pointers
4647/// struct __Block_byref_ND *__forwarding;
4648/// int32_t __flags;
4649/// int32_t __size;
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004650/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4651/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004652/// typex ND;
4653/// };
4654///
4655/// It then replaces declaration of ND variable with:
4656/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4657/// __size=sizeof(struct __Block_byref_ND),
4658/// ND=initializer-if-any};
4659///
4660///
4661void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004662 // Insert declaration for the function in which block literal is
4663 // used.
4664 if (CurFunctionDeclToDeclareForBlock)
4665 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004666 int flag = 0;
4667 int isa = 0;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004668 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4669 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian92368a12009-12-30 20:38:08 +00004670 SourceLocation X = ND->getLocEnd();
4671 X = SM->getInstantiationLoc(X);
4672 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004673 std::string Name(ND->getNameAsString());
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004674 std::string ByrefType;
4675 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004676 ByrefType += " {\n";
4677 ByrefType += " void *__isa;\n";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004678 RewriteByRefString(ByrefType, Name, ND);
4679 ByrefType += " *__forwarding;\n";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004680 ByrefType += " int __flags;\n";
4681 ByrefType += " int __size;\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004682 // Add void *__Block_byref_id_object_copy;
4683 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004684 QualType Ty = ND->getType();
4685 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4686 if (HasCopyAndDispose) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004687 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4688 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004689 }
4690
4691 Ty.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004692 ByrefType += " " + Name + ";\n";
4693 ByrefType += "};\n";
4694 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004695 SourceLocation FunLocStart;
4696 if (CurFunctionDef)
4697 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4698 else {
4699 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4700 FunLocStart = CurMethodDef->getLocStart();
4701 }
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004702 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004703 if (Ty.isObjCGCWeak()) {
4704 flag |= BLOCK_FIELD_IS_WEAK;
4705 isa = 1;
4706 }
4707
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004708 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004709 flag = BLOCK_BYREF_CALLER;
4710 QualType Ty = ND->getType();
4711 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4712 if (Ty->isBlockPointerType())
4713 flag |= BLOCK_FIELD_IS_BLOCK;
4714 else
4715 flag |= BLOCK_FIELD_IS_OBJECT;
4716 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004717 if (!HF.empty())
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004718 InsertText(FunLocStart, HF);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004719 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004720
4721 // struct __Block_byref_ND ND =
4722 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4723 // initializer-if-any};
4724 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanianf7945432010-01-05 18:15:57 +00004725 unsigned flags = 0;
4726 if (HasCopyAndDispose)
4727 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004728 Name = ND->getNameAsString();
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004729 ByrefType.clear();
4730 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004731 std::string ForwardingCastType("(");
4732 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004733 if (!hasInit) {
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004734 ByrefType += " " + Name + " = {(void*)";
4735 ByrefType += utostr(isa);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004736 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004737 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004738 ByrefType += ", ";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004739 ByrefType += "sizeof(";
4740 RewriteByRefString(ByrefType, Name, ND);
4741 ByrefType += ")";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004742 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004743 ByrefType += ", __Block_byref_id_object_copy_";
4744 ByrefType += utostr(flag);
4745 ByrefType += ", __Block_byref_id_object_dispose_";
4746 ByrefType += utostr(flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004747 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004748 ByrefType += "};\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004749 ReplaceText(DeclLoc, endBuf-startBuf+Name.size(), ByrefType);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004750 }
4751 else {
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004752 SourceLocation startLoc;
4753 Expr *E = ND->getInit();
4754 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4755 startLoc = ECE->getLParenLoc();
4756 else
4757 startLoc = E->getLocStart();
Fariborz Jahanianb8646ed2010-01-05 23:06:29 +00004758 startLoc = SM->getInstantiationLoc(startLoc);
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004759 endBuf = SM->getCharacterData(startLoc);
4760
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004761 ByrefType += " " + Name;
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004762 ByrefType += " = {(void*)";
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004763 ByrefType += utostr(isa);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004764 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004765 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004766 ByrefType += ", ";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004767 ByrefType += "sizeof(";
4768 RewriteByRefString(ByrefType, Name, ND);
4769 ByrefType += "), ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004770 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004771 ByrefType += "__Block_byref_id_object_copy_";
4772 ByrefType += utostr(flag);
4773 ByrefType += ", __Block_byref_id_object_dispose_";
4774 ByrefType += utostr(flag);
4775 ByrefType += ", ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004776 }
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004777 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroff13468372009-12-23 17:24:33 +00004778
4779 // Complete the newly synthesized compound expression by inserting a right
4780 // curly brace before the end of the declaration.
4781 // FIXME: This approach avoids rewriting the initializer expression. It
4782 // also assumes there is only one declarator. For example, the following
4783 // isn't currently supported by this routine (in general):
4784 //
4785 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4786 //
4787 const char *startBuf = SM->getCharacterData(startLoc);
4788 const char *semiBuf = strchr(startBuf, ';');
4789 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4790 SourceLocation semiLoc =
4791 startLoc.getFileLocWithOffset(semiBuf-startBuf);
4792
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004793 InsertText(semiLoc, "}");
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004794 }
Fariborz Jahanian81203462009-12-22 00:48:54 +00004795 return;
4796}
4797
Mike Stump11289f42009-09-09 15:08:12 +00004798void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004799 // Add initializers for any closure decl refs.
4800 GetBlockDeclRefExprs(Exp->getBody());
4801 if (BlockDeclRefs.size()) {
4802 // Unique all "by copy" declarations.
4803 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004804 if (!BlockDeclRefs[i]->isByRef()) {
4805 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4806 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4807 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4808 }
4809 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004810 // Unique all "by ref" declarations.
4811 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4812 if (BlockDeclRefs[i]->isByRef()) {
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004813 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4814 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4815 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4816 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004817 }
4818 // Find any imported blocks...they will need special attention.
4819 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00004820 if (BlockDeclRefs[i]->isByRef() ||
4821 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4822 BlockDeclRefs[i]->getType()->isBlockPointerType()) {
Steve Naroff832d8902008-11-13 17:40:07 +00004823 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004824 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4825 }
4826 }
4827}
4828
Steve Narofff4b992a2008-10-28 20:29:00 +00004829FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
4830 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004831 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Mike Stump11289f42009-09-09 15:08:12 +00004832 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00004833 ID, FType, 0, FunctionDecl::Extern, false,
Douglas Gregor739ef0c2009-02-25 16:33:18 +00004834 false);
Steve Narofff4b992a2008-10-28 20:29:00 +00004835}
4836
Steve Naroffd8907b72008-10-29 18:15:37 +00004837Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004838 Blocks.push_back(Exp);
4839
4840 CollectBlockDeclRefInfo(Exp);
4841 std::string FuncName;
Mike Stump11289f42009-09-09 15:08:12 +00004842
Steve Narofff4b992a2008-10-28 20:29:00 +00004843 if (CurFunctionDef)
Chris Lattnere4b95692008-11-24 03:33:13 +00004844 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00004845 else if (CurMethodDef)
4846 BuildUniqueMethodName(FuncName, CurMethodDef);
4847 else if (GlobalVarDecl)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004848 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump11289f42009-09-09 15:08:12 +00004849
Steve Narofff4b992a2008-10-28 20:29:00 +00004850 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump11289f42009-09-09 15:08:12 +00004851
Steve Narofff4b992a2008-10-28 20:29:00 +00004852 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4853 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump11289f42009-09-09 15:08:12 +00004854
Steve Narofff4b992a2008-10-28 20:29:00 +00004855 // Get a pointer to the function type so we can cast appropriately.
4856 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
4857
4858 FunctionDecl *FD;
4859 Expr *NewRep;
Mike Stump11289f42009-09-09 15:08:12 +00004860
Steve Narofff4b992a2008-10-28 20:29:00 +00004861 // Simulate a contructor call...
4862 FD = SynthBlockInitFunctionDecl(Tag.c_str());
Ted Kremenek5a201952009-02-07 01:47:29 +00004863 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004864
Steve Narofff4b992a2008-10-28 20:29:00 +00004865 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00004866
Steve Naroffe2514232008-10-29 21:23:59 +00004867 // Initialize the block function.
Steve Narofff4b992a2008-10-28 20:29:00 +00004868 FD = SynthBlockInitFunctionDecl(Func.c_str());
Ted Kremenek5a201952009-02-07 01:47:29 +00004869 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
4870 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00004871 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4872 CastExpr::CK_Unknown, Arg);
Mike Stump11289f42009-09-09 15:08:12 +00004873 InitExprs.push_back(castExpr);
4874
Steve Naroff30484702009-12-06 21:14:13 +00004875 // Initialize the block descriptor.
4876 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump11289f42009-09-09 15:08:12 +00004877
Steve Naroff30484702009-12-06 21:14:13 +00004878 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
4879 &Context->Idents.get(DescData.c_str()),
4880 Context->VoidPtrTy, 0,
4881 VarDecl::Static);
4882 UnaryOperator *DescRefExpr = new (Context) UnaryOperator(
4883 new (Context) DeclRefExpr(NewVD,
4884 Context->VoidPtrTy, SourceLocation()),
4885 UnaryOperator::AddrOf,
4886 Context->getPointerType(Context->VoidPtrTy),
4887 SourceLocation());
4888 InitExprs.push_back(DescRefExpr);
4889
Steve Narofff4b992a2008-10-28 20:29:00 +00004890 // Add initializers for any closure decl refs.
4891 if (BlockDeclRefs.size()) {
Steve Naroffe2514232008-10-29 21:23:59 +00004892 Expr *Exp;
Steve Narofff4b992a2008-10-28 20:29:00 +00004893 // Output all "by copy" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004894 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00004895 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004896 if (isObjCType((*I)->getType())) {
Steve Naroffe2514232008-10-29 21:23:59 +00004897 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner86d7d912008-11-24 03:54:41 +00004898 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004899 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroffa5c0db82008-12-11 21:05:33 +00004900 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Chris Lattner86d7d912008-11-24 03:54:41 +00004901 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004902 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
John McCall97513962010-01-15 18:39:57 +00004903 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4904 CastExpr::CK_Unknown, Arg);
Steve Narofff4b992a2008-10-28 20:29:00 +00004905 } else {
Chris Lattner86d7d912008-11-24 03:54:41 +00004906 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004907 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004908 }
Mike Stump11289f42009-09-09 15:08:12 +00004909 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00004910 }
4911 // Output all "by ref" declarations.
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004912 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00004913 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004914 ValueDecl *ND = (*I);
4915 std::string Name(ND->getNameAsString());
4916 std::string RecName;
4917 RewriteByRefString(RecName, Name, ND);
4918 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
4919 + sizeof("struct"));
4920 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
4921 SourceLocation(), II);
4922 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
4923 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
4924
Chris Lattner86d7d912008-11-24 03:54:41 +00004925 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004926 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4927 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00004928 Context->getPointerType(Exp->getType()),
Steve Naroffe2514232008-10-29 21:23:59 +00004929 SourceLocation());
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004930 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CastExpr::CK_Unknown, Exp);
Mike Stump11289f42009-09-09 15:08:12 +00004931 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00004932 }
4933 }
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00004934 if (ImportedBlockDecls.size()) {
4935 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4936 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff30484702009-12-06 21:14:13 +00004937 unsigned IntSize =
4938 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00004939 Expr *FlagExp = new (Context) IntegerLiteral(llvm::APInt(IntSize, flag),
4940 Context->IntTy, SourceLocation());
4941 InitExprs.push_back(FlagExp);
Steve Naroff30484702009-12-06 21:14:13 +00004942 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004943 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4944 FType, SourceLocation());
Ted Kremenek5a201952009-02-07 01:47:29 +00004945 NewRep = new (Context) UnaryOperator(NewRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00004946 Context->getPointerType(NewRep->getType()),
Steve Narofff4b992a2008-10-28 20:29:00 +00004947 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00004948 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CastExpr::CK_Unknown,
4949 NewRep);
Steve Narofff4b992a2008-10-28 20:29:00 +00004950 BlockDeclRefs.clear();
4951 BlockByRefDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004952 BlockByRefDeclsPtrSet.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00004953 BlockByCopyDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004954 BlockByCopyDeclsPtrSet.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00004955 ImportedBlockDecls.clear();
4956 return NewRep;
4957}
4958
4959//===----------------------------------------------------------------------===//
4960// Function Body / Expression rewriting
4961//===----------------------------------------------------------------------===//
4962
Steve Naroff4588d0f2008-12-04 16:24:46 +00004963// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
4964// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
4965// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
4966// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
4967// Since the rewriter isn't capable of rewriting rewritten code, it's important
4968// we get this right.
4969void RewriteObjC::CollectPropertySetters(Stmt *S) {
4970 // Perform a bottom up traversal of all children.
4971 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4972 CI != E; ++CI)
4973 if (*CI)
4974 CollectPropertySetters(*CI);
4975
4976 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
4977 if (BinOp->isAssignmentOp()) {
4978 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
4979 PropSetters[PRE] = BinOp;
4980 }
4981 }
4982}
4983
Steve Narofff4b992a2008-10-28 20:29:00 +00004984Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump11289f42009-09-09 15:08:12 +00004985 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00004986 isa<DoStmt>(S) || isa<ForStmt>(S))
4987 Stmts.push_back(S);
4988 else if (isa<ObjCForCollectionStmt>(S)) {
4989 Stmts.push_back(S);
Chris Lattnerb71980f2010-01-09 21:45:57 +00004990 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofff4b992a2008-10-28 20:29:00 +00004991 }
Mike Stump11289f42009-09-09 15:08:12 +00004992
Steve Narofff4b992a2008-10-28 20:29:00 +00004993 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004994
Steve Narofff4b992a2008-10-28 20:29:00 +00004995 // Perform a bottom up rewrite of all children.
4996 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4997 CI != E; ++CI)
4998 if (*CI) {
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00004999 Stmt *newStmt;
5000 Stmt *S = (*CI);
5001 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5002 Expr *OldBase = IvarRefExpr->getBase();
5003 bool replaced = false;
5004 newStmt = RewriteObjCNestedIvarRefExpr(S, replaced);
5005 if (replaced) {
5006 if (ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(newStmt))
5007 ReplaceStmt(OldBase, IRE->getBase());
5008 else
5009 ReplaceStmt(S, newStmt);
5010 }
5011 }
5012 else
5013 newStmt = RewriteFunctionBodyOrGlobalInitializer(S);
Mike Stump11289f42009-09-09 15:08:12 +00005014 if (newStmt)
Steve Narofff4b992a2008-10-28 20:29:00 +00005015 *CI = newStmt;
5016 }
Mike Stump11289f42009-09-09 15:08:12 +00005017
Steve Narofff4b992a2008-10-28 20:29:00 +00005018 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
5019 // Rewrite the block body in place.
5020 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Mike Stump11289f42009-09-09 15:08:12 +00005021
Steve Narofff4b992a2008-10-28 20:29:00 +00005022 // Now we snarf the rewritten text and stash it away for later use.
Ted Kremenekdb2ef372010-01-07 18:00:35 +00005023 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroffd8907b72008-10-29 18:15:37 +00005024 RewrittenBlockExprs[BE] = Str;
Mike Stump11289f42009-09-09 15:08:12 +00005025
Steve Narofff4b992a2008-10-28 20:29:00 +00005026 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
5027 //blockTranscribed->dump();
Steve Naroffd8907b72008-10-29 18:15:37 +00005028 ReplaceStmt(S, blockTranscribed);
Steve Narofff4b992a2008-10-28 20:29:00 +00005029 return blockTranscribed;
5030 }
5031 // Handle specific things.
5032 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5033 return RewriteAtEncode(AtEncode);
Mike Stump11289f42009-09-09 15:08:12 +00005034
Steve Naroff4588d0f2008-12-04 16:24:46 +00005035 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
5036 BinaryOperator *BinOp = PropSetters[PropRefExpr];
5037 if (BinOp) {
5038 // Because the rewriter doesn't allow us to rewrite rewritten code,
5039 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroff08628db2008-12-09 12:56:34 +00005040 DisableReplaceStmt = true;
5041 // Save the source range. Even if we disable the replacement, the
5042 // rewritten node will have been inserted into the tree. If the synthesized
5043 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump11289f42009-09-09 15:08:12 +00005044 // self.errorHandler = handler ? handler :
Steve Naroff08628db2008-12-09 12:56:34 +00005045 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
5046 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroff4588d0f2008-12-04 16:24:46 +00005047 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroff08628db2008-12-09 12:56:34 +00005048 DisableReplaceStmt = false;
Steve Naroff22216db2008-12-04 23:50:32 +00005049 //
5050 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
5051 // we changed the RHS of BinOp, the rewriter would fail (since it needs
5052 // to see the original expression). Consider this example:
5053 //
5054 // Foo *obj1, *obj2;
5055 //
5056 // obj1.i = [obj2 rrrr];
5057 //
5058 // 'BinOp' for the previous expression looks like:
5059 //
5060 // (BinaryOperator 0x231ccf0 'int' '='
5061 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
5062 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
5063 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
5064 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
5065 //
5066 // 'newStmt' represents the rewritten message expression. For example:
5067 //
5068 // (CallExpr 0x231d300 'id':'struct objc_object *'
5069 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
5070 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
5071 // (CStyleCastExpr 0x231d220 'void *'
5072 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
5073 //
5074 // Note that 'newStmt' is passed to RewritePropertySetter so that it
5075 // can be used as the setter argument. ReplaceStmt() will still 'see'
5076 // the original RHS (since we haven't altered BinOp).
5077 //
Mike Stump11289f42009-09-09 15:08:12 +00005078 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff22216db2008-12-04 23:50:32 +00005079 // node. As a result, we now leak the original AST nodes.
5080 //
Steve Naroff08628db2008-12-09 12:56:34 +00005081 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroff4588d0f2008-12-04 16:24:46 +00005082 } else {
5083 return RewritePropertyGetter(PropRefExpr);
Steve Narofff326f402008-12-03 00:56:33 +00005084 }
5085 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005086 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5087 return RewriteAtSelector(AtSelector);
Mike Stump11289f42009-09-09 15:08:12 +00005088
Steve Narofff4b992a2008-10-28 20:29:00 +00005089 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5090 return RewriteObjCStringLiteral(AtString);
Mike Stump11289f42009-09-09 15:08:12 +00005091
Steve Narofff4b992a2008-10-28 20:29:00 +00005092 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00005093#if 0
Steve Narofff4b992a2008-10-28 20:29:00 +00005094 // Before we rewrite it, put the original message expression in a comment.
5095 SourceLocation startLoc = MessExpr->getLocStart();
5096 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00005097
Steve Narofff4b992a2008-10-28 20:29:00 +00005098 const char *startBuf = SM->getCharacterData(startLoc);
5099 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump11289f42009-09-09 15:08:12 +00005100
Steve Narofff4b992a2008-10-28 20:29:00 +00005101 std::string messString;
5102 messString += "// ";
5103 messString.append(startBuf, endBuf-startBuf+1);
5104 messString += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00005105
5106 // FIXME: Missing definition of
Steve Narofff4b992a2008-10-28 20:29:00 +00005107 // InsertText(clang::SourceLocation, char const*, unsigned int).
5108 // InsertText(startLoc, messString.c_str(), messString.size());
5109 // Tried this, but it didn't work either...
5110 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroff4588d0f2008-12-04 16:24:46 +00005111#endif
Steve Narofff4b992a2008-10-28 20:29:00 +00005112 return RewriteMessageExpr(MessExpr);
5113 }
Mike Stump11289f42009-09-09 15:08:12 +00005114
Steve Narofff4b992a2008-10-28 20:29:00 +00005115 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5116 return RewriteObjCTryStmt(StmtTry);
5117
5118 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5119 return RewriteObjCSynchronizedStmt(StmtTry);
5120
5121 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5122 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump11289f42009-09-09 15:08:12 +00005123
Steve Narofff4b992a2008-10-28 20:29:00 +00005124 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5125 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump11289f42009-09-09 15:08:12 +00005126
5127 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofff4b992a2008-10-28 20:29:00 +00005128 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump11289f42009-09-09 15:08:12 +00005129 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofff4b992a2008-10-28 20:29:00 +00005130 OrigStmtRange.getEnd());
5131 if (BreakStmt *StmtBreakStmt =
5132 dyn_cast<BreakStmt>(S))
5133 return RewriteBreakStmt(StmtBreakStmt);
5134 if (ContinueStmt *StmtContinueStmt =
5135 dyn_cast<ContinueStmt>(S))
5136 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump11289f42009-09-09 15:08:12 +00005137
5138 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofff4b992a2008-10-28 20:29:00 +00005139 // and cast exprs.
5140 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5141 // FIXME: What we're doing here is modifying the type-specifier that
5142 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump11289f42009-09-09 15:08:12 +00005143 // a separate type-specifier that we can rewrite.
Steve Naroffe70a52a2009-12-05 15:55:59 +00005144 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5145 // the context of an ObjCForCollectionStmt. For example:
5146 // NSArray *someArray;
5147 // for (id <FooProtocol> index in someArray) ;
5148 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5149 // and it depends on the original text locations/positions.
Benjamin Krameracc5fa12009-12-05 22:16:51 +00005150 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
Steve Naroffe70a52a2009-12-05 15:55:59 +00005151 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump11289f42009-09-09 15:08:12 +00005152
Steve Narofff4b992a2008-10-28 20:29:00 +00005153 // Blocks rewrite rules.
5154 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5155 DI != DE; ++DI) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +00005156 Decl *SD = *DI;
Steve Narofff4b992a2008-10-28 20:29:00 +00005157 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005158 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005159 RewriteBlockPointerDecl(ND);
Mike Stump11289f42009-09-09 15:08:12 +00005160 else if (ND->getType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005161 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00005162 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005163 if (VD->hasAttr<BlocksAttr>()) {
5164 static unsigned uniqueByrefDeclCount = 0;
5165 assert(!BlockByRefDeclNo.count(ND) &&
5166 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5167 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005168 RewriteByRefVar(VD);
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005169 }
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00005170 else
5171 RewriteTypeOfDecl(VD);
5172 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005173 }
5174 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005175 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005176 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00005177 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005178 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5179 }
5180 }
5181 }
Mike Stump11289f42009-09-09 15:08:12 +00005182
Steve Narofff4b992a2008-10-28 20:29:00 +00005183 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5184 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump11289f42009-09-09 15:08:12 +00005185
5186 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00005187 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5188 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump11289f42009-09-09 15:08:12 +00005189 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5190 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005191 && "Statement stack mismatch");
5192 Stmts.pop_back();
5193 }
5194 // Handle blocks rewriting.
5195 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
5196 if (BDRE->isByRef())
Steve Naroffd9803712009-04-29 16:37:50 +00005197 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofff4b992a2008-10-28 20:29:00 +00005198 }
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005199 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5200 ValueDecl *VD = DRE->getDecl();
5201 if (VD->hasAttr<BlocksAttr>())
5202 return RewriteBlockDeclRefExpr(DRE);
5203 }
5204
Steve Narofff4b992a2008-10-28 20:29:00 +00005205 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroff350b6652008-10-30 10:07:53 +00005206 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00005207 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroff350b6652008-10-30 10:07:53 +00005208 ReplaceStmt(S, BlockCall);
5209 return BlockCall;
5210 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005211 }
Steve Naroffc989a7b2008-11-03 23:29:32 +00005212 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005213 RewriteCastExpr(CE);
5214 }
5215#if 0
5216 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Ted Kremenek5a201952009-02-07 01:47:29 +00005217 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00005218 // Get the new text.
5219 std::string SStr;
5220 llvm::raw_string_ostream Buf(SStr);
Eli Friedman0905f142009-05-30 05:19:26 +00005221 Replacement->printPretty(Buf, *Context);
Steve Narofff4b992a2008-10-28 20:29:00 +00005222 const std::string &Str = Buf.str();
5223
5224 printf("CAST = %s\n", &Str[0]);
5225 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5226 delete S;
5227 return Replacement;
5228 }
5229#endif
5230 // Return this stmt unmodified.
5231 return S;
5232}
5233
Steve Naroffe70a52a2009-12-05 15:55:59 +00005234void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
5235 for (RecordDecl::field_iterator i = RD->field_begin(),
5236 e = RD->field_end(); i != e; ++i) {
5237 FieldDecl *FD = *i;
5238 if (isTopLevelBlockPointerType(FD->getType()))
5239 RewriteBlockPointerDecl(FD);
5240 if (FD->getType()->isObjCQualifiedIdType() ||
5241 FD->getType()->isObjCQualifiedInterfaceType())
5242 RewriteObjCQualifiedInterfaceTypes(FD);
5243 }
5244}
5245
Steve Narofff4b992a2008-10-28 20:29:00 +00005246/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5247/// main file of the input.
5248void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5249 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffb1368882008-12-17 00:20:22 +00005250 if (FD->isOverloadedOperator())
5251 return;
Mike Stump11289f42009-09-09 15:08:12 +00005252
Steve Narofff4b992a2008-10-28 20:29:00 +00005253 // Since function prototypes don't have ParmDecl's, we check the function
5254 // prototype. This enables us to rewrite function declarations and
5255 // definitions using the same code.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005256 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005257
Sebastian Redla7b98a72009-04-26 20:35:05 +00005258 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00005259 if (CompoundStmt *Body = FD->getCompoundBody()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005260 CurFunctionDef = FD;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00005261 CurFunctionDeclToDeclareForBlock = FD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005262 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005263 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00005264 Body =
5265 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5266 FD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005267 CurrentBody = 0;
5268 if (PropParentMap) {
5269 delete PropParentMap;
5270 PropParentMap = 0;
5271 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005272 // This synthesizes and inserts the block "impl" struct, invoke function,
5273 // and any copy/dispose helper functions.
5274 InsertBlockLiteralsWithinFunction(FD);
5275 CurFunctionDef = 0;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00005276 CurFunctionDeclToDeclareForBlock = 0;
Mike Stump11289f42009-09-09 15:08:12 +00005277 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005278 return;
5279 }
5280 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00005281 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005282 CurMethodDef = MD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005283 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005284 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00005285 Body =
5286 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5287 MD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005288 CurrentBody = 0;
5289 if (PropParentMap) {
5290 delete PropParentMap;
5291 PropParentMap = 0;
5292 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005293 InsertBlockLiteralsWithinMethod(MD);
5294 CurMethodDef = 0;
5295 }
5296 }
5297 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5298 ClassImplementation.push_back(CI);
5299 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5300 CategoryImplementation.push_back(CI);
5301 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
5302 RewriteForwardClassDecl(CD);
5303 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5304 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroffa5c0db82008-12-11 21:05:33 +00005305 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005306 RewriteBlockPointerDecl(VD);
Steve Naroffd8907b72008-10-29 18:15:37 +00005307 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005308 CheckFunctionPointerDecl(VD->getType(), VD);
5309 if (VD->getInit()) {
Steve Naroffc989a7b2008-11-03 23:29:32 +00005310 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005311 RewriteCastExpr(CE);
5312 }
5313 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00005314 } else if (VD->getType()->isRecordType()) {
5315 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5316 if (RD->isDefinition())
5317 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005318 }
Steve Naroffd8907b72008-10-29 18:15:37 +00005319 if (VD->getInit()) {
5320 GlobalVarDecl = VD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005321 CollectPropertySetters(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00005322 CurrentBody = VD->getInit();
Steve Naroffd8907b72008-10-29 18:15:37 +00005323 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00005324 CurrentBody = 0;
5325 if (PropParentMap) {
5326 delete PropParentMap;
5327 PropParentMap = 0;
5328 }
Mike Stump11289f42009-09-09 15:08:12 +00005329 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner86d7d912008-11-24 03:54:41 +00005330 VD->getNameAsCString());
Steve Naroffd8907b72008-10-29 18:15:37 +00005331 GlobalVarDecl = 0;
5332
5333 // This is needed for blocks.
Steve Naroffc989a7b2008-11-03 23:29:32 +00005334 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroffd8907b72008-10-29 18:15:37 +00005335 RewriteCastExpr(CE);
5336 }
5337 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005338 return;
5339 }
5340 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005341 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005342 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00005343 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005344 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
Steve Naroffe70a52a2009-12-05 15:55:59 +00005345 else if (TD->getUnderlyingType()->isRecordType()) {
5346 RecordDecl *RD = TD->getUnderlyingType()->getAs<RecordType>()->getDecl();
5347 if (RD->isDefinition())
5348 RewriteRecordBody(RD);
5349 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005350 return;
5351 }
5352 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroffe70a52a2009-12-05 15:55:59 +00005353 if (RD->isDefinition())
5354 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005355 return;
5356 }
5357 // Nothing yet.
5358}
5359
Chris Lattnercf169832009-03-28 04:11:33 +00005360void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005361 if (Diags.hasErrorOccurred())
5362 return;
Mike Stump11289f42009-09-09 15:08:12 +00005363
Steve Narofff4b992a2008-10-28 20:29:00 +00005364 RewriteInclude();
Mike Stump11289f42009-09-09 15:08:12 +00005365
Steve Naroffd9803712009-04-29 16:37:50 +00005366 // Here's a great place to add any extra declarations that may be needed.
5367 // Write out meta data for each @protocol(<expr>).
Mike Stump11289f42009-09-09 15:08:12 +00005368 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00005369 E = ProtocolExprDecls.end(); I != E; ++I)
5370 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5371
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005372 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005373 if (ClassImplementation.size() || CategoryImplementation.size())
5374 RewriteImplementations();
Steve Naroffd9803712009-04-29 16:37:50 +00005375
Steve Narofff4b992a2008-10-28 20:29:00 +00005376 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5377 // we are done.
Mike Stump11289f42009-09-09 15:08:12 +00005378 if (const RewriteBuffer *RewriteBuf =
Steve Narofff4b992a2008-10-28 20:29:00 +00005379 Rewrite.getRewriteBufferFor(MainFileID)) {
5380 //printf("Changed:\n");
5381 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5382 } else {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005383 llvm::errs() << "No changes\n";
Steve Narofff4b992a2008-10-28 20:29:00 +00005384 }
Steve Narofff8cfd162008-11-13 20:07:04 +00005385
Steve Naroffd9803712009-04-29 16:37:50 +00005386 if (ClassImplementation.size() || CategoryImplementation.size() ||
5387 ProtocolExprDecls.size()) {
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005388 // Rewrite Objective-c meta data*
5389 std::string ResultStr;
5390 SynthesizeMetaDataIntoBuffer(ResultStr);
5391 // Emit metadata.
5392 *OutFile << ResultStr;
5393 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005394 OutFile->flush();
5395}
5396