blob: f5ff5bc3f228809b0a4a424d195331cb48316a4e [file] [log] [blame]
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
Chris Lattnere99c8322007-10-11 00:43:27 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnere99c8322007-10-11 00:43:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
Eli Friedman9f30fc32009-05-18 22:50:54 +000014#include "clang/Frontend/ASTConsumers.h"
Chris Lattner16a0de42007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattnere99c8322007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Steve Naroff1042ff32008-12-08 16:43:47 +000018#include "clang/AST/ParentMap.h"
Chris Lattner16a0de42007-10-11 18:38:32 +000019#include "clang/Basic/SourceManager.h"
Steve Naroffdb1ab1c2007-10-23 23:50:29 +000020#include "clang/Basic/IdentifierTable.h"
Chris Lattner4431a1b2007-11-30 22:53:43 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattnerf3a59a12007-12-02 01:13:47 +000022#include "clang/Lex/Lexer.h"
Benjamin Kramer89b422c2009-08-23 12:08:50 +000023#include "llvm/Support/MemoryBuffer.h"
24#include "llvm/Support/raw_ostream.h"
Chris Lattner211f8b82007-10-25 17:07:24 +000025#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian99e96b02007-10-26 19:46:17 +000026#include "llvm/ADT/SmallPtrSet.h"
Ted Kremenek2d470fc2008-09-13 05:16:45 +000027#include "llvm/ADT/OwningPtr.h"
Fariborz Jahaniane3891582010-01-05 18:04:40 +000028#include "llvm/ADT/DenseSet.h"
Chris Lattnere99c8322007-10-11 00:43:27 +000029using namespace clang;
Chris Lattner211f8b82007-10-25 17:07:24 +000030using llvm::utostr;
Chris Lattnere99c8322007-10-11 00:43:27 +000031
Chris Lattnere99c8322007-10-11 00:43:27 +000032namespace {
Steve Naroff1dc53ef2008-04-14 22:03:09 +000033 class RewriteObjC : public ASTConsumer {
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +000034 enum {
35 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
36 block, ... */
37 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
38 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
39 __block variable */
40 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
41 helpers */
42 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
43 support routines */
44 BLOCK_BYREF_CURRENT_MAX = 256
45 };
46
47 enum {
48 BLOCK_NEEDS_FREE = (1 << 24),
49 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
50 BLOCK_HAS_CXX_OBJ = (1 << 26),
51 BLOCK_IS_GC = (1 << 27),
52 BLOCK_IS_GLOBAL = (1 << 28),
53 BLOCK_HAS_DESCRIPTOR = (1 << 29)
54 };
55
Chris Lattner0bd1c972007-10-16 21:07:07 +000056 Rewriter Rewrite;
Chris Lattnere9c810c2007-11-30 22:25:36 +000057 Diagnostic &Diags;
Steve Naroff945a3b12008-03-10 20:43:59 +000058 const LangOptions &LangOpts;
Steve Naroff7b3579b2008-01-30 19:17:43 +000059 unsigned RewriteFailedDiag;
Steve Naroff6d6da252008-12-05 17:03:39 +000060 unsigned TryFinallyContainsReturnDiag;
Mike Stump11289f42009-09-09 15:08:12 +000061
Chris Lattnerc6d91c02007-10-17 22:35:30 +000062 ASTContext *Context;
Chris Lattnere99c8322007-10-11 00:43:27 +000063 SourceManager *SM;
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +000064 TranslationUnitDecl *TUDecl;
Chris Lattnerd32480d2009-01-17 06:22:33 +000065 FileID MainFileID;
Chris Lattnerf3a59a12007-12-02 01:13:47 +000066 const char *MainFileStart, *MainFileEnd;
Chris Lattner0bd1c972007-10-16 21:07:07 +000067 SourceLocation LastIncLoc;
Mike Stump11289f42009-09-09 15:08:12 +000068
Ted Kremenek1b0ea822008-01-07 19:49:32 +000069 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
70 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
71 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Naroff13e74872008-05-06 18:26:51 +000072 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremenek1b0ea822008-01-07 19:49:32 +000073 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
74 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +000075 llvm::SmallVector<Stmt *, 32> Stmts;
76 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroffd9803712009-04-29 16:37:50 +000077 // Remember all the @protocol(<expr>) expressions.
78 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Fariborz Jahaniane3891582010-01-05 18:04:40 +000079
80 llvm::DenseSet<uint64_t> CopyDestroyCache;
81
Steve Naroffce8e8862008-03-15 00:55:56 +000082 unsigned NumObjCStringLiterals;
Mike Stump11289f42009-09-09 15:08:12 +000083
Steve Naroffdb1ab1c2007-10-23 23:50:29 +000084 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff7fa2f042007-11-15 10:28:18 +000085 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +000086 FunctionDecl *MsgSendStretFunctionDecl;
87 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanian4f76f222007-12-03 21:26:48 +000088 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +000089 FunctionDecl *GetClassFunctionDecl;
Steve Naroffb2f8ff12007-12-07 03:50:46 +000090 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff574440f2007-10-24 22:48:43 +000091 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff265a6b92007-11-08 14:30:50 +000092 FunctionDecl *CFStringFunctionDecl;
Steve Naroff17978c42008-03-11 17:37:02 +000093 FunctionDecl *SuperContructorFunctionDecl;
Mike Stump11289f42009-09-09 15:08:12 +000094
Steve Naroffa397efd2007-11-03 11:27:19 +000095 // ObjC string constant support.
Steve Naroff08899ff2008-04-15 22:42:06 +000096 VarDecl *ConstantStringClassReference;
Steve Naroffa397efd2007-11-03 11:27:19 +000097 RecordDecl *NSStringRecord;
Mike Stump11289f42009-09-09 15:08:12 +000098
Fariborz Jahanian19d42bf2008-01-16 00:09:11 +000099 // ObjC foreach break/continue generation support.
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +0000100 int BcLabelCount;
Mike Stump11289f42009-09-09 15:08:12 +0000101
Steve Naroff7fa2f042007-11-15 10:28:18 +0000102 // Needed for super.
Steve Naroff677ab3a2008-10-27 17:20:55 +0000103 ObjCMethodDecl *CurMethodDef;
Steve Naroff7fa2f042007-11-15 10:28:18 +0000104 RecordDecl *SuperStructDecl;
Steve Naroffce8e8862008-03-15 00:55:56 +0000105 RecordDecl *ConstantStringDecl;
Mike Stump11289f42009-09-09 15:08:12 +0000106
Steve Naroffd9803712009-04-29 16:37:50 +0000107 TypeDecl *ProtocolTypeDecl;
108 QualType getProtocolType();
Mike Stump11289f42009-09-09 15:08:12 +0000109
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000110 // Needed for header files being rewritten
111 bool IsHeader;
Mike Stump11289f42009-09-09 15:08:12 +0000112
Steve Narofff9e7c902008-03-28 22:26:09 +0000113 std::string InFileName;
Eli Friedman94cf21e2009-05-18 22:20:00 +0000114 llvm::raw_ostream* OutFile;
Eli Friedmanf22439a2009-05-18 22:39:16 +0000115
116 bool SilenceRewriteMacroWarning;
Fariborz Jahanianbc6811c2010-01-07 22:51:18 +0000117 bool objc_impl_method;
Eli Friedmanf22439a2009-05-18 22:39:16 +0000118
Steve Naroff00a31762008-03-27 22:29:16 +0000119 std::string Preamble;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000120
121 // Block expressions.
122 llvm::SmallVector<BlockExpr *, 32> Blocks;
123 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
124 llvm::DenseMap<BlockDeclRefExpr *, CallExpr *> BlockCallExprs;
Mike Stump11289f42009-09-09 15:08:12 +0000125
Steve Naroff677ab3a2008-10-27 17:20:55 +0000126 // Block related declarations.
127 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDecls;
128 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDecls;
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +0000129 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000130 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
131
132 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
133
Steve Naroff4588d0f2008-12-04 16:24:46 +0000134 // This maps a property to it's assignment statement.
135 llvm::DenseMap<ObjCPropertyRefExpr *, BinaryOperator *> PropSetters;
Steve Naroff1042ff32008-12-08 16:43:47 +0000136 // This maps a property to it's synthesied message expression.
137 // This allows us to rewrite chained getters (e.g. o.a.b.c).
138 llvm::DenseMap<ObjCPropertyRefExpr *, Stmt *> PropGetters;
Mike Stump11289f42009-09-09 15:08:12 +0000139
Steve Naroff22216db2008-12-04 23:50:32 +0000140 // This maps an original source AST to it's rewritten form. This allows
141 // us to avoid rewriting the same node twice (which is very uncommon).
142 // This is needed to support some of the exotic property rewriting.
143 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Narofff326f402008-12-03 00:56:33 +0000144
Steve Naroff677ab3a2008-10-27 17:20:55 +0000145 FunctionDecl *CurFunctionDef;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000146 FunctionDecl *CurFunctionDeclToDeclareForBlock;
Steve Naroffd8907b72008-10-29 18:15:37 +0000147 VarDecl *GlobalVarDecl;
Mike Stump11289f42009-09-09 15:08:12 +0000148
Steve Naroff08628db2008-12-09 12:56:34 +0000149 bool DisableReplaceStmt;
Mike Stump11289f42009-09-09 15:08:12 +0000150
Fariborz Jahanian93191af2007-10-18 19:23:00 +0000151 static const int OBJC_ABI_VERSION =7 ;
Chris Lattnere99c8322007-10-11 00:43:27 +0000152 public:
Ted Kremenek380df932008-05-31 20:11:04 +0000153 virtual void Initialize(ASTContext &context);
154
Chris Lattner3c799d72007-10-24 17:06:59 +0000155 // Top Level Driver code.
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000156 virtual void HandleTopLevelDecl(DeclGroupRef D) {
157 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I)
158 HandleTopLevelSingleDecl(*I);
159 }
160 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000161 void HandleDeclInMainFile(Decl *D);
Eli Friedman94cf21e2009-05-18 22:20:00 +0000162 RewriteObjC(std::string inFile, llvm::raw_ostream *OS,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000163 Diagnostic &D, const LangOptions &LOpts,
164 bool silenceMacroWarn);
Ted Kremenek6231e7e2008-08-08 04:15:52 +0000165
166 ~RewriteObjC() {}
Mike Stump11289f42009-09-09 15:08:12 +0000167
Chris Lattnercf169832009-03-28 04:11:33 +0000168 virtual void HandleTranslationUnit(ASTContext &C);
Mike Stump11289f42009-09-09 15:08:12 +0000169
Fariborz Jahaniana7e1dcd2010-02-05 16:43:40 +0000170 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff22216db2008-12-04 23:50:32 +0000171 Stmt *ReplacingStmt = ReplacedNodes[Old];
Mike Stump11289f42009-09-09 15:08:12 +0000172
Steve Naroff22216db2008-12-04 23:50:32 +0000173 if (ReplacingStmt)
174 return; // We can't rewrite the same node twice.
Chris Lattner2e0d2602008-01-31 19:37:57 +0000175
Steve Naroff08628db2008-12-09 12:56:34 +0000176 if (DisableReplaceStmt)
177 return; // Used when rewriting the assignment of a property setter.
178
Steve Naroff22216db2008-12-04 23:50:32 +0000179 // If replacement succeeded or warning disabled return with no warning.
Fariborz Jahaniana7e1dcd2010-02-05 16:43:40 +0000180 if (!Rewrite.ReplaceStmt(Old, New)) {
Steve Naroff22216db2008-12-04 23:50:32 +0000181 ReplacedNodes[Old] = New;
182 return;
183 }
184 if (SilenceRewriteMacroWarning)
185 return;
Chris Lattner8488c822008-11-18 07:04:44 +0000186 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
187 << Old->getSourceRange();
Chris Lattner2e0d2602008-01-31 19:37:57 +0000188 }
Steve Naroff08628db2008-12-09 12:56:34 +0000189
190 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
191 // Measaure the old text.
192 int Size = Rewrite.getRangeSize(SrcRange);
193 if (Size == -1) {
194 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
195 << Old->getSourceRange();
196 return;
197 }
198 // Get the new text.
199 std::string SStr;
200 llvm::raw_string_ostream S(SStr);
Chris Lattnerc61089a2009-06-30 01:26:17 +0000201 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
Steve Naroff08628db2008-12-09 12:56:34 +0000202 const std::string &Str = S.str();
203
204 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbardec484a2009-08-19 19:10:30 +0000205 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroff08628db2008-12-09 12:56:34 +0000206 ReplacedNodes[Old] = New;
207 return;
208 }
209 if (SilenceRewriteMacroWarning)
210 return;
211 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
212 << Old->getSourceRange();
213 }
214
Steve Naroff00a31762008-03-27 22:29:16 +0000215 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
216 bool InsertAfter = true) {
Chris Lattner9cc55f52008-01-31 19:51:04 +0000217 // If insertion succeeded or warning disabled return with no warning.
Daniel Dunbardec484a2009-08-19 19:10:30 +0000218 if (!Rewrite.InsertText(Loc, llvm::StringRef(StrData, StrLen),
219 InsertAfter) ||
Chris Lattner1780a852008-01-31 19:42:41 +0000220 SilenceRewriteMacroWarning)
221 return;
Mike Stump11289f42009-09-09 15:08:12 +0000222
Chris Lattner1780a852008-01-31 19:42:41 +0000223 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
224 }
Mike Stump11289f42009-09-09 15:08:12 +0000225
Chris Lattner9cc55f52008-01-31 19:51:04 +0000226 void RemoveText(SourceLocation Loc, unsigned StrLen) {
227 // If removal succeeded or warning disabled return with no warning.
228 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
229 return;
Mike Stump11289f42009-09-09 15:08:12 +0000230
Chris Lattner9cc55f52008-01-31 19:51:04 +0000231 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
232 }
Chris Lattner3c799d72007-10-24 17:06:59 +0000233
Chris Lattner9cc55f52008-01-31 19:51:04 +0000234 void ReplaceText(SourceLocation Start, unsigned OrigLength,
235 const char *NewStr, unsigned NewLength) {
236 // If removal succeeded or warning disabled return with no warning.
Daniel Dunbardec484a2009-08-19 19:10:30 +0000237 if (!Rewrite.ReplaceText(Start, OrigLength,
238 llvm::StringRef(NewStr, NewLength)) ||
Chris Lattner9cc55f52008-01-31 19:51:04 +0000239 SilenceRewriteMacroWarning)
240 return;
Mike Stump11289f42009-09-09 15:08:12 +0000241
Chris Lattner9cc55f52008-01-31 19:51:04 +0000242 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
243 }
Mike Stump11289f42009-09-09 15:08:12 +0000244
Chris Lattner3c799d72007-10-24 17:06:59 +0000245 // Syntactic Rewriting.
Steve Narofff36987c2007-11-04 22:37:50 +0000246 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian80258362008-01-19 00:30:35 +0000247 void RewriteInclude();
Chris Lattner3c799d72007-10-24 17:06:59 +0000248 void RewriteTabs();
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000249 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffc038b3a2008-12-02 17:36:43 +0000250 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
251 ObjCImplementationDecl *IMD,
252 ObjCCategoryImplDecl *CID);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000253 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000254 void RewriteImplementationDecl(Decl *Dcl);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000255 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +0000256 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
257 ValueDecl *VD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000258 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
259 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
260 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
261 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000262 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000263 void RewriteFunctionDecl(FunctionDecl *FD);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000264 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000265 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroff873bd842008-07-29 18:15:38 +0000266 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroff50d42052007-11-01 13:24:47 +0000267 bool needToScanForQualifiers(QualType T);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000268 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff7fa2f042007-11-15 10:28:18 +0000269 QualType getSuperStructType();
Steve Naroffce8e8862008-03-15 00:55:56 +0000270 QualType getConstantStringStructType();
Steve Naroffcd92aeb2008-05-31 14:15:04 +0000271 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Mike Stump11289f42009-09-09 15:08:12 +0000272
Chris Lattner3c799d72007-10-24 17:06:59 +0000273 // Expression Rewriting.
Steve Naroff20113382007-11-09 15:20:18 +0000274 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroff4588d0f2008-12-04 16:24:46 +0000275 void CollectPropertySetters(Stmt *S);
Mike Stump11289f42009-09-09 15:08:12 +0000276
Steve Naroff1042ff32008-12-08 16:43:47 +0000277 Stmt *CurrentBody;
278 ParentMap *PropParentMap; // created lazily.
Mike Stump11289f42009-09-09 15:08:12 +0000279
Chris Lattner69534692007-10-24 16:57:36 +0000280 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Fariborz Jahanian80fadb52010-02-05 01:35:00 +0000281 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart,
282 bool &replaced);
283 Stmt *RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced);
Steve Naroff4588d0f2008-12-04 16:24:46 +0000284 Stmt *RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr);
Mike Stump11289f42009-09-09 15:08:12 +0000285 Stmt *RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroff08628db2008-12-09 12:56:34 +0000286 SourceRange SrcRange);
Steve Naroffe4f9b232007-11-05 14:50:49 +0000287 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner69534692007-10-24 16:57:36 +0000288 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffa397efd2007-11-03 11:27:19 +0000289 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian33c0e812007-12-07 18:47:10 +0000290 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffec60b432009-12-05 21:43:12 +0000291 void WarnAboutReturnGotoStmts(Stmt *S);
292 void HasReturnStmts(Stmt *S, bool &hasReturns);
293 void RewriteTryReturnStmts(Stmt *S);
294 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000295 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian284011b2008-01-29 22:59:37 +0000296 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000297 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
298 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
299 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattnera779d692008-01-31 05:10:40 +0000300 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
301 SourceLocation OrigEnd);
Mike Stump11289f42009-09-09 15:08:12 +0000302 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
Steve Naroff574440f2007-10-24 22:48:43 +0000303 Expr **args, unsigned nargs);
Fariborz Jahanian965a8962008-01-08 22:06:28 +0000304 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +0000305 Stmt *RewriteBreakStmt(BreakStmt *S);
306 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian965a8962008-01-08 22:06:28 +0000307 void SynthCountByEnumWithState(std::string &buf);
Mike Stump11289f42009-09-09 15:08:12 +0000308
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000309 void SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +0000310 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +0000311 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +0000312 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +0000313 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000314 void SynthGetClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +0000315 void SynthGetMetaClassFunctionDecl();
Fariborz Jahanian31e18502007-12-04 21:47:40 +0000316 void SynthSelGetUidFunctionDecl();
Steve Naroff17978c42008-03-11 17:37:02 +0000317 void SynthSuperContructorFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000318
Chris Lattner3c799d72007-10-24 17:06:59 +0000319 // Metadata emission.
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000320 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +0000321 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000322
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000323 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +0000324 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000325
Douglas Gregor29bd76f2009-04-23 01:02:12 +0000326 template<typename MethodIterator>
327 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
328 MethodIterator MethodEnd,
Fariborz Jahanian3df412a2007-10-25 00:14:44 +0000329 bool IsInstanceMethod,
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +0000330 const char *prefix,
Chris Lattner211f8b82007-10-25 17:07:24 +0000331 const char *ClassName,
332 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000333
Steve Naroffd9803712009-04-29 16:37:50 +0000334 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
335 const char *prefix,
336 const char *ClassName,
337 std::string &Result);
338 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
Mike Stump11289f42009-09-09 15:08:12 +0000339 const char *prefix,
Steve Naroffd9803712009-04-29 16:37:50 +0000340 const char *ClassName,
341 std::string &Result);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000342 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +0000343 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000344 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
345 ObjCIvarDecl *ivar,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +0000346 std::string &Result);
Steve Narofff8cfd162008-11-13 20:07:04 +0000347 void RewriteImplementations();
348 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000349
Steve Naroff677ab3a2008-10-27 17:20:55 +0000350 // Block rewriting.
Mike Stump11289f42009-09-09 15:08:12 +0000351 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000352 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
Mike Stump11289f42009-09-09 15:08:12 +0000353
Steve Naroff677ab3a2008-10-27 17:20:55 +0000354 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
355 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
Mike Stump11289f42009-09-09 15:08:12 +0000356
357 // Block specific rewrite rules.
Steve Naroff677ab3a2008-10-27 17:20:55 +0000358 void RewriteBlockCall(CallExpr *Exp);
359 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian02e07732009-12-23 02:07:37 +0000360 void RewriteByRefVar(VarDecl *VD);
Fariborz Jahaniane3891582010-01-05 18:04:40 +0000361 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +0000362 Stmt *RewriteBlockDeclRefExpr(Expr *VD);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000363 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Mike Stump11289f42009-09-09 15:08:12 +0000364
365 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Steve Naroff677ab3a2008-10-27 17:20:55 +0000366 const char *funcName, std::string Tag);
Mike Stump11289f42009-09-09 15:08:12 +0000367 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Steve Naroff677ab3a2008-10-27 17:20:55 +0000368 const char *funcName, std::string Tag);
Steve Naroff30484702009-12-06 21:14:13 +0000369 std::string SynthesizeBlockImpl(BlockExpr *CE,
370 std::string Tag, std::string Desc);
371 std::string SynthesizeBlockDescriptor(std::string DescTag,
372 std::string ImplTag,
373 int i, const char *funcName,
374 unsigned hasCopy);
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +0000375 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000376 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000377 const char *FunName);
Steve Naroffe70a52a2009-12-05 15:55:59 +0000378 void RewriteRecordBody(RecordDecl *RD);
Mike Stump11289f42009-09-09 15:08:12 +0000379
Steve Naroff677ab3a2008-10-27 17:20:55 +0000380 void CollectBlockDeclRefInfo(BlockExpr *Exp);
381 void GetBlockCallExprs(Stmt *S);
382 void GetBlockDeclRefExprs(Stmt *S);
Mike Stump11289f42009-09-09 15:08:12 +0000383
Steve Naroff677ab3a2008-10-27 17:20:55 +0000384 // We avoid calling Type::isBlockPointerType(), since it operates on the
385 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek5a201952009-02-07 01:47:29 +0000386 bool isTopLevelBlockPointerType(QualType T) {
387 return isa<BlockPointerType>(T);
388 }
Mike Stump11289f42009-09-09 15:08:12 +0000389
Steve Naroff677ab3a2008-10-27 17:20:55 +0000390 // FIXME: This predicate seems like it would be useful to add to ASTContext.
391 bool isObjCType(QualType T) {
392 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
393 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000394
Steve Naroff677ab3a2008-10-27 17:20:55 +0000395 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000396
Steve Naroff677ab3a2008-10-27 17:20:55 +0000397 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
398 OCT == Context->getCanonicalType(Context->getObjCClassType()))
399 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000400
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000401 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump11289f42009-09-09 15:08:12 +0000402 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Narofffb4330f2009-06-17 22:40:22 +0000403 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff677ab3a2008-10-27 17:20:55 +0000404 return true;
405 }
406 return false;
407 }
408 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Ted Kremenek5a201952009-02-07 01:47:29 +0000409 void GetExtentOfArgList(const char *Name, const char *&LParen,
410 const char *&RParen);
Steve Naroffc989a7b2008-11-03 23:29:32 +0000411 void RewriteCastExpr(CStyleCastExpr *CE);
Mike Stump11289f42009-09-09 15:08:12 +0000412
Steve Narofff4b992a2008-10-28 20:29:00 +0000413 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Steve Naroffd8907b72008-10-29 18:15:37 +0000414 Stmt *SynthBlockInitExpr(BlockExpr *Exp);
Mike Stump11289f42009-09-09 15:08:12 +0000415
Steve Naroffd9803712009-04-29 16:37:50 +0000416 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump11289f42009-09-09 15:08:12 +0000417 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroffd9803712009-04-29 16:37:50 +0000418 if (From[i] == '"')
419 To += "\\\"";
420 else
421 To += From[i];
422 }
423 }
Chris Lattnere99c8322007-10-11 00:43:27 +0000424 };
John McCall97513962010-01-15 18:39:57 +0000425
426 // Helper function: create a CStyleCastExpr with trivial type source info.
427 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
428 CastExpr::CastKind Kind, Expr *E) {
429 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
430 return new (Ctx) CStyleCastExpr(Ty, Kind, E, TInfo,
431 SourceLocation(), SourceLocation());
432 }
Chris Lattnere99c8322007-10-11 00:43:27 +0000433}
434
Mike Stump11289f42009-09-09 15:08:12 +0000435void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
436 NamedDecl *D) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000437 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000438 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +0000439 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +0000440 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff677ab3a2008-10-27 17:20:55 +0000441 // All the args are checked/rewritten. Don't call twice!
442 RewriteBlockPointerDecl(D);
443 break;
444 }
445 }
446}
447
448void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000449 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +0000450 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000451 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000452}
453
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000454static bool IsHeaderFile(const std::string &Filename) {
455 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump11289f42009-09-09 15:08:12 +0000456
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000457 if (DotPos == std::string::npos) {
458 // no file extension
Mike Stump11289f42009-09-09 15:08:12 +0000459 return false;
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000460 }
Mike Stump11289f42009-09-09 15:08:12 +0000461
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000462 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
463 // C header: .h
464 // C++ header: .hh or .H;
465 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump11289f42009-09-09 15:08:12 +0000466}
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000467
Eli Friedman94cf21e2009-05-18 22:20:00 +0000468RewriteObjC::RewriteObjC(std::string inFile, llvm::raw_ostream* OS,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000469 Diagnostic &D, const LangOptions &LOpts,
470 bool silenceMacroWarn)
471 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
472 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Narofff9e7c902008-03-28 22:26:09 +0000473 IsHeader = IsHeaderFile(inFile);
Mike Stump11289f42009-09-09 15:08:12 +0000474 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Steve Narofff9e7c902008-03-28 22:26:09 +0000475 "rewriting sub-expression within a macro (may not be correct)");
Mike Stump11289f42009-09-09 15:08:12 +0000476 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek5a201952009-02-07 01:47:29 +0000477 "rewriter doesn't support user-specified control flow semantics "
478 "for @try/@finally (code may not execute properly)");
Steve Narofff9e7c902008-03-28 22:26:09 +0000479}
480
Eli Friedmana63ab2d2009-05-18 22:29:17 +0000481ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
482 llvm::raw_ostream* OS,
Mike Stump11289f42009-09-09 15:08:12 +0000483 Diagnostic &Diags,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000484 const LangOptions &LOpts,
485 bool SilenceRewriteMacroWarning) {
486 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere9c810c2007-11-30 22:25:36 +0000487}
Chris Lattnere99c8322007-10-11 00:43:27 +0000488
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000489void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner187f6262008-01-31 19:38:44 +0000490 Context = &context;
491 SM = &Context->getSourceManager();
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +0000492 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner187f6262008-01-31 19:38:44 +0000493 MsgSendFunctionDecl = 0;
494 MsgSendSuperFunctionDecl = 0;
495 MsgSendStretFunctionDecl = 0;
496 MsgSendSuperStretFunctionDecl = 0;
497 MsgSendFpretFunctionDecl = 0;
498 GetClassFunctionDecl = 0;
499 GetMetaClassFunctionDecl = 0;
500 SelGetUidFunctionDecl = 0;
501 CFStringFunctionDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000502 ConstantStringClassReference = 0;
503 NSStringRecord = 0;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000504 CurMethodDef = 0;
505 CurFunctionDef = 0;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000506 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000507 GlobalVarDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000508 SuperStructDecl = 0;
Steve Naroffd9803712009-04-29 16:37:50 +0000509 ProtocolTypeDecl = 0;
Steve Naroff60a9ef62008-03-27 22:59:54 +0000510 ConstantStringDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000511 BcLabelCount = 0;
Steve Naroff17978c42008-03-11 17:37:02 +0000512 SuperContructorFunctionDecl = 0;
Steve Naroffce8e8862008-03-15 00:55:56 +0000513 NumObjCStringLiterals = 0;
Steve Narofff1ab6002008-12-08 20:01:41 +0000514 PropParentMap = 0;
515 CurrentBody = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000516 DisableReplaceStmt = false;
Fariborz Jahanianbc6811c2010-01-07 22:51:18 +0000517 objc_impl_method = false;
Mike Stump11289f42009-09-09 15:08:12 +0000518
Chris Lattner187f6262008-01-31 19:38:44 +0000519 // Get the ID and start/end of the main file.
520 MainFileID = SM->getMainFileID();
521 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
522 MainFileStart = MainBuf->getBufferStart();
523 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000524
Chris Lattner184e65d2009-04-14 23:22:57 +0000525 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump11289f42009-09-09 15:08:12 +0000526
Chris Lattner187f6262008-01-31 19:38:44 +0000527 // declaring objc_selector outside the parameter list removes a silly
528 // scope related warning...
Steve Naroff00a31762008-03-27 22:29:16 +0000529 if (IsHeader)
Steve Narofffcc6fd52009-02-03 20:39:18 +0000530 Preamble = "#pragma once\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000531 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff6ab6dc72008-12-23 20:11:22 +0000532 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroff00a31762008-03-27 22:29:16 +0000533 Preamble += "struct objc_object *superClass; ";
Steve Naroff17978c42008-03-11 17:37:02 +0000534 if (LangOpts.Microsoft) {
535 // Add a constructor for creating temporary objects.
Ted Kremenek5a201952009-02-07 01:47:29 +0000536 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
537 ": ";
Steve Naroff00a31762008-03-27 22:29:16 +0000538 Preamble += "object(o), superClass(s) {} ";
Steve Naroff17978c42008-03-11 17:37:02 +0000539 }
Steve Naroff00a31762008-03-27 22:29:16 +0000540 Preamble += "};\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000541 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
542 Preamble += "typedef struct objc_object Protocol;\n";
543 Preamble += "#define _REWRITER_typedef_Protocol\n";
544 Preamble += "#endif\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000545 if (LangOpts.Microsoft) {
546 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
547 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
548 } else
549 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
550 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroff00a31762008-03-27 22:29:16 +0000551 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000552 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroff00a31762008-03-27 22:29:16 +0000553 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000554 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroff00a31762008-03-27 22:29:16 +0000555 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000556 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroff00a31762008-03-27 22:29:16 +0000557 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000558 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroff00a31762008-03-27 22:29:16 +0000559 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000560 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroff00a31762008-03-27 22:29:16 +0000561 Preamble += "(const char *);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000562 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroff00a31762008-03-27 22:29:16 +0000563 Preamble += "(const char *);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000564 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
565 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
566 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
567 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
568 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroffd30f8c52008-05-09 21:17:56 +0000569 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff8dd15252008-07-16 18:58:11 +0000570 // @synchronized hooks.
Steve Narofff122ff02008-12-08 17:30:33 +0000571 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
572 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
573 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000574 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
575 Preamble += "struct __objcFastEnumerationState {\n\t";
576 Preamble += "unsigned long state;\n\t";
Steve Naroff4dbab8a2008-04-04 22:58:22 +0000577 Preamble += "void **itemsPtr;\n\t";
Steve Naroff00a31762008-03-27 22:29:16 +0000578 Preamble += "unsigned long *mutationsPtr;\n\t";
579 Preamble += "unsigned long extra[5];\n};\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000580 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000581 Preamble += "#define __FASTENUMERATIONSTATE\n";
582 Preamble += "#endif\n";
583 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
584 Preamble += "struct __NSConstantStringImpl {\n";
585 Preamble += " int *isa;\n";
586 Preamble += " int flags;\n";
587 Preamble += " char *str;\n";
588 Preamble += " long length;\n";
589 Preamble += "};\n";
Steve Naroffdd514e02008-08-05 20:04:48 +0000590 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
591 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
592 Preamble += "#else\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000593 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroffdd514e02008-08-05 20:04:48 +0000594 Preamble += "#endif\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000595 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
596 Preamble += "#endif\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000597 // Blocks preamble.
598 Preamble += "#ifndef BLOCK_IMPL\n";
599 Preamble += "#define BLOCK_IMPL\n";
600 Preamble += "struct __block_impl {\n";
601 Preamble += " void *isa;\n";
602 Preamble += " int Flags;\n";
Steve Naroff30484702009-12-06 21:14:13 +0000603 Preamble += " int Reserved;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000604 Preamble += " void *FuncPtr;\n";
605 Preamble += "};\n";
Steve Naroff61d879e2008-12-16 15:50:30 +0000606 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
Steve Naroff287a2bf2009-12-06 01:52:22 +0000607 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
Steve Naroff2b3843d2009-12-06 01:33:56 +0000608 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_assign(void *, const void *, const int);\n";
609 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
610 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
611 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
612 Preamble += "#else\n";
Steve Naroff7bf01ea2010-01-05 18:09:31 +0000613 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
614 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
Steve Naroff2b3843d2009-12-06 01:33:56 +0000615 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
616 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
617 Preamble += "#endif\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000618 Preamble += "#endif\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000619 if (LangOpts.Microsoft) {
Steve Narofff122ff02008-12-08 17:30:33 +0000620 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
621 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000622 Preamble += "#define __attribute__(X)\n";
Fariborz Jahanianf0462ff2010-01-15 22:29:39 +0000623 Preamble += "#define __weak\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000624 }
Fariborz Jahanian7fac6552010-01-05 19:21:35 +0000625 else {
Fariborz Jahanian02e07732009-12-23 02:07:37 +0000626 Preamble += "#define __block\n";
Fariborz Jahanian7fac6552010-01-05 19:21:35 +0000627 Preamble += "#define __weak\n";
628 }
Chris Lattner187f6262008-01-31 19:38:44 +0000629}
630
631
Chris Lattner3c799d72007-10-24 17:06:59 +0000632//===----------------------------------------------------------------------===//
633// Top Level Driver Code
634//===----------------------------------------------------------------------===//
635
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000636void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremenek31e7f0f2010-02-05 21:28:51 +0000637 if (Diags.hasErrorOccurred())
638 return;
639
Chris Lattner0bd1c972007-10-16 21:07:07 +0000640 // Two cases: either the decl could be in the main file, or it could be in a
641 // #included file. If the former, rewrite it now. If the later, check to see
642 // if we rewrote the #include/#import.
643 SourceLocation Loc = D->getLocation();
Chris Lattner8a425862009-01-16 07:36:28 +0000644 Loc = SM->getInstantiationLoc(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000645
Chris Lattner0bd1c972007-10-16 21:07:07 +0000646 // If this is for a builtin, ignore it.
647 if (Loc.isInvalid()) return;
648
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000649 // Look for built-in declarations that we need to refer during the rewrite.
650 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000651 RewriteFunctionDecl(FD);
Steve Naroff08899ff2008-04-15 22:42:06 +0000652 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffa397efd2007-11-03 11:27:19 +0000653 // declared in <Foundation/NSString.h>
Chris Lattner86d7d912008-11-24 03:54:41 +0000654 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroffa397efd2007-11-03 11:27:19 +0000655 ConstantStringClassReference = FVD;
656 return;
657 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000658 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroff161a92b2007-10-26 20:53:56 +0000659 RewriteInterfaceDecl(MD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000660 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000661 RewriteCategoryDecl(CD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000662 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Narofff921385f2007-10-30 16:42:30 +0000663 RewriteProtocolDecl(PD);
Mike Stump11289f42009-09-09 15:08:12 +0000664 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000665 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000666 RewriteForwardProtocolDecl(FP);
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000667 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
668 // Recurse into linkage specifications
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000669 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
670 DIEnd = LSD->decls_end();
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000671 DI != DIEnd; ++DI)
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000672 HandleTopLevelSingleDecl(*DI);
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000673 }
Chris Lattner3c799d72007-10-24 17:06:59 +0000674 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekd61ed3b2008-04-14 21:24:13 +0000675 if (SM->isFromMainFile(Loc))
Chris Lattner0bd1c972007-10-16 21:07:07 +0000676 return HandleDeclInMainFile(D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000677}
678
Chris Lattner3c799d72007-10-24 17:06:59 +0000679//===----------------------------------------------------------------------===//
680// Syntactic (non-AST) Rewriting Code
681//===----------------------------------------------------------------------===//
682
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000683void RewriteObjC::RewriteInclude() {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000684 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Fariborz Jahanian80258362008-01-19 00:30:35 +0000685 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
686 const char *MainBufStart = MainBuf.first;
687 const char *MainBufEnd = MainBuf.second;
688 size_t ImportLen = strlen("import");
689 size_t IncludeLen = strlen("include");
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);
Chris Lattner9cc55f52008-01-31 19:51:04 +0000703 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
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.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000736 ReplaceText(TabLoc, 1, " ", 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();
754 InsertText(startLoc, "// ", 3);
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 += "; }";
Steve Naroff9af94912008-12-02 15:48:25 +0000782 InsertText(onePastSemiLoc, Getr.c_str(), Getr.size());
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 += "; }";
Steve Naroff9af94912008-12-02 15:48:25 +0000797 InsertText(onePastSemiLoc, Setr.c_str(), Setr.size());
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.
Mike Stump11289f42009-09-09 15:08:12 +0000836 ReplaceText(startLoc, semiPtr-startBuf+1,
Chris Lattner9cc55f52008-01-31 19:51:04 +0000837 typedefString.c_str(), typedefString.size());
Chris Lattner3c799d72007-10-24 17:06:59 +0000838}
839
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000840void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahanianda8ec2b2010-01-21 17:36:00 +0000841 // When method is a synthesized one, such as a getter/setter there is
842 // nothing to rewrite.
843 if (Method->isSynthesized())
844 return;
Steve Naroff3ce37a62007-12-14 23:37:57 +0000845 SourceLocation LocStart = Method->getLocStart();
846 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000847
Chris Lattner88ea93e2009-02-04 01:06:56 +0000848 if (SM->getInstantiationLineNumber(LocEnd) >
849 SM->getInstantiationLineNumber(LocStart)) {
Steve Naroffe020fa12008-10-21 13:37:27 +0000850 InsertText(LocStart, "#if 0\n", 6);
851 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff3ce37a62007-12-14 23:37:57 +0000852 } else {
Chris Lattner1780a852008-01-31 19:42:41 +0000853 InsertText(LocStart, "// ", 3);
Steve Naroff5448cf62007-10-30 13:30:57 +0000854 }
855}
856
Mike Stump11289f42009-09-09 15:08:12 +0000857void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahanianda8ec2b2010-01-21 17:36:00 +0000858 SourceLocation Loc = prop->getAtLoc();
Mike Stump11289f42009-09-09 15:08:12 +0000859
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000860 ReplaceText(Loc, 0, "// ", 3);
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000861 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahaniane8a30162007-11-07 00:09:37 +0000862}
863
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000864void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000865 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000866
Steve Naroff5448cf62007-10-30 13:30:57 +0000867 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000868 ReplaceText(LocStart, 0, "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +0000869
Fariborz Jahanian68ebe632010-02-10 01:15:09 +0000870 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
871 E = CatDecl->prop_end(); I != E; ++I)
872 RewriteProperty(*I);
873
Mike Stump11289f42009-09-09 15:08:12 +0000874 for (ObjCCategoryDecl::instmeth_iterator
875 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000876 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000877 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +0000878 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000879 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000880 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000881 RewriteMethodDeclaration(*I);
882
Steve Naroff5448cf62007-10-30 13:30:57 +0000883 // Lastly, comment out the @end.
Ted Kremenekc7c64312010-01-07 01:20:12 +0000884 ReplaceText(CatDecl->getAtEndRange().getBegin(), 0, "// ", 3);
Steve Naroff5448cf62007-10-30 13:30:57 +0000885}
886
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000887void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000888 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Mike Stump11289f42009-09-09 15:08:12 +0000889
Steve Narofff921385f2007-10-30 16:42:30 +0000890 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000891
Steve Narofff921385f2007-10-30 16:42:30 +0000892 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000893 ReplaceText(LocStart, 0, "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +0000894
895 for (ObjCProtocolDecl::instmeth_iterator
896 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000897 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000898 RewriteMethodDeclaration(*I);
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000899 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000900 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000901 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000902 RewriteMethodDeclaration(*I);
903
Steve Narofff921385f2007-10-30 16:42:30 +0000904 // Lastly, comment out the @end.
Ted Kremenekc7c64312010-01-07 01:20:12 +0000905 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Chris Lattner9cc55f52008-01-31 19:51:04 +0000906 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroffa509f042007-11-14 15:03:57 +0000907
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000908 // Must comment out @optional/@required
909 const char *startBuf = SM->getCharacterData(LocStart);
910 const char *endBuf = SM->getCharacterData(LocEnd);
911 for (const char *p = startBuf; p < endBuf; p++) {
912 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
913 std::string CommentedOptional = "/* @optional */";
Steve Naroffa509f042007-11-14 15:03:57 +0000914 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattner9cc55f52008-01-31 19:51:04 +0000915 ReplaceText(OptionalLoc, strlen("@optional"),
916 CommentedOptional.c_str(), CommentedOptional.size());
Mike Stump11289f42009-09-09 15:08:12 +0000917
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000918 }
919 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
920 std::string CommentedRequired = "/* @required */";
Steve Naroffa509f042007-11-14 15:03:57 +0000921 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattner9cc55f52008-01-31 19:51:04 +0000922 ReplaceText(OptionalLoc, strlen("@required"),
923 CommentedRequired.c_str(), CommentedRequired.size());
Mike Stump11289f42009-09-09 15:08:12 +0000924
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000925 }
926 }
Steve Narofff921385f2007-10-30 16:42:30 +0000927}
928
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000929void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000930 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffc17b0562007-11-14 03:37:28 +0000931 if (LocStart.isInvalid())
932 assert(false && "Invalid SourceLocation");
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000933 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000934 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000935}
936
Mike Stump11289f42009-09-09 15:08:12 +0000937void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000938 std::string &ResultStr) {
Steve Naroff295570a2008-10-30 12:09:33 +0000939 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroffb067bbd2008-07-16 14:40:40 +0000940 const FunctionType *FPRetType = 0;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000941 ResultStr += "\nstatic ";
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000942 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanian24cb52c2007-12-17 21:03:50 +0000943 ResultStr += "id";
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000944 else if (OMD->getResultType()->isFunctionPointerType() ||
945 OMD->getResultType()->isBlockPointerType()) {
Steve Naroffb067bbd2008-07-16 14:40:40 +0000946 // needs special handling, since pointer-to-functions have special
947 // syntax (where a decaration models use).
948 QualType retType = OMD->getResultType();
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000949 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000950 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000951 PointeeTy = PT->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000952 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000953 PointeeTy = BPT->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +0000954 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000955 ResultStr += FPRetType->getResultType().getAsString();
956 ResultStr += "(*";
Steve Naroffb067bbd2008-07-16 14:40:40 +0000957 }
958 } else
Fariborz Jahanian24cb52c2007-12-17 21:03:50 +0000959 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian7262fca2008-01-10 01:39:52 +0000960 ResultStr += " ";
Mike Stump11289f42009-09-09 15:08:12 +0000961
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000962 // Unique method name
Fariborz Jahanian56338352007-11-13 21:02:00 +0000963 std::string NameStr;
Mike Stump11289f42009-09-09 15:08:12 +0000964
Douglas Gregorffca3a22009-01-09 17:18:27 +0000965 if (OMD->isInstanceMethod())
Fariborz Jahanian56338352007-11-13 21:02:00 +0000966 NameStr += "_I_";
967 else
968 NameStr += "_C_";
Mike Stump11289f42009-09-09 15:08:12 +0000969
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000970 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +0000971 NameStr += "_";
Mike Stump11289f42009-09-09 15:08:12 +0000972
973 if (ObjCCategoryImplDecl *CID =
Steve Naroff11b387f2009-01-08 19:41:02 +0000974 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000975 NameStr += CID->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +0000976 NameStr += "_";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000977 }
Mike Stump11289f42009-09-09 15:08:12 +0000978 // Append selector names, replacing ':' with '_'
Chris Lattnere4b95692008-11-24 03:33:13 +0000979 {
980 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000981 int len = selString.size();
982 for (int i = 0; i < len; i++)
983 if (selString[i] == ':')
984 selString[i] = '_';
Fariborz Jahanian56338352007-11-13 21:02:00 +0000985 NameStr += selString;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000986 }
Fariborz Jahanian56338352007-11-13 21:02:00 +0000987 // Remember this name for metadata emission
988 MethodInternalNames[OMD] = NameStr;
989 ResultStr += NameStr;
Mike Stump11289f42009-09-09 15:08:12 +0000990
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000991 // Rewrite arguments
992 ResultStr += "(";
Mike Stump11289f42009-09-09 15:08:12 +0000993
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000994 // invisible arguments
Douglas Gregorffca3a22009-01-09 17:18:27 +0000995 if (OMD->isInstanceMethod()) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000996 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000997 selfTy = Context->getPointerType(selfTy);
Steve Naroffdc5b6b22008-03-12 00:25:36 +0000998 if (!LangOpts.Microsoft) {
999 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
1000 ResultStr += "struct ";
1001 }
1002 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001003 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +00001004 ResultStr += " *";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001005 }
1006 else
Steve Naroffd9803712009-04-29 16:37:50 +00001007 ResultStr += Context->getObjCClassType().getAsString();
Mike Stump11289f42009-09-09 15:08:12 +00001008
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001009 ResultStr += " self, ";
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001010 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001011 ResultStr += " _cmd";
Mike Stump11289f42009-09-09 15:08:12 +00001012
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001013 // Method arguments.
Chris Lattnera4997152009-02-20 18:43:26 +00001014 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1015 E = OMD->param_end(); PI != E; ++PI) {
1016 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001017 ResultStr += ", ";
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001018 if (PDecl->getType()->isObjCQualifiedIdType()) {
1019 ResultStr += "id ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001020 ResultStr += PDecl->getNameAsString();
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001021 } else {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001022 std::string Name = PDecl->getNameAsString();
Steve Naroffa5c0db82008-12-11 21:05:33 +00001023 if (isTopLevelBlockPointerType(PDecl->getType())) {
Steve Naroff44df6a22008-10-30 14:45:29 +00001024 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001025 const BlockPointerType *BPT = PDecl->getType()->getAs<BlockPointerType>();
Douglas Gregor7de59662009-05-29 20:38:28 +00001026 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name,
1027 Context->PrintingPolicy);
Steve Naroff44df6a22008-10-30 14:45:29 +00001028 } else
Douglas Gregor7de59662009-05-29 20:38:28 +00001029 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001030 ResultStr += Name;
1031 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001032 }
Fariborz Jahanianeab81cd2008-01-21 20:14:23 +00001033 if (OMD->isVariadic())
1034 ResultStr += ", ...";
Fariborz Jahanian7262fca2008-01-10 01:39:52 +00001035 ResultStr += ") ";
Mike Stump11289f42009-09-09 15:08:12 +00001036
Steve Naroffb067bbd2008-07-16 14:40:40 +00001037 if (FPRetType) {
1038 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump11289f42009-09-09 15:08:12 +00001039
Steve Naroffb067bbd2008-07-16 14:40:40 +00001040 // Now, emit the argument types (if any).
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001041 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroffb067bbd2008-07-16 14:40:40 +00001042 ResultStr += "(";
1043 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1044 if (i) ResultStr += ", ";
1045 std::string ParamStr = FT->getArgType(i).getAsString();
1046 ResultStr += ParamStr;
1047 }
1048 if (FT->isVariadic()) {
1049 if (FT->getNumArgs()) ResultStr += ", ";
1050 ResultStr += "...";
1051 }
1052 ResultStr += ")";
1053 } else {
1054 ResultStr += "()";
1055 }
1056 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001057}
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001058void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001059 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1060 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump11289f42009-09-09 15:08:12 +00001061
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00001062 if (IMD)
Chris Lattner1780a852008-01-31 19:42:41 +00001063 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00001064 else
Chris Lattner1780a852008-01-31 19:42:41 +00001065 InsertText(CID->getLocStart(), "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +00001066
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001067 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001068 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1069 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001070 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001071 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001072 ObjCMethodDecl *OMD = *I;
1073 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001074 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001075 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redla7b98a72009-04-26 20:35:05 +00001076
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001077 const char *startBuf = SM->getCharacterData(LocStart);
1078 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattner9cc55f52008-01-31 19:51:04 +00001079 ReplaceText(LocStart, endBuf-startBuf,
1080 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001081 }
Mike Stump11289f42009-09-09 15:08:12 +00001082
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001083 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001084 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1085 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001086 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001087 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001088 ObjCMethodDecl *OMD = *I;
1089 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001090 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001091 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +00001092
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001093 const char *startBuf = SM->getCharacterData(LocStart);
1094 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattner9cc55f52008-01-31 19:51:04 +00001095 ReplaceText(LocStart, endBuf-startBuf,
Mike Stump11289f42009-09-09 15:08:12 +00001096 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001097 }
Steve Naroffe1908e32008-12-01 20:33:01 +00001098 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001099 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001100 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001101 I != E; ++I) {
Steve Naroffc038b3a2008-12-02 17:36:43 +00001102 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffe1908e32008-12-01 20:33:01 +00001103 }
1104
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00001105 if (IMD)
Chris Lattner1780a852008-01-31 19:42:41 +00001106 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00001107 else
Mike Stump11289f42009-09-09 15:08:12 +00001108 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001109}
1110
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001111void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffc5484042007-10-30 02:23:23 +00001112 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001113 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff2f55b982007-11-01 03:35:41 +00001114 // we haven't seen a forward decl - generate a typedef.
Steve Naroff03f27672007-11-14 23:02:56 +00001115 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001116 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001117 ResultStr += "\n";
1118 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001119 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001120 ResultStr += "\n";
Steve Naroffa1e115e2008-03-10 23:16:54 +00001121 ResultStr += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001122 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001123 ResultStr += ";\n#endif\n";
Steve Naroff2f55b982007-11-01 03:35:41 +00001124 // Mark this typedef as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001125 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff2f55b982007-11-01 03:35:41 +00001126 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001127 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump11289f42009-09-09 15:08:12 +00001128
1129 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001130 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff0c0f5ba2009-01-11 01:06:09 +00001131 RewriteProperty(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001132 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001133 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001134 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001135 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001136 for (ObjCInterfaceDecl::classmeth_iterator
1137 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001138 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001139 RewriteMethodDeclaration(*I);
1140
Steve Naroff4cd61ac2007-10-30 03:43:13 +00001141 // Lastly, comment out the @end.
Ted Kremenekc7c64312010-01-07 01:20:12 +00001142 ReplaceText(ClassDecl->getAtEndRange().getBegin(), 0, "// ", 3);
Steve Naroff161a92b2007-10-26 20:53:56 +00001143}
1144
Steve Naroff08628db2008-12-09 12:56:34 +00001145Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1146 SourceRange SrcRange) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00001147 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1148 // This allows us to reuse all the fun and games in SynthMessageExpr().
1149 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1150 ObjCMessageExpr *MsgExpr;
1151 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1152 llvm::SmallVector<Expr *, 1> ExprVec;
1153 ExprVec.push_back(newStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001154
Steve Naroff1042ff32008-12-08 16:43:47 +00001155 Stmt *Receiver = PropRefExpr->getBase();
1156 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1157 if (PRE && PropGetters[PRE]) {
1158 // This allows us to handle chain/nested property getters.
1159 Receiver = PropGetters[PRE];
1160 }
Mike Stump11289f42009-09-09 15:08:12 +00001161 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
1162 PDecl->getSetterName(), PDecl->getType(),
1163 PDecl->getSetterMethodDecl(),
1164 SourceLocation(), SourceLocation(),
Steve Naroff4588d0f2008-12-04 16:24:46 +00001165 &ExprVec[0], 1);
1166 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001167
Steve Naroff4588d0f2008-12-04 16:24:46 +00001168 // Now do the actual rewrite.
Steve Naroff08628db2008-12-09 12:56:34 +00001169 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffdf705772008-12-10 14:53:27 +00001170 //delete BinOp;
Ted Kremenek5a201952009-02-07 01:47:29 +00001171 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1172 // to things that stay around.
1173 Context->Deallocate(MsgExpr);
Steve Naroff4588d0f2008-12-04 16:24:46 +00001174 return ReplacingStmt;
Steve Narofff326f402008-12-03 00:56:33 +00001175}
1176
Steve Naroff4588d0f2008-12-04 16:24:46 +00001177Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Narofff326f402008-12-03 00:56:33 +00001178 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1179 // This allows us to reuse all the fun and games in SynthMessageExpr().
1180 ObjCMessageExpr *MsgExpr;
1181 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
Mike Stump11289f42009-09-09 15:08:12 +00001182
Steve Naroff1042ff32008-12-08 16:43:47 +00001183 Stmt *Receiver = PropRefExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00001184
Steve Naroff1042ff32008-12-08 16:43:47 +00001185 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1186 if (PRE && PropGetters[PRE]) {
1187 // This allows us to handle chain/nested property getters.
1188 Receiver = PropGetters[PRE];
1189 }
Mike Stump11289f42009-09-09 15:08:12 +00001190 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
1191 PDecl->getGetterName(), PDecl->getType(),
1192 PDecl->getGetterMethodDecl(),
1193 SourceLocation(), SourceLocation(),
Steve Narofff326f402008-12-03 00:56:33 +00001194 0, 0);
1195
Steve Naroff22216db2008-12-04 23:50:32 +00001196 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001197
1198 if (!PropParentMap)
1199 PropParentMap = new ParentMap(CurrentBody);
1200
1201 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1202 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1203 // We stash away the ReplacingStmt since actually doing the
1204 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1205 PropGetters[PropRefExpr] = ReplacingStmt;
Ted Kremenek5a201952009-02-07 01:47:29 +00001206 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1207 // to things that stay around.
1208 Context->Deallocate(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001209 return PropRefExpr; // return the original...
1210 } else {
1211 ReplaceStmt(PropRefExpr, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001212 // delete PropRefExpr; elsewhere...
Ted Kremenek5a201952009-02-07 01:47:29 +00001213 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1214 // to things that stay around.
1215 Context->Deallocate(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001216 return ReplacingStmt;
1217 }
Steve Narofff326f402008-12-03 00:56:33 +00001218}
1219
Mike Stump11289f42009-09-09 15:08:12 +00001220Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001221 SourceLocation OrigStart,
1222 bool &replaced) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001223 ObjCIvarDecl *D = IV->getDecl();
Fariborz Jahanian0f3aecf2010-01-07 18:18:32 +00001224 const Expr *BaseExpr = IV->getBase();
Steve Naroff677ab3a2008-10-27 17:20:55 +00001225 if (CurMethodDef) {
Fariborz Jahanianf9e8c2b2010-01-26 18:28:51 +00001226 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001227 ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian0f3aecf2010-01-07 18:18:32 +00001228 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanianf0ed69c2010-01-26 20:37:44 +00001229 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
Steve Naroffb1c02372008-05-08 17:52:16 +00001230 // lookup which class implements the instance variable.
1231 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001232 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001233 clsDeclared);
Steve Naroffb1c02372008-05-08 17:52:16 +00001234 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001235
Steve Naroffb1c02372008-05-08 17:52:16 +00001236 // Synthesize an explicit cast to gain access to the ivar.
1237 std::string RecName = clsDeclared->getIdentifier()->getName();
1238 RecName += "_IMPL";
1239 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00001240 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001241 SourceLocation(), II);
Steve Naroffb1c02372008-05-08 17:52:16 +00001242 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1243 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall97513962010-01-15 18:39:57 +00001244 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
1245 CastExpr::CK_Unknown,
1246 IV->getBase());
Steve Naroffb1c02372008-05-08 17:52:16 +00001247 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001248 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1249 IV->getBase()->getLocEnd(),
1250 castExpr);
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001251 replaced = true;
Mike Stump11289f42009-09-09 15:08:12 +00001252 if (IV->isFreeIvar() &&
Steve Naroff677ab3a2008-10-27 17:20:55 +00001253 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001254 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1255 IV->getLocation(),
1256 D->getType());
Steve Naroff22216db2008-12-04 23:50:32 +00001257 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffb1c02372008-05-08 17:52:16 +00001258 return ME;
Steve Naroff05caa482007-11-15 11:33:00 +00001259 }
Fariborz Jahanian81310812010-01-28 01:41:20 +00001260 // Get the new text
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001261 // Cannot delete IV->getBase(), since PE points to it.
1262 // Replace the old base with the cast. This is important when doing
1263 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001264 IV->setBase(PE);
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001265 return IV;
Steve Naroff05caa482007-11-15 11:33:00 +00001266 }
Steve Naroff24840f62008-04-18 21:55:08 +00001267 } else { // we are outside a method.
Steve Naroff29ce4e52008-05-06 23:20:07 +00001268 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump11289f42009-09-09 15:08:12 +00001269
Steve Naroff29ce4e52008-05-06 23:20:07 +00001270 // Explicit ivar refs need to have a cast inserted.
1271 // FIXME: consider sharing some of this code with the code above.
Fariborz Jahanian12e2e862010-01-12 17:31:23 +00001272 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Fariborz Jahanian9146e442010-01-11 17:50:35 +00001273 ObjCInterfaceType *iFaceDecl =
1274 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001275 // lookup which class implements the instance variable.
1276 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001277 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001278 clsDeclared);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001279 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001280
Steve Naroff29ce4e52008-05-06 23:20:07 +00001281 // Synthesize an explicit cast to gain access to the ivar.
1282 std::string RecName = clsDeclared->getIdentifier()->getName();
1283 RecName += "_IMPL";
1284 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00001285 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001286 SourceLocation(), II);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001287 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1288 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall97513962010-01-15 18:39:57 +00001289 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
1290 CastExpr::CK_Unknown,
1291 IV->getBase());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001292 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001293 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner34873d22008-05-28 16:38:23 +00001294 IV->getBase()->getLocEnd(), castExpr);
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001295 replaced = true;
Steve Naroff29ce4e52008-05-06 23:20:07 +00001296 // Cannot delete IV->getBase(), since PE points to it.
1297 // Replace the old base with the cast. This is important when doing
1298 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001299 IV->setBase(PE);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001300 return IV;
1301 }
Steve Naroff05caa482007-11-15 11:33:00 +00001302 }
Steve Naroff24840f62008-04-18 21:55:08 +00001303 return IV;
Steve Narofff60782b2007-11-15 02:58:25 +00001304}
1305
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001306Stmt *RewriteObjC::RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced) {
1307 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1308 CI != E; ++CI) {
1309 if (*CI) {
1310 Stmt *newStmt = RewriteObjCNestedIvarRefExpr(*CI, replaced);
1311 if (newStmt)
1312 *CI = newStmt;
1313 }
1314 }
1315 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
1316 SourceRange OrigStmtRange = S->getSourceRange();
1317 Stmt *newStmt = RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin(),
1318 replaced);
1319 return newStmt;
Fariborz Jahanian31433382010-02-05 17:48:10 +00001320 }
1321 if (ObjCMessageExpr *MsgRefExpr = dyn_cast<ObjCMessageExpr>(S)) {
1322 Stmt *newStmt = SynthMessageExpr(MsgRefExpr);
1323 return newStmt;
1324 }
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00001325 return S;
1326}
1327
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001328/// SynthCountByEnumWithState - To print:
1329/// ((unsigned int (*)
1330/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001331/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001332/// sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001333/// "countByEnumeratingWithState:objects:count:"),
1334/// &enumState,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001335/// (id *)items, (unsigned int)16)
1336///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001337void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001338 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1339 "id *, unsigned int))(void *)objc_msgSend)";
1340 buf += "\n\t\t";
1341 buf += "((id)l_collection,\n\t\t";
1342 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1343 buf += "\n\t\t";
1344 buf += "&enumState, "
1345 "(id *)items, (unsigned int)16)";
1346}
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001347
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001348/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1349/// statement to exit to its outer synthesized loop.
1350///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001351Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001352 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1353 return S;
1354 // replace break with goto __break_label
1355 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001356
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001357 SourceLocation startLoc = S->getLocStart();
1358 buf = "goto __break_label_";
1359 buf += utostr(ObjCBcLabelNo.back());
Chris Lattner9cc55f52008-01-31 19:51:04 +00001360 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001361
1362 return 0;
1363}
1364
1365/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1366/// statement to continue with its inner synthesized loop.
1367///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001368Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001369 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1370 return S;
1371 // replace continue with goto __continue_label
1372 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001373
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001374 SourceLocation startLoc = S->getLocStart();
1375 buf = "goto __continue_label_";
1376 buf += utostr(ObjCBcLabelNo.back());
Chris Lattner9cc55f52008-01-31 19:51:04 +00001377 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001378
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001379 return 0;
1380}
1381
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001382/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001383/// It rewrites:
1384/// for ( type elem in collection) { stmts; }
Mike Stump11289f42009-09-09 15:08:12 +00001385
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001386/// Into:
1387/// {
Mike Stump11289f42009-09-09 15:08:12 +00001388/// type elem;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001389/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001390/// id items[16];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001391/// id l_collection = (id)collection;
Mike Stump11289f42009-09-09 15:08:12 +00001392/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001393/// objects:items count:16];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001394/// if (limit) {
1395/// unsigned long startMutations = *enumState.mutationsPtr;
1396/// do {
1397/// unsigned long counter = 0;
1398/// do {
Mike Stump11289f42009-09-09 15:08:12 +00001399/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001400/// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001401/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001402/// stmts;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001403/// __continue_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001404/// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001405/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001406/// objects:items count:16]);
1407/// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001408/// __break_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001409/// }
1410/// else
1411/// elem = nil;
1412/// }
1413///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001414Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattnera779d692008-01-31 05:10:40 +00001415 SourceLocation OrigEnd) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001416 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001417 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001418 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump11289f42009-09-09 15:08:12 +00001419 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001420 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001421
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001422 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001423 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001424 const char *elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001425 std::string elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001426 std::string buf;
1427 buf = "\n{\n\t";
1428 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1429 // type elem;
Chris Lattner529efc72009-03-28 06:33:19 +00001430 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek292b3842008-10-06 22:16:13 +00001431 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001432 if (ElementType->isObjCQualifiedIdType() ||
1433 ElementType->isObjCQualifiedInterfaceType())
1434 // Simply use 'id' for all qualified types.
1435 elementTypeAsString = "id";
1436 else
1437 elementTypeAsString = ElementType.getAsString();
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001438 buf += elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001439 buf += " ";
Chris Lattner86d7d912008-11-24 03:54:41 +00001440 elementName = D->getNameAsCString();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001441 buf += elementName;
1442 buf += ";\n\t";
1443 }
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001444 else {
1445 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner86d7d912008-11-24 03:54:41 +00001446 elementName = DR->getDecl()->getNameAsCString();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001447 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1448 if (VD->getType()->isObjCQualifiedIdType() ||
1449 VD->getType()->isObjCQualifiedInterfaceType())
1450 // Simply use 'id' for all qualified types.
1451 elementTypeAsString = "id";
1452 else
1453 elementTypeAsString = VD->getType().getAsString();
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001454 }
Mike Stump11289f42009-09-09 15:08:12 +00001455
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001456 // struct __objcFastEnumerationState enumState = { 0 };
1457 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1458 // id items[16];
1459 buf += "id items[16];\n\t";
1460 // id l_collection = (id)
1461 buf += "id l_collection = (id)";
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001462 // Find start location of 'collection' the hard way!
1463 const char *startCollectionBuf = startBuf;
1464 startCollectionBuf += 3; // skip 'for'
1465 startCollectionBuf = strchr(startCollectionBuf, '(');
1466 startCollectionBuf++; // skip '('
1467 // find 'in' and skip it.
1468 while (*startCollectionBuf != ' ' ||
1469 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1470 (*(startCollectionBuf+3) != ' ' &&
1471 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1472 startCollectionBuf++;
1473 startCollectionBuf += 3;
Mike Stump11289f42009-09-09 15:08:12 +00001474
1475 // Replace: "for (type element in" with string constructed thus far.
Chris Lattner9cc55f52008-01-31 19:51:04 +00001476 ReplaceText(startLoc, startCollectionBuf - startBuf,
1477 buf.c_str(), buf.size());
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001478 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001479 SourceLocation rightParenLoc = S->getRParenLoc();
1480 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1481 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001482 buf = ";\n\t";
Mike Stump11289f42009-09-09 15:08:12 +00001483
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001484 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1485 // objects:items count:16];
1486 // which is synthesized into:
Mike Stump11289f42009-09-09 15:08:12 +00001487 // unsigned int limit =
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001488 // ((unsigned int (*)
1489 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001490 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001491 // sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001492 // "countByEnumeratingWithState:objects:count:"),
1493 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001494 // (id *)items, (unsigned int)16);
1495 buf += "unsigned long limit =\n\t\t";
1496 SynthCountByEnumWithState(buf);
1497 buf += ";\n\t";
1498 /// if (limit) {
1499 /// unsigned long startMutations = *enumState.mutationsPtr;
1500 /// do {
1501 /// unsigned long counter = 0;
1502 /// do {
Mike Stump11289f42009-09-09 15:08:12 +00001503 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001504 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001505 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001506 buf += "if (limit) {\n\t";
1507 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1508 buf += "do {\n\t\t";
1509 buf += "unsigned long counter = 0;\n\t\t";
1510 buf += "do {\n\t\t\t";
1511 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1512 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1513 buf += elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001514 buf += " = (";
1515 buf += elementTypeAsString;
1516 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001517 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattner9cc55f52008-01-31 19:51:04 +00001518 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001519
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001520 /// __continue_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001521 /// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001522 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001523 /// objects:items count:16]);
1524 /// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001525 /// __break_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001526 /// }
1527 /// else
1528 /// elem = nil;
1529 /// }
Mike Stump11289f42009-09-09 15:08:12 +00001530 ///
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001531 buf = ";\n\t";
1532 buf += "__continue_label_";
1533 buf += utostr(ObjCBcLabelNo.back());
1534 buf += ": ;";
1535 buf += "\n\t\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001536 buf += "} while (counter < limit);\n\t";
1537 buf += "} while (limit = ";
1538 SynthCountByEnumWithState(buf);
1539 buf += ");\n\t";
1540 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001541 buf += " = ((";
1542 buf += elementTypeAsString;
1543 buf += ")0);\n\t";
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001544 buf += "__break_label_";
1545 buf += utostr(ObjCBcLabelNo.back());
1546 buf += ": ;\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001547 buf += "}\n\t";
1548 buf += "else\n\t\t";
1549 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001550 buf += " = ((";
1551 buf += elementTypeAsString;
1552 buf += ")0);\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001553 buf += "}\n";
Mike Stump11289f42009-09-09 15:08:12 +00001554
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001555 // Insert all these *after* the statement body.
Sebastian Redla7b98a72009-04-26 20:35:05 +00001556 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Narofff0ff8792008-07-21 18:26:02 +00001557 if (isa<CompoundStmt>(S->getBody())) {
1558 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1559 InsertText(endBodyLoc, buf.c_str(), buf.size());
1560 } else {
1561 /* Need to treat single statements specially. For example:
1562 *
1563 * for (A *a in b) if (stuff()) break;
1564 * for (A *a in b) xxxyy;
1565 *
1566 * The following code simply scans ahead to the semi to find the actual end.
1567 */
1568 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1569 const char *semiBuf = strchr(stmtBuf, ';');
1570 assert(semiBuf && "Can't find ';'");
1571 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1572 InsertText(endBodyLoc, buf.c_str(), buf.size());
1573 }
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001574 Stmts.pop_back();
1575 ObjCBcLabelNo.pop_back();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001576 return 0;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001577}
1578
Mike Stump11289f42009-09-09 15:08:12 +00001579/// RewriteObjCSynchronizedStmt -
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001580/// This routine rewrites @synchronized(expr) stmt;
1581/// into:
1582/// objc_sync_enter(expr);
1583/// @try stmt @finally { objc_sync_exit(expr); }
1584///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001585Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001586 // Get the start location and compute the semi location.
1587 SourceLocation startLoc = S->getLocStart();
1588 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001589
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001590 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump11289f42009-09-09 15:08:12 +00001591
1592 std::string buf;
Steve Naroffb2fc0522008-08-21 13:03:03 +00001593 buf = "objc_sync_enter((id)";
1594 const char *lparenBuf = startBuf;
1595 while (*lparenBuf != '(') lparenBuf++;
1596 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001597 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1598 // the sync expression is typically a message expression that's already
Steve Naroffad7013b2008-08-19 13:04:19 +00001599 // been rewritten! (which implies the SourceLocation's are invalid).
1600 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001601 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffad7013b2008-08-19 13:04:19 +00001602 while (*endBuf != ')') endBuf--;
1603 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001604 buf = ");\n";
1605 // declare a new scope with two variables, _stack and _rethrow.
1606 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1607 buf += "int buf[18/*32-bit i386*/];\n";
1608 buf += "char *pointers[4];} _stack;\n";
1609 buf += "id volatile _rethrow = 0;\n";
1610 buf += "objc_exception_try_enter(&_stack);\n";
1611 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001612 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001613 startLoc = S->getSynchBody()->getLocEnd();
1614 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001615
Steve Naroffad7013b2008-08-19 13:04:19 +00001616 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001617 SourceLocation lastCurlyLoc = startLoc;
1618 buf = "}\nelse {\n";
1619 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroffd9803712009-04-29 16:37:50 +00001620 buf += "}\n";
1621 buf += "{ /* implicit finally clause */\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001622 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffec60b432009-12-05 21:43:12 +00001623
1624 std::string syncBuf;
1625 syncBuf += " objc_sync_exit(";
John McCall97513962010-01-15 18:39:57 +00001626 Expr *syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1627 CastExpr::CK_Unknown,
1628 S->getSynchExpr());
Ted Kremenek2d470fc2008-09-13 05:16:45 +00001629 std::string syncExprBufS;
1630 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00001631 syncExpr->printPretty(syncExprBuf, *Context, 0,
1632 PrintingPolicy(LangOpts));
Steve Naroffec60b432009-12-05 21:43:12 +00001633 syncBuf += syncExprBuf.str();
1634 syncBuf += ");";
1635
1636 buf += syncBuf;
1637 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001638 buf += "}\n";
1639 buf += "}";
Mike Stump11289f42009-09-09 15:08:12 +00001640
Chris Lattner9cc55f52008-01-31 19:51:04 +00001641 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffec60b432009-12-05 21:43:12 +00001642
1643 bool hasReturns = false;
1644 HasReturnStmts(S->getSynchBody(), hasReturns);
1645 if (hasReturns)
1646 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1647
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001648 return 0;
1649}
1650
Steve Naroffec60b432009-12-05 21:43:12 +00001651void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1652{
Steve Naroff6d6da252008-12-05 17:03:39 +00001653 // Perform a bottom up traversal of all children.
1654 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1655 CI != E; ++CI)
1656 if (*CI)
Steve Naroffec60b432009-12-05 21:43:12 +00001657 WarnAboutReturnGotoStmts(*CI);
Steve Naroff6d6da252008-12-05 17:03:39 +00001658
Steve Naroffec60b432009-12-05 21:43:12 +00001659 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump11289f42009-09-09 15:08:12 +00001660 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff6d6da252008-12-05 17:03:39 +00001661 TryFinallyContainsReturnDiag);
1662 }
1663 return;
1664}
1665
Steve Naroffec60b432009-12-05 21:43:12 +00001666void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1667{
1668 // Perform a bottom up traversal of all children.
1669 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1670 CI != E; ++CI)
1671 if (*CI)
1672 HasReturnStmts(*CI, hasReturns);
1673
1674 if (isa<ReturnStmt>(S))
1675 hasReturns = true;
1676 return;
1677}
1678
1679void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1680 // Perform a bottom up traversal of all children.
1681 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1682 CI != E; ++CI)
1683 if (*CI) {
1684 RewriteTryReturnStmts(*CI);
1685 }
1686 if (isa<ReturnStmt>(S)) {
1687 SourceLocation startLoc = S->getLocStart();
1688 const char *startBuf = SM->getCharacterData(startLoc);
1689
1690 const char *semiBuf = strchr(startBuf, ';');
1691 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1692 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1693
1694 std::string buf;
1695 buf = "{ objc_exception_try_exit(&_stack); return";
1696
1697 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
1698 InsertText(onePastSemiLoc, "}", 1);
1699 }
1700 return;
1701}
1702
1703void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1704 // Perform a bottom up traversal of all children.
1705 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1706 CI != E; ++CI)
1707 if (*CI) {
1708 RewriteSyncReturnStmts(*CI, syncExitBuf);
1709 }
1710 if (isa<ReturnStmt>(S)) {
1711 SourceLocation startLoc = S->getLocStart();
1712 const char *startBuf = SM->getCharacterData(startLoc);
1713
1714 const char *semiBuf = strchr(startBuf, ';');
1715 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1716 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1717
1718 std::string buf;
1719 buf = "{ objc_exception_try_exit(&_stack);";
1720 buf += syncExitBuf;
1721 buf += " return";
1722
1723 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
1724 InsertText(onePastSemiLoc, "}", 1);
1725 }
1726 return;
1727}
1728
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001729Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001730 // Get the start location and compute the semi location.
1731 SourceLocation startLoc = S->getLocStart();
1732 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001733
Steve Naroffbf478ec2007-11-07 04:08:17 +00001734 assert((*startBuf == '@') && "bogus @try location");
1735
1736 std::string buf;
1737 // declare a new scope with two variables, _stack and _rethrow.
1738 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1739 buf += "int buf[18/*32-bit i386*/];\n";
1740 buf += "char *pointers[4];} _stack;\n";
1741 buf += "id volatile _rethrow = 0;\n";
1742 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff16018582007-11-07 18:43:40 +00001743 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffbf478ec2007-11-07 04:08:17 +00001744
Chris Lattner9cc55f52008-01-31 19:51:04 +00001745 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001746
Steve Naroffbf478ec2007-11-07 04:08:17 +00001747 startLoc = S->getTryBody()->getLocEnd();
1748 startBuf = SM->getCharacterData(startLoc);
1749
1750 assert((*startBuf == '}') && "bogus @try block");
Mike Stump11289f42009-09-09 15:08:12 +00001751
Steve Naroffbf478ec2007-11-07 04:08:17 +00001752 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffce2dca12008-07-16 15:31:30 +00001753 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1754 if (catchList) {
1755 startLoc = startLoc.getFileLocWithOffset(1);
1756 buf = " /* @catch begin */ else {\n";
1757 buf += " id _caught = objc_exception_extract(&_stack);\n";
1758 buf += " objc_exception_try_enter (&_stack);\n";
1759 buf += " if (_setjmp(_stack.buf))\n";
1760 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1761 buf += " else { /* @catch continue */";
Mike Stump11289f42009-09-09 15:08:12 +00001762
Steve Naroffce2dca12008-07-16 15:31:30 +00001763 InsertText(startLoc, buf.c_str(), buf.size());
Steve Narofffac18fe2008-09-09 19:59:12 +00001764 } else { /* no catch list */
1765 buf = "}\nelse {\n";
1766 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1767 buf += "}";
1768 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffce2dca12008-07-16 15:31:30 +00001769 }
Steve Naroffbf478ec2007-11-07 04:08:17 +00001770 bool sawIdTypedCatch = false;
1771 Stmt *lastCatchBody = 0;
Steve Naroffbf478ec2007-11-07 04:08:17 +00001772 while (catchList) {
Steve Naroff371b8fb2009-03-03 19:52:17 +00001773 ParmVarDecl *catchDecl = catchList->getCatchParamDecl();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001774
Mike Stump11289f42009-09-09 15:08:12 +00001775 if (catchList == S->getCatchStmts())
Steve Naroffbf478ec2007-11-07 04:08:17 +00001776 buf = "if ("; // we are generating code for the first catch clause
1777 else
1778 buf = "else if (";
1779 startLoc = catchList->getLocStart();
1780 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001781
Steve Naroffbf478ec2007-11-07 04:08:17 +00001782 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump11289f42009-09-09 15:08:12 +00001783
Steve Naroffbf478ec2007-11-07 04:08:17 +00001784 const char *lParenLoc = strchr(startBuf, '(');
1785
Steve Naroffe6b7ffd2008-02-01 22:08:12 +00001786 if (catchList->hasEllipsis()) {
Steve Naroffedb5bc62008-02-01 20:02:07 +00001787 // Now rewrite the body...
1788 lastCatchBody = catchList->getCatchBody();
Steve Naroffedb5bc62008-02-01 20:02:07 +00001789 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1790 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001791 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1792 "bogus @catch paren location");
Steve Naroffedb5bc62008-02-01 20:02:07 +00001793 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001794
Steve Naroffedb5bc62008-02-01 20:02:07 +00001795 buf += "1) { id _tmp = _caught;";
Daniel Dunbardec484a2009-08-19 19:10:30 +00001796 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff371b8fb2009-03-03 19:52:17 +00001797 } else if (catchDecl) {
1798 QualType t = catchDecl->getType();
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001799 if (t == Context->getObjCIdType()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001800 buf += "1) { ";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001801 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001802 sawIdTypedCatch = true;
Fariborz Jahanian59516092010-01-12 01:22:23 +00001803 } else if (t->isObjCObjectPointerType()) {
1804 QualType InterfaceTy = t->getPointeeType();
1805 const ObjCInterfaceType *cls = // Should be a pointer to a class.
1806 InterfaceTy->getAs<ObjCInterfaceType>();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001807 if (cls) {
Steve Naroff16018582007-11-07 18:43:40 +00001808 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001809 buf += cls->getDecl()->getNameAsString();
Steve Naroff16018582007-11-07 18:43:40 +00001810 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001811 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001812 }
1813 }
1814 // Now rewrite the body...
1815 lastCatchBody = catchList->getCatchBody();
1816 SourceLocation rParenLoc = catchList->getRParenLoc();
1817 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1818 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1819 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1820 assert((*rParenBuf == ')') && "bogus @catch paren location");
1821 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001822
Steve Naroffbf478ec2007-11-07 04:08:17 +00001823 buf = " = _caught;";
Mike Stump11289f42009-09-09 15:08:12 +00001824 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroffbf478ec2007-11-07 04:08:17 +00001825 // declares the @catch parameter).
Chris Lattner9cc55f52008-01-31 19:51:04 +00001826 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff371b8fb2009-03-03 19:52:17 +00001827 } else {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001828 assert(false && "@catch rewrite bug");
Steve Naroffa733c7f2007-11-07 15:32:26 +00001829 }
Steve Naroffedb5bc62008-02-01 20:02:07 +00001830 // make sure all the catch bodies get rewritten!
Steve Naroffbf478ec2007-11-07 04:08:17 +00001831 catchList = catchList->getNextCatchStmt();
1832 }
1833 // Complete the catch list...
1834 if (lastCatchBody) {
1835 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001836 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1837 "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001838
Steve Naroff4adbe312008-09-11 15:29:03 +00001839 // Insert the last (implicit) else clause *before* the right curly brace.
1840 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1841 buf = "} /* last catch end */\n";
1842 buf += "else {\n";
1843 buf += " _rethrow = _caught;\n";
1844 buf += " objc_exception_try_exit(&_stack);\n";
1845 buf += "} } /* @catch end */\n";
1846 if (!S->getFinallyStmt())
1847 buf += "}\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001848 InsertText(bodyLoc, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001849
Steve Naroffbf478ec2007-11-07 04:08:17 +00001850 // Set lastCurlyLoc
1851 lastCurlyLoc = lastCatchBody->getLocEnd();
1852 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001853 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001854 startLoc = finalStmt->getLocStart();
1855 startBuf = SM->getCharacterData(startLoc);
1856 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump11289f42009-09-09 15:08:12 +00001857
Steve Naroffbf478ec2007-11-07 04:08:17 +00001858 buf = "/* @finally */";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001859 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001860
Steve Naroffbf478ec2007-11-07 04:08:17 +00001861 Stmt *body = finalStmt->getFinallyBody();
1862 SourceLocation startLoc = body->getLocStart();
1863 SourceLocation endLoc = body->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001864 assert(*SM->getCharacterData(startLoc) == '{' &&
1865 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001866 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001867 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001868
Steve Naroffbf478ec2007-11-07 04:08:17 +00001869 startLoc = startLoc.getFileLocWithOffset(1);
1870 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001871 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001872 endLoc = endLoc.getFileLocWithOffset(-1);
1873 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001874 InsertText(endLoc, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001875
Steve Naroffbf478ec2007-11-07 04:08:17 +00001876 // Set lastCurlyLoc
1877 lastCurlyLoc = body->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00001878
Steve Naroff6d6da252008-12-05 17:03:39 +00001879 // Now check for any return/continue/go statements within the @try.
Steve Naroffec60b432009-12-05 21:43:12 +00001880 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff4adbe312008-09-11 15:29:03 +00001881 } else { /* no finally clause - make sure we synthesize an implicit one */
1882 buf = "{ /* implicit finally clause */\n";
1883 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1884 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1885 buf += "}";
1886 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffec60b432009-12-05 21:43:12 +00001887
1888 // Now check for any return/continue/go statements within the @try.
1889 // The implicit finally clause won't called if the @try contains any
1890 // jump statements.
1891 bool hasReturns = false;
1892 HasReturnStmts(S->getTryBody(), hasReturns);
1893 if (hasReturns)
1894 RewriteTryReturnStmts(S->getTryBody());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001895 }
1896 // Now emit the final closing curly brace...
1897 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1898 buf = " } /* @try scope end */\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001899 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001900 return 0;
1901}
1902
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001903Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001904 return 0;
1905}
1906
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001907Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001908 return 0;
1909}
1910
Mike Stump11289f42009-09-09 15:08:12 +00001911// This can't be done with ReplaceStmt(S, ThrowExpr), since
1912// the throw expression is typically a message expression that's already
Steve Naroffa733c7f2007-11-07 15:32:26 +00001913// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001914Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroffa733c7f2007-11-07 15:32:26 +00001915 // Get the start location and compute the semi location.
1916 SourceLocation startLoc = S->getLocStart();
1917 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001918
Steve Naroffa733c7f2007-11-07 15:32:26 +00001919 assert((*startBuf == '@') && "bogus @throw location");
1920
1921 std::string buf;
1922 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffc7d2df22008-01-19 00:42:38 +00001923 if (S->getThrowExpr())
1924 buf = "objc_exception_throw(";
1925 else // add an implicit argument
1926 buf = "objc_exception_throw(_caught";
Mike Stump11289f42009-09-09 15:08:12 +00001927
Steve Naroff29788342008-07-25 15:41:30 +00001928 // handle "@ throw" correctly.
1929 const char *wBuf = strchr(startBuf, 'w');
1930 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1931 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001932
Steve Naroffa733c7f2007-11-07 15:32:26 +00001933 const char *semiBuf = strchr(startBuf, ';');
1934 assert((*semiBuf == ';') && "@throw: can't find ';'");
1935 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1936 buf = ");";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001937 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroffa733c7f2007-11-07 15:32:26 +00001938 return 0;
1939}
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001940
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001941Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerc6d91c02007-10-17 22:35:30 +00001942 // Create a new string expression.
1943 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlssond8499822007-10-29 05:01:08 +00001944 std::string StrEncoding;
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00001945 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00001946 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
1947 StrEncoding.length(), false,StrType,
1948 SourceLocation());
Chris Lattner2e0d2602008-01-31 19:37:57 +00001949 ReplaceStmt(Exp, Replacement);
Mike Stump11289f42009-09-09 15:08:12 +00001950
Chris Lattner4431a1b2007-11-30 22:53:43 +00001951 // Replace this subexpr in the parent.
Steve Naroff22216db2008-12-04 23:50:32 +00001952 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattner69534692007-10-24 16:57:36 +00001953 return Replacement;
Chris Lattnera7c19fe2007-10-16 22:36:42 +00001954}
1955
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001956Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff2654e182008-12-22 22:16:07 +00001957 if (!SelGetUidFunctionDecl)
1958 SynthSelGetUidFunctionDecl();
Steve Naroffe4f9b232007-11-05 14:50:49 +00001959 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1960 // Create a call to sel_registerName("selName").
1961 llvm::SmallVector<Expr*, 8> SelExprs;
1962 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00001963 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00001964 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00001965 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00001966 false, argType, SourceLocation()));
Steve Naroffe4f9b232007-11-05 14:50:49 +00001967 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1968 &SelExprs[0], SelExprs.size());
Chris Lattner2e0d2602008-01-31 19:37:57 +00001969 ReplaceStmt(Exp, SelExp);
Steve Naroff22216db2008-12-04 23:50:32 +00001970 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffe4f9b232007-11-05 14:50:49 +00001971 return SelExp;
1972}
1973
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001974CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff574440f2007-10-24 22:48:43 +00001975 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001976 // Get the type, we will need to reference it in a couple spots.
Steve Naroff574440f2007-10-24 22:48:43 +00001977 QualType msgSendType = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001978
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001979 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek5a201952009-02-07 01:47:29 +00001980 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001981
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001982 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattner3c799d72007-10-24 17:06:59 +00001983 QualType pToFunc = Context->getPointerType(msgSendType);
Mike Stump11289f42009-09-09 15:08:12 +00001984 ImplicitCastExpr *ICE = new (Context) ImplicitCastExpr(pToFunc,
Anders Carlssona2615922009-07-31 00:48:10 +00001985 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00001986 DRE,
Douglas Gregora11693b2008-11-12 17:17:38 +00001987 /*isLvalue=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00001988
John McCall9dd450b2009-09-21 23:43:11 +00001989 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00001990
Ted Kremenekd7b4f402009-02-09 20:51:47 +00001991 return new (Context) CallExpr(*Context, ICE, args, nargs, FT->getResultType(),
1992 SourceLocation());
Steve Naroff574440f2007-10-24 22:48:43 +00001993}
1994
Steve Naroff50d42052007-11-01 13:24:47 +00001995static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1996 const char *&startRef, const char *&endRef) {
1997 while (startBuf < endBuf) {
1998 if (*startBuf == '<')
1999 startRef = startBuf; // mark the start.
2000 if (*startBuf == '>') {
Steve Naroff1b232132007-11-09 12:50:28 +00002001 if (startRef && *startRef == '<') {
2002 endRef = startBuf; // mark the end.
2003 return true;
2004 }
2005 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00002006 }
2007 startBuf++;
2008 }
2009 return false;
2010}
2011
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002012static void scanToNextArgument(const char *&argRef) {
2013 int angle = 0;
2014 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2015 if (*argRef == '<')
2016 angle++;
2017 else if (*argRef == '>')
2018 angle--;
2019 argRef++;
2020 }
2021 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2022}
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002023
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002024bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian80c54b02010-02-03 21:29:28 +00002025 if (T->isObjCQualifiedIdType())
2026 return true;
Fariborz Jahanian06769f92010-02-02 18:35:07 +00002027 if (const PointerType *PT = T->getAs<PointerType>()) {
2028 if (PT->getPointeeType()->isObjCQualifiedIdType())
2029 return true;
2030 }
2031 if (T->isObjCObjectPointerType()) {
2032 T = T->getPointeeType();
2033 return T->isObjCQualifiedInterfaceType();
2034 }
2035 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00002036}
2037
Steve Naroff873bd842008-07-29 18:15:38 +00002038void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2039 QualType Type = E->getType();
2040 if (needToScanForQualifiers(Type)) {
Steve Naroffdbfc6932008-11-19 21:15:47 +00002041 SourceLocation Loc, EndLoc;
Mike Stump11289f42009-09-09 15:08:12 +00002042
Steve Naroffdbfc6932008-11-19 21:15:47 +00002043 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2044 Loc = ECE->getLParenLoc();
2045 EndLoc = ECE->getRParenLoc();
2046 } else {
2047 Loc = E->getLocStart();
2048 EndLoc = E->getLocEnd();
2049 }
2050 // This will defend against trying to rewrite synthesized expressions.
2051 if (Loc.isInvalid() || EndLoc.isInvalid())
2052 return;
2053
Steve Naroff873bd842008-07-29 18:15:38 +00002054 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffdbfc6932008-11-19 21:15:47 +00002055 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff873bd842008-07-29 18:15:38 +00002056 const char *startRef = 0, *endRef = 0;
2057 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2058 // Get the locations of the startRef, endRef.
2059 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
2060 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
2061 // Comment out the protocol references.
2062 InsertText(LessLoc, "/*", 2);
2063 InsertText(GreaterLoc, "*/", 2);
2064 }
2065 }
2066}
2067
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002068void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002069 SourceLocation Loc;
2070 QualType Type;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002071 const FunctionProtoType *proto = 0;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002072 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2073 Loc = VD->getLocation();
2074 Type = VD->getType();
2075 }
2076 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2077 Loc = FD->getLocation();
2078 // Check for ObjC 'id' and class types that have been adorned with protocol
2079 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall9dd450b2009-09-21 23:43:11 +00002080 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002081 assert(funcType && "missing function type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002082 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002083 if (!proto)
2084 return;
2085 Type = proto->getResultType();
2086 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00002087 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2088 Loc = FD->getLocation();
2089 Type = FD->getType();
2090 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002091 else
2092 return;
Mike Stump11289f42009-09-09 15:08:12 +00002093
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002094 if (needToScanForQualifiers(Type)) {
Steve Naroff50d42052007-11-01 13:24:47 +00002095 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002096
Steve Naroff50d42052007-11-01 13:24:47 +00002097 const char *endBuf = SM->getCharacterData(Loc);
2098 const char *startBuf = endBuf;
Steve Naroff930e0992008-05-31 05:02:17 +00002099 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroff50d42052007-11-01 13:24:47 +00002100 startBuf--; // scan backward (from the decl location) for return type.
2101 const char *startRef = 0, *endRef = 0;
2102 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2103 // Get the locations of the startRef, endRef.
2104 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2105 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2106 // Comment out the protocol references.
Chris Lattner1780a852008-01-31 19:42:41 +00002107 InsertText(LessLoc, "/*", 2);
2108 InsertText(GreaterLoc, "*/", 2);
Steve Naroff37e011c2007-10-31 04:38:33 +00002109 }
2110 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002111 if (!proto)
2112 return; // most likely, was a variable
Steve Naroff50d42052007-11-01 13:24:47 +00002113 // Now check arguments.
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002114 const char *startBuf = SM->getCharacterData(Loc);
2115 const char *startFuncBuf = startBuf;
Steve Naroff50d42052007-11-01 13:24:47 +00002116 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2117 if (needToScanForQualifiers(proto->getArgType(i))) {
2118 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002119
Steve Naroff50d42052007-11-01 13:24:47 +00002120 const char *endBuf = startBuf;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002121 // scan forward (from the decl location) for argument types.
2122 scanToNextArgument(endBuf);
Steve Naroff50d42052007-11-01 13:24:47 +00002123 const char *startRef = 0, *endRef = 0;
2124 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2125 // Get the locations of the startRef, endRef.
Mike Stump11289f42009-09-09 15:08:12 +00002126 SourceLocation LessLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002127 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump11289f42009-09-09 15:08:12 +00002128 SourceLocation GreaterLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002129 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroff50d42052007-11-01 13:24:47 +00002130 // Comment out the protocol references.
Chris Lattner1780a852008-01-31 19:42:41 +00002131 InsertText(LessLoc, "/*", 2);
2132 InsertText(GreaterLoc, "*/", 2);
Steve Naroff50d42052007-11-01 13:24:47 +00002133 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002134 startBuf = ++endBuf;
2135 }
2136 else {
Steve Naroffc884aa82008-08-06 15:58:23 +00002137 // If the function name is derived from a macro expansion, then the
2138 // argument buffer will not follow the name. Need to speak with Chris.
2139 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002140 startBuf++; // scan forward (from the decl location) for argument types.
2141 startBuf++;
2142 }
Steve Naroff50d42052007-11-01 13:24:47 +00002143 }
Steve Naroff37e011c2007-10-31 04:38:33 +00002144}
2145
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002146// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002147void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002148 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2149 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002150 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002151 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002152 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002153 false /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002154 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002155 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002156 SelGetUidIdent, getFuncType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002157 FunctionDecl::Extern, false);
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002158}
2159
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002160void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002161 // declared in <objc/objc.h>
Douglas Gregor1e21c192009-01-09 01:47:02 +00002162 if (FD->getIdentifier() &&
2163 strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002164 SelGetUidFunctionDecl = FD;
Steve Naroff37e011c2007-10-31 04:38:33 +00002165 return;
2166 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002167 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002168}
2169
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002170void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2171 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2172 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2173 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2174 if (!proto)
2175 return;
2176 QualType Type = proto->getResultType();
2177 std::string FdStr = Type.getAsString();
2178 FdStr += " ";
2179 FdStr += FD->getNameAsCString();
2180 FdStr += "(";
2181 unsigned numArgs = proto->getNumArgs();
2182 for (unsigned i = 0; i < numArgs; i++) {
2183 QualType ArgType = proto->getArgType(i);
2184 FdStr += ArgType.getAsString();
2185
2186 if (i+1 < numArgs)
2187 FdStr += ", ";
2188 }
2189 FdStr += ");\n";
2190 InsertText(FunLocStart, FdStr.c_str(), FdStr.size());
2191 CurFunctionDeclToDeclareForBlock = 0;
2192}
2193
Steve Naroff17978c42008-03-11 17:37:02 +00002194// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002195void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroff17978c42008-03-11 17:37:02 +00002196 if (SuperContructorFunctionDecl)
2197 return;
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002198 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroff17978c42008-03-11 17:37:02 +00002199 llvm::SmallVector<QualType, 16> ArgTys;
2200 QualType argT = Context->getObjCIdType();
2201 assert(!argT.isNull() && "Can't find 'id' type");
2202 ArgTys.push_back(argT);
2203 ArgTys.push_back(argT);
2204 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2205 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002206 false, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002207 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002208 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002209 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002210 FunctionDecl::Extern, false);
Steve Naroff17978c42008-03-11 17:37:02 +00002211}
2212
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002213// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002214void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002215 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2216 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002217 QualType argT = Context->getObjCIdType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002218 assert(!argT.isNull() && "Can't find 'id' type");
2219 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002220 argT = Context->getObjCSelType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002221 assert(!argT.isNull() && "Can't find 'SEL' type");
2222 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002223 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002224 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002225 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002226 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002227 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002228 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002229 FunctionDecl::Extern, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002230}
2231
Steve Naroff7fa2f042007-11-15 10:28:18 +00002232// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002233void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002234 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2235 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002236 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002237 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002238 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002239 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2240 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2241 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002242 argT = Context->getObjCSelType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002243 assert(!argT.isNull() && "Can't find 'SEL' type");
2244 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002245 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff7fa2f042007-11-15 10:28:18 +00002246 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002247 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002248 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002249 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002250 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002251 FunctionDecl::Extern, false);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002252}
2253
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002254// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002255void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002256 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2257 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002258 QualType argT = Context->getObjCIdType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002259 assert(!argT.isNull() && "Can't find 'id' type");
2260 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002261 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002262 assert(!argT.isNull() && "Can't find 'SEL' type");
2263 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002264 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002265 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002266 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002267 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002268 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002269 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002270 FunctionDecl::Extern, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002271}
2272
Mike Stump11289f42009-09-09 15:08:12 +00002273// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002274// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002275void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump11289f42009-09-09 15:08:12 +00002276 IdentifierInfo *msgSendIdent =
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002277 &Context->Idents.get("objc_msgSendSuper_stret");
2278 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002279 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002280 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002281 &Context->Idents.get("objc_super"));
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002282 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2283 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2284 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002285 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002286 assert(!argT.isNull() && "Can't find 'SEL' type");
2287 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002288 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002289 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002290 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002291 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002292 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002293 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002294 FunctionDecl::Extern, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002295}
2296
Steve Naroff2e4e3852008-05-08 22:02:18 +00002297// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002298void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002299 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2300 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002301 QualType argT = Context->getObjCIdType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002302 assert(!argT.isNull() && "Can't find 'id' type");
2303 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002304 argT = Context->getObjCSelType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002305 assert(!argT.isNull() && "Can't find 'SEL' type");
2306 ArgTys.push_back(argT);
Steve Naroff2e4e3852008-05-08 22:02:18 +00002307 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002308 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002309 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002310 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002311 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002312 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002313 FunctionDecl::Extern, false);
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002314}
2315
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002316// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002317void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002318 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2319 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002320 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002321 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002322 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002323 false /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002324 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002325 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002326 getClassIdent, getClassType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002327 FunctionDecl::Extern, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002328}
2329
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002330// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002331void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002332 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2333 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002334 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002335 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002336 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002337 false /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002338 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002339 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002340 getClassIdent, getClassType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002341 FunctionDecl::Extern, false);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002342}
2343
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002344Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffce8e8862008-03-15 00:55:56 +00002345 QualType strType = getConstantStringStructType();
2346
2347 std::string S = "__NSConstantStringImpl_";
Steve Naroffa6141f02008-05-31 03:35:42 +00002348
2349 std::string tmpName = InFileName;
2350 unsigned i;
2351 for (i=0; i < tmpName.length(); i++) {
2352 char c = tmpName.at(i);
2353 // replace any non alphanumeric characters with '_'.
2354 if (!isalpha(c) && (c < '0' || c > '9'))
2355 tmpName[i] = '_';
2356 }
2357 S += tmpName;
2358 S += "_";
Steve Naroffce8e8862008-03-15 00:55:56 +00002359 S += utostr(NumObjCStringLiterals++);
2360
Steve Naroff00a31762008-03-27 22:29:16 +00002361 Preamble += "static __NSConstantStringImpl " + S;
2362 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2363 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffce8e8862008-03-15 00:55:56 +00002364 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremenek2d470fc2008-09-13 05:16:45 +00002365 std::string prettyBufS;
2366 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00002367 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2368 PrintingPolicy(LangOpts));
Steve Naroff00a31762008-03-27 22:29:16 +00002369 Preamble += prettyBuf.str();
2370 Preamble += ",";
Steve Naroff94ed6dc2009-12-06 01:48:44 +00002371 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00002372
2373 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2374 &Context->Idents.get(S.c_str()), strType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002375 VarDecl::Static);
Ted Kremenek5a201952009-02-07 01:47:29 +00002376 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
2377 Expr *Unop = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002378 Context->getPointerType(DRE->getType()),
Steve Naroffce8e8862008-03-15 00:55:56 +00002379 SourceLocation());
Steve Naroff265a6b92007-11-08 14:30:50 +00002380 // cast to NSConstantString *
John McCall97513962010-01-15 18:39:57 +00002381 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2382 CastExpr::CK_Unknown, Unop);
Chris Lattner2e0d2602008-01-31 19:37:57 +00002383 ReplaceStmt(Exp, cast);
Steve Naroff22216db2008-12-04 23:50:32 +00002384 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff265a6b92007-11-08 14:30:50 +00002385 return cast;
Steve Naroffa397efd2007-11-03 11:27:19 +00002386}
2387
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002388ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002389 // check if we are sending a message to 'super'
Douglas Gregorffca3a22009-01-09 17:18:27 +00002390 if (!CurMethodDef || !CurMethodDef->isInstanceMethod()) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002391
Douglas Gregor8ea1f532008-11-04 14:56:14 +00002392 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
Mike Stump11289f42009-09-09 15:08:12 +00002393 const ObjCObjectPointerType *OPT =
John McCall9dd450b2009-09-21 23:43:11 +00002394 Super->getType()->getAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00002395 assert(OPT);
2396 const ObjCInterfaceType *IT = OPT->getInterfaceType();
Chris Lattnera9b3cae2008-06-21 18:04:54 +00002397 return IT->getDecl();
2398 }
2399 return 0;
Steve Naroff7fa2f042007-11-15 10:28:18 +00002400}
2401
2402// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002403QualType RewriteObjC::getSuperStructType() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002404 if (!SuperStructDecl) {
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002405 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002406 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002407 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002408 QualType FieldTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00002409
Steve Naroff7fa2f042007-11-15 10:28:18 +00002410 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002411 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002412 // struct objc_class *super;
Mike Stump11289f42009-09-09 15:08:12 +00002413 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor91f84212008-12-11 16:49:14 +00002414
Steve Naroff7fa2f042007-11-15 10:28:18 +00002415 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002416 for (unsigned i = 0; i < 2; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002417 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2418 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002419 FieldTypes[i], 0,
2420 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002421 /*Mutable=*/false));
Douglas Gregor91f84212008-12-11 16:49:14 +00002422 }
Mike Stump11289f42009-09-09 15:08:12 +00002423
Douglas Gregor91f84212008-12-11 16:49:14 +00002424 SuperStructDecl->completeDefinition(*Context);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002425 }
2426 return Context->getTagDeclType(SuperStructDecl);
2427}
2428
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002429QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffce8e8862008-03-15 00:55:56 +00002430 if (!ConstantStringDecl) {
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002431 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002432 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002433 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffce8e8862008-03-15 00:55:56 +00002434 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00002435
Steve Naroffce8e8862008-03-15 00:55:56 +00002436 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002437 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffce8e8862008-03-15 00:55:56 +00002438 // int flags;
Mike Stump11289f42009-09-09 15:08:12 +00002439 FieldTypes[1] = Context->IntTy;
Steve Naroffce8e8862008-03-15 00:55:56 +00002440 // char *str;
Mike Stump11289f42009-09-09 15:08:12 +00002441 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffce8e8862008-03-15 00:55:56 +00002442 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00002443 FieldTypes[3] = Context->LongTy;
Douglas Gregor91f84212008-12-11 16:49:14 +00002444
Steve Naroffce8e8862008-03-15 00:55:56 +00002445 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002446 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002447 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2448 ConstantStringDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00002449 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002450 FieldTypes[i], 0,
Douglas Gregor91f84212008-12-11 16:49:14 +00002451 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002452 /*Mutable=*/true));
Douglas Gregor91f84212008-12-11 16:49:14 +00002453 }
2454
2455 ConstantStringDecl->completeDefinition(*Context);
Steve Naroffce8e8862008-03-15 00:55:56 +00002456 }
2457 return Context->getTagDeclType(ConstantStringDecl);
2458}
2459
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002460Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002461 if (!SelGetUidFunctionDecl)
2462 SynthSelGetUidFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002463 if (!MsgSendFunctionDecl)
2464 SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002465 if (!MsgSendSuperFunctionDecl)
2466 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002467 if (!MsgSendStretFunctionDecl)
2468 SynthMsgSendStretFunctionDecl();
2469 if (!MsgSendSuperStretFunctionDecl)
2470 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002471 if (!MsgSendFpretFunctionDecl)
2472 SynthMsgSendFpretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002473 if (!GetClassFunctionDecl)
2474 SynthGetClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002475 if (!GetMetaClassFunctionDecl)
2476 SynthGetMetaClassFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002477
Steve Naroff7fa2f042007-11-15 10:28:18 +00002478 // default to objc_msgSend().
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002479 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2480 // May need to use objc_msgSend_stret() as well.
2481 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroffd9803712009-04-29 16:37:50 +00002482 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2483 QualType resultType = mDecl->getResultType();
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002484 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002485 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002486 else if (resultType->isRealFloatingType())
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002487 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002488 }
Mike Stump11289f42009-09-09 15:08:12 +00002489
Steve Naroff574440f2007-10-24 22:48:43 +00002490 // Synthesize a call to objc_msgSend().
2491 llvm::SmallVector<Expr*, 8> MsgExprs;
2492 IdentifierInfo *clsName = Exp->getClassName();
Mike Stump11289f42009-09-09 15:08:12 +00002493
Steve Naroff574440f2007-10-24 22:48:43 +00002494 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2495 if (clsName) { // class message.
Steve Naroff6c79f972008-07-24 19:44:33 +00002496 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2497 // the 'super' idiom within a class method.
Daniel Dunbar07d07852009-10-18 21:17:35 +00002498 if (clsName->getName() == "super") {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002499 MsgSendFlavor = MsgSendSuperFunctionDecl;
2500 if (MsgSendStretFlavor)
2501 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2502 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002503
2504 ObjCInterfaceDecl *SuperDecl =
Steve Naroff677ab3a2008-10-27 17:20:55 +00002505 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002506
2507 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00002508
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002509 // set the receiver to self, the first argument to all methods.
Steve Naroffd9803712009-04-29 16:37:50 +00002510 InitExprs.push_back(
John McCall97513962010-01-15 18:39:57 +00002511 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2512 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002513 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroffd9803712009-04-29 16:37:50 +00002514 Context->getObjCIdType(),
John McCall97513962010-01-15 18:39:57 +00002515 SourceLocation()))
2516 ); // set the 'receiver'.
Steve Naroffd9803712009-04-29 16:37:50 +00002517
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002518 llvm::SmallVector<Expr*, 8> ClsExprs;
2519 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002520 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002521 SuperDecl->getIdentifier()->getNameStart(),
2522 SuperDecl->getIdentifier()->getLength(),
2523 false, argType, SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002524 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002525 &ClsExprs[0],
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002526 ClsExprs.size());
2527 // To turn off a warning, type-cast to 'id'
Douglas Gregore200adc2008-10-27 19:41:14 +00002528 InitExprs.push_back( // set 'super class', using objc_getClass().
John McCall97513962010-01-15 18:39:57 +00002529 NoTypeInfoCStyleCastExpr(Context,
2530 Context->getObjCIdType(),
2531 CastExpr::CK_Unknown, Cls));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002532 // struct objc_super
2533 QualType superType = getSuperStructType();
Steve Naroff0b844f02008-03-11 18:14:26 +00002534 Expr *SuperRep;
Mike Stump11289f42009-09-09 15:08:12 +00002535
Steve Naroff0b844f02008-03-11 18:14:26 +00002536 if (LangOpts.Microsoft) {
2537 SynthSuperContructorFunctionDecl();
2538 // Simulate a contructor call...
Mike Stump11289f42009-09-09 15:08:12 +00002539 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff0b844f02008-03-11 18:14:26 +00002540 superType, SourceLocation());
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002541 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002542 InitExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002543 superType, SourceLocation());
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002544 // The code for super is a little tricky to prevent collision with
2545 // the structure definition in the header. The rewriter has it's own
2546 // internal definition (__rw_objc_super) that is uses. This is why
2547 // we need the cast below. For example:
2548 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2549 //
Ted Kremenek5a201952009-02-07 01:47:29 +00002550 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002551 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002552 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00002553 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2554 Context->getPointerType(superType),
2555 CastExpr::CK_Unknown, SuperRep);
Mike Stump11289f42009-09-09 15:08:12 +00002556 } else {
Steve Naroff0b844f02008-03-11 18:14:26 +00002557 // (struct objc_super) { <exprs from above> }
Mike Stump11289f42009-09-09 15:08:12 +00002558 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2559 &InitExprs[0], InitExprs.size(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002560 SourceLocation());
John McCalle15bbff2010-01-18 19:35:47 +00002561 TypeSourceInfo *superTInfo
2562 = Context->getTrivialTypeSourceInfo(superType);
John McCall5d7aa7f2010-01-19 22:33:45 +00002563 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2564 superType, ILE, false);
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002565 // struct objc_super *
Ted Kremenek5a201952009-02-07 01:47:29 +00002566 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002567 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002568 SourceLocation());
Steve Naroff0b844f02008-03-11 18:14:26 +00002569 }
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002570 MsgExprs.push_back(SuperRep);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002571 } else {
2572 llvm::SmallVector<Expr*, 8> ClsExprs;
2573 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002574 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002575 clsName->getNameStart(),
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002576 clsName->getLength(),
2577 false, argType,
2578 SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002579 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002580 &ClsExprs[0],
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002581 ClsExprs.size());
2582 MsgExprs.push_back(Cls);
2583 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002584 } else { // instance message.
2585 Expr *recExpr = Exp->getReceiver();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002586
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002587 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002588 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002589 if (MsgSendStretFlavor)
2590 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff7fa2f042007-11-15 10:28:18 +00002591 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002592
Steve Naroff7fa2f042007-11-15 10:28:18 +00002593 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00002594
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002595 InitExprs.push_back(
John McCall97513962010-01-15 18:39:57 +00002596 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2597 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002598 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroff97adf602008-07-16 22:35:27 +00002599 Context->getObjCIdType(),
John McCall97513962010-01-15 18:39:57 +00002600 SourceLocation()))
2601 ); // set the 'receiver'.
Mike Stump11289f42009-09-09 15:08:12 +00002602
Steve Naroff7fa2f042007-11-15 10:28:18 +00002603 llvm::SmallVector<Expr*, 8> ClsExprs;
2604 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002605 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002606 SuperDecl->getIdentifier()->getNameStart(),
2607 SuperDecl->getIdentifier()->getLength(),
2608 false, argType, SourceLocation()));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002609 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002610 &ClsExprs[0],
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002611 ClsExprs.size());
Fariborz Jahaniand5db92b2007-12-05 17:29:46 +00002612 // To turn off a warning, type-cast to 'id'
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002613 InitExprs.push_back(
Douglas Gregore200adc2008-10-27 19:41:14 +00002614 // set 'super class', using objc_getClass().
John McCall97513962010-01-15 18:39:57 +00002615 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2616 CastExpr::CK_Unknown, Cls));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002617 // struct objc_super
2618 QualType superType = getSuperStructType();
Steve Naroff17978c42008-03-11 17:37:02 +00002619 Expr *SuperRep;
Mike Stump11289f42009-09-09 15:08:12 +00002620
Steve Naroff17978c42008-03-11 17:37:02 +00002621 if (LangOpts.Microsoft) {
2622 SynthSuperContructorFunctionDecl();
2623 // Simulate a contructor call...
Mike Stump11289f42009-09-09 15:08:12 +00002624 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff17978c42008-03-11 17:37:02 +00002625 superType, SourceLocation());
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002626 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002627 InitExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002628 superType, SourceLocation());
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002629 // The code for super is a little tricky to prevent collision with
2630 // the structure definition in the header. The rewriter has it's own
2631 // internal definition (__rw_objc_super) that is uses. This is why
2632 // we need the cast below. For example:
2633 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2634 //
Ted Kremenek5a201952009-02-07 01:47:29 +00002635 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002636 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002637 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00002638 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2639 Context->getPointerType(superType),
2640 CastExpr::CK_Unknown, SuperRep);
Steve Naroff17978c42008-03-11 17:37:02 +00002641 } else {
2642 // (struct objc_super) { <exprs from above> }
Mike Stump11289f42009-09-09 15:08:12 +00002643 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2644 &InitExprs[0], InitExprs.size(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002645 SourceLocation());
John McCalle15bbff2010-01-18 19:35:47 +00002646 TypeSourceInfo *superTInfo
2647 = Context->getTrivialTypeSourceInfo(superType);
John McCall5d7aa7f2010-01-19 22:33:45 +00002648 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2649 superType, ILE, false);
Steve Naroff17978c42008-03-11 17:37:02 +00002650 }
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002651 MsgExprs.push_back(SuperRep);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002652 } else {
Fariborz Jahanianff6a4552007-12-07 21:21:21 +00002653 // Remove all type-casts because it may contain objc-style types; e.g.
2654 // Foo<Proto> *.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002655 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanianff6a4552007-12-07 21:21:21 +00002656 recExpr = CE->getSubExpr();
John McCall97513962010-01-15 18:39:57 +00002657 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2658 CastExpr::CK_Unknown, recExpr);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002659 MsgExprs.push_back(recExpr);
2660 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002661 }
Steve Naroffa397efd2007-11-03 11:27:19 +00002662 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff574440f2007-10-24 22:48:43 +00002663 llvm::SmallVector<Expr*, 8> SelExprs;
2664 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002665 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00002666 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00002667 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00002668 false, argType, SourceLocation()));
Steve Naroff574440f2007-10-24 22:48:43 +00002669 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2670 &SelExprs[0], SelExprs.size());
2671 MsgExprs.push_back(SelExp);
Mike Stump11289f42009-09-09 15:08:12 +00002672
Steve Naroff574440f2007-10-24 22:48:43 +00002673 // Now push any user supplied arguments.
2674 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroffe7f18192007-11-14 23:54:14 +00002675 Expr *userExpr = Exp->getArg(i);
Steve Narofff60782b2007-11-15 02:58:25 +00002676 // Make all implicit casts explicit...ICE comes in handy:-)
2677 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2678 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregore200adc2008-10-27 19:41:14 +00002679 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002680 ? Context->getObjCIdType()
Douglas Gregore200adc2008-10-27 19:41:14 +00002681 : ICE->getType();
John McCall97513962010-01-15 18:39:57 +00002682 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CastExpr::CK_Unknown,
2683 userExpr);
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002684 }
2685 // Make id<P...> cast into an 'id' cast.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002686 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002687 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregorf19b2312008-10-28 15:36:24 +00002688 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002689 userExpr = CE->getSubExpr();
John McCall97513962010-01-15 18:39:57 +00002690 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2691 CastExpr::CK_Unknown, userExpr);
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002692 }
Mike Stump11289f42009-09-09 15:08:12 +00002693 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002694 MsgExprs.push_back(userExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00002695 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2696 // out the argument in the original expression (since we aren't deleting
2697 // the ObjCMessageExpr). See RewritePropertySetter() usage for more info.
2698 //Exp->setArg(i, 0);
Steve Naroff574440f2007-10-24 22:48:43 +00002699 }
Steve Narofff36987c2007-11-04 22:37:50 +00002700 // Generate the funky cast.
2701 CastExpr *cast;
2702 llvm::SmallVector<QualType, 8> ArgTypes;
2703 QualType returnType;
Mike Stump11289f42009-09-09 15:08:12 +00002704
Steve Narofff36987c2007-11-04 22:37:50 +00002705 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff44864e42007-11-15 10:43:57 +00002706 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2707 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2708 else
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002709 ArgTypes.push_back(Context->getObjCIdType());
2710 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattnera4997152009-02-20 18:43:26 +00002711 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Narofff36987c2007-11-04 22:37:50 +00002712 // Push any user argument types.
Chris Lattnera4997152009-02-20 18:43:26 +00002713 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2714 E = OMD->param_end(); PI != E; ++PI) {
2715 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump11289f42009-09-09 15:08:12 +00002716 ? Context->getObjCIdType()
Chris Lattnera4997152009-02-20 18:43:26 +00002717 : (*PI)->getType();
Steve Naroff52c65fa2008-10-29 14:49:46 +00002718 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffa5c0db82008-12-11 21:05:33 +00002719 if (isTopLevelBlockPointerType(t)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002720 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroff52c65fa2008-10-29 14:49:46 +00002721 t = Context->getPointerType(BPT->getPointeeType());
2722 }
Steve Naroff98eb8d12007-11-05 14:36:37 +00002723 ArgTypes.push_back(t);
2724 }
Chris Lattnera4997152009-02-20 18:43:26 +00002725 returnType = OMD->getResultType()->isObjCQualifiedIdType()
2726 ? Context->getObjCIdType() : OMD->getResultType();
Steve Narofff36987c2007-11-04 22:37:50 +00002727 } else {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002728 returnType = Context->getObjCIdType();
Steve Narofff36987c2007-11-04 22:37:50 +00002729 }
2730 // Get the type, we will need to reference it in a couple spots.
Steve Naroff7fa2f042007-11-15 10:28:18 +00002731 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002732
Steve Narofff36987c2007-11-04 22:37:50 +00002733 // Create a reference to the objc_msgSend() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00002734 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002735 SourceLocation());
Steve Narofff36987c2007-11-04 22:37:50 +00002736
Mike Stump11289f42009-09-09 15:08:12 +00002737 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Narofff36987c2007-11-04 22:37:50 +00002738 // If we don't do this cast, we get the following bizarre warning/note:
2739 // xx.m:13: warning: function called through a non-compatible type
2740 // xx.m:13: note: if this code is reached, the program will abort
John McCall97513962010-01-15 18:39:57 +00002741 cast = NoTypeInfoCStyleCastExpr(Context,
2742 Context->getPointerType(Context->VoidTy),
2743 CastExpr::CK_Unknown, DRE);
Mike Stump11289f42009-09-09 15:08:12 +00002744
Steve Narofff36987c2007-11-04 22:37:50 +00002745 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00002746 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00002747 &ArgTypes[0], ArgTypes.size(),
Steve Naroff327f0f42008-03-18 02:02:04 +00002748 // If we don't have a method decl, force a variadic cast.
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002749 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Narofff36987c2007-11-04 22:37:50 +00002750 castType = Context->getPointerType(castType);
John McCall97513962010-01-15 18:39:57 +00002751 cast = NoTypeInfoCStyleCastExpr(Context, castType, CastExpr::CK_Unknown,
2752 cast);
Steve Narofff36987c2007-11-04 22:37:50 +00002753
2754 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00002755 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump11289f42009-09-09 15:08:12 +00002756
John McCall9dd450b2009-09-21 23:43:11 +00002757 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002758 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002759 MsgExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002760 FT->getResultType(), SourceLocation());
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002761 Stmt *ReplacingStmt = CE;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002762 if (MsgSendStretFlavor) {
2763 // We have the method which returns a struct/union. Must also generate
2764 // call to objc_msgSend_stret and hang both varieties on a conditional
2765 // expression which dictate which one to envoke depending on size of
2766 // method's return type.
Mike Stump11289f42009-09-09 15:08:12 +00002767
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002768 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00002769 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002770 SourceLocation());
2771 // Need to cast objc_msgSend_stret to "void *" (see above comment).
John McCall97513962010-01-15 18:39:57 +00002772 cast = NoTypeInfoCStyleCastExpr(Context,
2773 Context->getPointerType(Context->VoidTy),
2774 CastExpr::CK_Unknown, STDRE);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002775 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00002776 castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00002777 &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002778 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002779 castType = Context->getPointerType(castType);
John McCall97513962010-01-15 18:39:57 +00002780 cast = NoTypeInfoCStyleCastExpr(Context, castType, CastExpr::CK_Unknown,
2781 cast);
Mike Stump11289f42009-09-09 15:08:12 +00002782
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002783 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00002784 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump11289f42009-09-09 15:08:12 +00002785
John McCall9dd450b2009-09-21 23:43:11 +00002786 FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002787 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002788 MsgExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002789 FT->getResultType(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002790
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002791 // Build sizeof(returnType)
Mike Stump11289f42009-09-09 15:08:12 +00002792 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
John McCallbcd03502009-12-07 02:54:59 +00002793 Context->getTrivialTypeSourceInfo(returnType),
Sebastian Redl6f282892008-11-11 17:56:53 +00002794 Context->getSizeType(),
2795 SourceLocation(), SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002796 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2797 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2798 // For X86 it is more complicated and some kind of target specific routine
2799 // is needed to decide what to do.
Mike Stump11289f42009-09-09 15:08:12 +00002800 unsigned IntSize =
Chris Lattner37e05872008-03-05 18:54:05 +00002801 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Mike Stump11289f42009-09-09 15:08:12 +00002802 IntegerLiteral *limit = new (Context) IntegerLiteral(llvm::APInt(IntSize, 8),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002803 Context->IntTy,
2804 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002805 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
2806 BinaryOperator::LE,
2807 Context->IntTy,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002808 SourceLocation());
2809 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump11289f42009-09-09 15:08:12 +00002810 ConditionalOperator *CondExpr =
Douglas Gregor7e112b02009-08-26 14:37:04 +00002811 new (Context) ConditionalOperator(lessThanExpr,
2812 SourceLocation(), CE,
2813 SourceLocation(), STCE, returnType);
Ted Kremenek5a201952009-02-07 01:47:29 +00002814 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002815 }
Mike Stump11289f42009-09-09 15:08:12 +00002816 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002817 return ReplacingStmt;
2818}
2819
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002820Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002821 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Mike Stump11289f42009-09-09 15:08:12 +00002822
Steve Naroff574440f2007-10-24 22:48:43 +00002823 // Now do the actual rewrite.
Chris Lattner2e0d2602008-01-31 19:37:57 +00002824 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00002825
2826 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002827 return ReplacingStmt;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002828}
2829
Steve Naroffd9803712009-04-29 16:37:50 +00002830// typedef struct objc_object Protocol;
2831QualType RewriteObjC::getProtocolType() {
2832 if (!ProtocolTypeDecl) {
John McCallbcd03502009-12-07 02:54:59 +00002833 TypeSourceInfo *TInfo
2834 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroffd9803712009-04-29 16:37:50 +00002835 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002836 SourceLocation(),
Steve Naroffd9803712009-04-29 16:37:50 +00002837 &Context->Idents.get("Protocol"),
John McCallbcd03502009-12-07 02:54:59 +00002838 TInfo);
Steve Naroffd9803712009-04-29 16:37:50 +00002839 }
2840 return Context->getTypeDeclType(ProtocolTypeDecl);
2841}
2842
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00002843/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroffd9803712009-04-29 16:37:50 +00002844/// a synthesized/forward data reference (to the protocol's metadata).
2845/// The forward references (and metadata) are generated in
2846/// RewriteObjC::HandleTranslationUnit().
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002847Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroffd9803712009-04-29 16:37:50 +00002848 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
2849 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump11289f42009-09-09 15:08:12 +00002850 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Douglas Gregored6c7442009-11-23 11:41:28 +00002851 ID, getProtocolType(), 0, VarDecl::Extern);
Steve Naroffd9803712009-04-29 16:37:50 +00002852 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), SourceLocation());
2853 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
2854 Context->getPointerType(DRE->getType()),
2855 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00002856 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
2857 CastExpr::CK_Unknown,
2858 DerefExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00002859 ReplaceStmt(Exp, castExpr);
2860 ProtocolExprDecls.insert(Exp->getProtocol());
Mike Stump11289f42009-09-09 15:08:12 +00002861 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffd9803712009-04-29 16:37:50 +00002862 return castExpr;
Mike Stump11289f42009-09-09 15:08:12 +00002863
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00002864}
2865
Mike Stump11289f42009-09-09 15:08:12 +00002866bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002867 const char *endBuf) {
2868 while (startBuf < endBuf) {
2869 if (*startBuf == '#') {
2870 // Skip whitespace.
2871 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2872 ;
2873 if (!strncmp(startBuf, "if", strlen("if")) ||
2874 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2875 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2876 !strncmp(startBuf, "define", strlen("define")) ||
2877 !strncmp(startBuf, "undef", strlen("undef")) ||
2878 !strncmp(startBuf, "else", strlen("else")) ||
2879 !strncmp(startBuf, "elif", strlen("elif")) ||
2880 !strncmp(startBuf, "endif", strlen("endif")) ||
2881 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2882 !strncmp(startBuf, "include", strlen("include")) ||
2883 !strncmp(startBuf, "import", strlen("import")) ||
2884 !strncmp(startBuf, "include_next", strlen("include_next")))
2885 return true;
2886 }
2887 startBuf++;
2888 }
2889 return false;
2890}
2891
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002892/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002893/// an objective-c class with ivars.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002894void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002895 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002896 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Mike Stump11289f42009-09-09 15:08:12 +00002897 assert(CDecl->getNameAsCString() &&
Douglas Gregor77324f32008-11-17 14:58:09 +00002898 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00002899 // Do not synthesize more than once.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002900 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00002901 return;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002902 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattner8d1c04f2008-03-16 21:08:55 +00002903 int NumIvars = CDecl->ivar_size();
Steve Naroffdde78982007-11-14 19:25:57 +00002904 SourceLocation LocStart = CDecl->getLocStart();
2905 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00002906
Steve Naroffdde78982007-11-14 19:25:57 +00002907 const char *startBuf = SM->getCharacterData(LocStart);
2908 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump11289f42009-09-09 15:08:12 +00002909
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00002910 // If no ivars and no root or if its root, directly or indirectly,
2911 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattner8d1c04f2008-03-16 21:08:55 +00002912 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2913 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner184e65d2009-04-14 23:22:57 +00002914 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Chris Lattner9cc55f52008-01-31 19:51:04 +00002915 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00002916 return;
2917 }
Mike Stump11289f42009-09-09 15:08:12 +00002918
2919 // FIXME: This has potential of causing problem. If
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002920 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00002921 Result += "\nstruct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002922 Result += CDecl->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +00002923 if (LangOpts.Microsoft)
2924 Result += "_IMPL";
Steve Naroffdc5b6b22008-03-12 00:25:36 +00002925
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002926 if (NumIvars > 0) {
Steve Naroffdde78982007-11-14 19:25:57 +00002927 const char *cursor = strchr(startBuf, '{');
Mike Stump11289f42009-09-09 15:08:12 +00002928 assert((cursor && endBuf)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002929 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002930 // If the buffer contains preprocessor directives, we do more fine-grained
2931 // rewrites. This is intended to fix code that looks like (which occurs in
2932 // NSURL.h, for example):
2933 //
2934 // #ifdef XYZ
2935 // @interface Foo : NSObject
2936 // #else
2937 // @interface FooBar : NSObject
2938 // #endif
2939 // {
2940 // int i;
2941 // }
2942 // @end
2943 //
2944 // This clause is segregated to avoid breaking the common case.
2945 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump11289f42009-09-09 15:08:12 +00002946 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002947 CDecl->getClassLoc();
2948 const char *endHeader = SM->getCharacterData(L);
Chris Lattner184e65d2009-04-14 23:22:57 +00002949 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002950
Chris Lattnerf5b77512009-02-20 18:18:36 +00002951 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002952 // advance to the end of the referenced protocols.
2953 while (endHeader < cursor && *endHeader != '>') endHeader++;
2954 endHeader++;
2955 }
2956 // rewrite the original header
2957 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2958 } else {
2959 // rewrite the original header *without* disturbing the '{'
Steve Naroffb0e33902009-12-04 21:36:32 +00002960 ReplaceText(LocStart, cursor-startBuf, Result.c_str(), Result.size());
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002961 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002962 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroffdde78982007-11-14 19:25:57 +00002963 Result = "\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002964 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00002965 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002966 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00002967 Result += "_IVARS;\n";
Mike Stump11289f42009-09-09 15:08:12 +00002968
Steve Naroffdde78982007-11-14 19:25:57 +00002969 // insert the super class structure definition.
Chris Lattner1780a852008-01-31 19:42:41 +00002970 SourceLocation OnePastCurly =
2971 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2972 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Naroffdde78982007-11-14 19:25:57 +00002973 }
2974 cursor++; // past '{'
Mike Stump11289f42009-09-09 15:08:12 +00002975
Steve Naroffdde78982007-11-14 19:25:57 +00002976 // Now comment out any visibility specifiers.
2977 while (cursor < endBuf) {
2978 if (*cursor == '@') {
2979 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner174a8252007-11-14 22:57:51 +00002980 // Skip whitespace.
2981 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2982 /*scan*/;
2983
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002984 // FIXME: presence of @public, etc. inside comment results in
2985 // this transformation as well, which is still correct c-code.
Steve Naroffdde78982007-11-14 19:25:57 +00002986 if (!strncmp(cursor, "public", strlen("public")) ||
2987 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffaf91b9a2008-04-04 22:34:24 +00002988 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002989 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattner1780a852008-01-31 19:42:41 +00002990 InsertText(atLoc, "// ", 3);
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002991 }
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002992 // FIXME: If there are cases where '<' is used in ivar declaration part
2993 // of user code, then scan the ivar list and use needToScanForQualifiers
2994 // for type checking.
2995 else if (*cursor == '<') {
2996 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner1780a852008-01-31 19:42:41 +00002997 InsertText(atLoc, "/* ", 3);
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002998 cursor = strchr(cursor, '>');
2999 cursor++;
3000 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner1780a852008-01-31 19:42:41 +00003001 InsertText(atLoc, " */", 3);
Steve Naroff295570a2008-10-30 12:09:33 +00003002 } else if (*cursor == '^') { // rewrite block specifier.
3003 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
3004 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003005 }
Steve Naroffdde78982007-11-14 19:25:57 +00003006 cursor++;
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003007 }
Steve Naroffdde78982007-11-14 19:25:57 +00003008 // Don't forget to add a ';'!!
Chris Lattner1780a852008-01-31 19:42:41 +00003009 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Naroffdde78982007-11-14 19:25:57 +00003010 } else { // we don't have any instance variables - insert super struct.
Chris Lattner184e65d2009-04-14 23:22:57 +00003011 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Naroffdde78982007-11-14 19:25:57 +00003012 Result += " {\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003013 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00003014 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003015 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00003016 Result += "_IVARS;\n};\n";
Chris Lattner9cc55f52008-01-31 19:51:04 +00003017 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003018 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003019 // Mark this struct as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003020 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Naroff13e74872008-05-06 18:26:51 +00003021 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003022}
3023
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003024// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003025/// class methods.
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003026template<typename MethodIterator>
3027void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
3028 MethodIterator MethodEnd,
Fariborz Jahanian3df412a2007-10-25 00:14:44 +00003029 bool IsInstanceMethod,
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003030 const char *prefix,
Chris Lattner211f8b82007-10-25 17:07:24 +00003031 const char *ClassName,
3032 std::string &Result) {
Chris Lattner31bc07e2007-12-12 07:46:12 +00003033 if (MethodBegin == MethodEnd) return;
Mike Stump11289f42009-09-09 15:08:12 +00003034
Chris Lattner31bc07e2007-12-12 07:46:12 +00003035 if (!objc_impl_method) {
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003036 /* struct _objc_method {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003037 SEL _cmd;
3038 char *method_types;
3039 void *_imp;
3040 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003041 */
Chris Lattner211f8b82007-10-25 17:07:24 +00003042 Result += "\nstruct _objc_method {\n";
3043 Result += "\tSEL _cmd;\n";
3044 Result += "\tchar *method_types;\n";
3045 Result += "\tvoid *_imp;\n";
3046 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003047
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003048 objc_impl_method = true;
Fariborz Jahanian74a1cfa2007-10-19 00:36:46 +00003049 }
Mike Stump11289f42009-09-09 15:08:12 +00003050
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003051 // Build _objc_method_list for class's methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003052
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003053 /* struct {
3054 struct _objc_method_list *next_method;
3055 int method_count;
3056 struct _objc_method method_list[];
3057 }
3058 */
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003059 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003060 Result += "\nstatic struct {\n";
3061 Result += "\tstruct _objc_method_list *next_method;\n";
3062 Result += "\tint method_count;\n";
3063 Result += "\tstruct _objc_method method_list[";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003064 Result += utostr(NumMethods);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003065 Result += "];\n} _OBJC_";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003066 Result += prefix;
3067 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
3068 Result += "_METHODS_";
3069 Result += ClassName;
Steve Naroffb327e492008-03-12 17:18:30 +00003070 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003071 Result += IsInstanceMethod ? "inst" : "cls";
3072 Result += "_meth\")))= ";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003073 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003074
Chris Lattner31bc07e2007-12-12 07:46:12 +00003075 Result += "\t,{{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00003076 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattner31bc07e2007-12-12 07:46:12 +00003077 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003078 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattner31bc07e2007-12-12 07:46:12 +00003079 Result += "\", \"";
3080 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003081 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003082 Result += MethodInternalNames[*MethodBegin];
3083 Result += "}\n";
3084 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3085 Result += "\t ,{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00003086 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003087 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003088 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003089 Result += "\", \"";
3090 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003091 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003092 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanian56338352007-11-13 21:02:00 +00003093 Result += "}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003094 }
Chris Lattner31bc07e2007-12-12 07:46:12 +00003095 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003096}
3097
Steve Naroffd9803712009-04-29 16:37:50 +00003098/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner390d39a2008-07-21 21:32:27 +00003099void RewriteObjC::
Steve Naroffd9803712009-04-29 16:37:50 +00003100RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, const char *prefix,
3101 const char *ClassName, std::string &Result) {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003102 static bool objc_protocol_methods = false;
Steve Naroffd9803712009-04-29 16:37:50 +00003103
3104 // Output struct protocol_methods holder of method selector and type.
3105 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3106 /* struct protocol_methods {
3107 SEL _cmd;
3108 char *method_types;
3109 }
3110 */
3111 Result += "\nstruct _protocol_methods {\n";
3112 Result += "\tstruct objc_selector *_cmd;\n";
3113 Result += "\tchar *method_types;\n";
3114 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003115
Steve Naroffd9803712009-04-29 16:37:50 +00003116 objc_protocol_methods = true;
3117 }
3118 // Do not synthesize the protocol more than once.
3119 if (ObjCSynthesizedProtocols.count(PDecl))
3120 return;
Mike Stump11289f42009-09-09 15:08:12 +00003121
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003122 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3123 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3124 PDecl->instmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003125 /* struct _objc_protocol_method_list {
3126 int protocol_method_count;
3127 struct protocol_methods protocols[];
3128 }
Steve Naroff251084d2008-03-12 01:06:30 +00003129 */
Steve Naroffd9803712009-04-29 16:37:50 +00003130 Result += "\nstatic struct {\n";
3131 Result += "\tint protocol_method_count;\n";
3132 Result += "\tstruct _protocol_methods protocol_methods[";
3133 Result += utostr(NumMethods);
3134 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3135 Result += PDecl->getNameAsString();
3136 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3137 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003138
Steve Naroffd9803712009-04-29 16:37:50 +00003139 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003140 for (ObjCProtocolDecl::instmeth_iterator
3141 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003142 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003143 if (I == PDecl->instmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003144 Result += "\t ,{{(struct objc_selector *)\"";
3145 else
3146 Result += "\t ,{(struct objc_selector *)\"";
3147 Result += (*I)->getSelector().getAsString().c_str();
3148 std::string MethodTypeString;
3149 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3150 Result += "\", \"";
3151 Result += MethodTypeString;
3152 Result += "\"}\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003153 }
Steve Naroffd9803712009-04-29 16:37:50 +00003154 Result += "\t }\n};\n";
3155 }
Mike Stump11289f42009-09-09 15:08:12 +00003156
Steve Naroffd9803712009-04-29 16:37:50 +00003157 // Output class methods declared in this protocol.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003158 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3159 PDecl->classmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003160 if (NumMethods > 0) {
3161 /* struct _objc_protocol_method_list {
3162 int protocol_method_count;
3163 struct protocol_methods protocols[];
3164 }
3165 */
3166 Result += "\nstatic struct {\n";
3167 Result += "\tint protocol_method_count;\n";
3168 Result += "\tstruct _protocol_methods protocol_methods[";
3169 Result += utostr(NumMethods);
3170 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3171 Result += PDecl->getNameAsString();
3172 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3173 "{\n\t";
3174 Result += utostr(NumMethods);
3175 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003176
Steve Naroffd9803712009-04-29 16:37:50 +00003177 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003178 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003179 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003180 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003181 if (I == PDecl->classmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003182 Result += "\t ,{{(struct objc_selector *)\"";
3183 else
3184 Result += "\t ,{(struct objc_selector *)\"";
3185 Result += (*I)->getSelector().getAsString().c_str();
3186 std::string MethodTypeString;
3187 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3188 Result += "\", \"";
3189 Result += MethodTypeString;
3190 Result += "\"}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003191 }
Steve Naroffd9803712009-04-29 16:37:50 +00003192 Result += "\t }\n};\n";
3193 }
3194
3195 // Output:
3196 /* struct _objc_protocol {
3197 // Objective-C 1.0 extensions
3198 struct _objc_protocol_extension *isa;
3199 char *protocol_name;
3200 struct _objc_protocol **protocol_list;
3201 struct _objc_protocol_method_list *instance_methods;
3202 struct _objc_protocol_method_list *class_methods;
Mike Stump11289f42009-09-09 15:08:12 +00003203 };
Steve Naroffd9803712009-04-29 16:37:50 +00003204 */
3205 static bool objc_protocol = false;
3206 if (!objc_protocol) {
3207 Result += "\nstruct _objc_protocol {\n";
3208 Result += "\tstruct _objc_protocol_extension *isa;\n";
3209 Result += "\tchar *protocol_name;\n";
3210 Result += "\tstruct _objc_protocol **protocol_list;\n";
3211 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3212 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003213 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003214
Steve Naroffd9803712009-04-29 16:37:50 +00003215 objc_protocol = true;
Chris Lattner388f6e92008-07-21 21:33:21 +00003216 }
Mike Stump11289f42009-09-09 15:08:12 +00003217
Steve Naroffd9803712009-04-29 16:37:50 +00003218 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3219 Result += PDecl->getNameAsString();
3220 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3221 "{\n\t0, \"";
3222 Result += PDecl->getNameAsString();
3223 Result += "\", 0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003224 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003225 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3226 Result += PDecl->getNameAsString();
3227 Result += ", ";
3228 }
3229 else
3230 Result += "0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003231 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003232 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3233 Result += PDecl->getNameAsString();
3234 Result += "\n";
3235 }
3236 else
3237 Result += "0\n";
3238 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003239
Steve Naroffd9803712009-04-29 16:37:50 +00003240 // Mark this protocol as having been generated.
3241 if (!ObjCSynthesizedProtocols.insert(PDecl))
3242 assert(false && "protocol already synthesized");
3243
3244}
3245
3246void RewriteObjC::
3247RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
3248 const char *prefix, const char *ClassName,
3249 std::string &Result) {
3250 if (Protocols.empty()) return;
Mike Stump11289f42009-09-09 15:08:12 +00003251
Steve Naroffd9803712009-04-29 16:37:50 +00003252 for (unsigned i = 0; i != Protocols.size(); i++)
3253 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3254
Chris Lattner388f6e92008-07-21 21:33:21 +00003255 // Output the top lovel protocol meta-data for the class.
3256 /* struct _objc_protocol_list {
3257 struct _objc_protocol_list *next;
3258 int protocol_count;
3259 struct _objc_protocol *class_protocols[];
3260 }
3261 */
3262 Result += "\nstatic struct {\n";
3263 Result += "\tstruct _objc_protocol_list *next;\n";
3264 Result += "\tint protocol_count;\n";
3265 Result += "\tstruct _objc_protocol *class_protocols[";
3266 Result += utostr(Protocols.size());
3267 Result += "];\n} _OBJC_";
3268 Result += prefix;
3269 Result += "_PROTOCOLS_";
3270 Result += ClassName;
3271 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3272 "{\n\t0, ";
3273 Result += utostr(Protocols.size());
3274 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003275
Chris Lattner388f6e92008-07-21 21:33:21 +00003276 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003277 Result += Protocols[0]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003278 Result += " \n";
Mike Stump11289f42009-09-09 15:08:12 +00003279
Chris Lattner388f6e92008-07-21 21:33:21 +00003280 for (unsigned i = 1; i != Protocols.size(); i++) {
3281 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003282 Result += Protocols[i]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003283 Result += "\n";
3284 }
3285 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003286}
3287
Steve Naroffd9803712009-04-29 16:37:50 +00003288
Mike Stump11289f42009-09-09 15:08:12 +00003289/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003290/// implementation.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003291void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003292 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003293 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003294 // Find category declaration for this implementation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003295 ObjCCategoryDecl *CDecl;
Mike Stump11289f42009-09-09 15:08:12 +00003296 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003297 CDecl = CDecl->getNextClassCategory())
3298 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3299 break;
Mike Stump11289f42009-09-09 15:08:12 +00003300
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003301 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003302 FullCategoryName += '_';
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003303 FullCategoryName += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003304
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003305 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003306 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003307 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003308
3309 // If any of our property implementations have associated getters or
3310 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003311 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3312 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003313 Prop != PropEnd; ++Prop) {
3314 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3315 continue;
3316 if (!(*Prop)->getPropertyIvarDecl())
3317 continue;
3318 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3319 if (!PD)
3320 continue;
3321 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3322 InstanceMethods.push_back(Getter);
3323 if (PD->isReadOnly())
3324 continue;
3325 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3326 InstanceMethods.push_back(Setter);
3327 }
3328 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003329 true, "CATEGORY_", FullCategoryName.c_str(),
3330 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003331
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003332 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003333 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003334 false, "CATEGORY_", FullCategoryName.c_str(),
3335 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003336
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003337 // Protocols referenced in class declaration?
Fariborz Jahanian989e0392007-11-13 22:09:49 +00003338 // Null CDecl is case of a category implementation with no category interface
3339 if (CDecl)
Steve Naroffd9803712009-04-29 16:37:50 +00003340 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
3341 FullCategoryName.c_str(), Result);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003342 /* struct _objc_category {
3343 char *category_name;
3344 char *class_name;
3345 struct _objc_method_list *instance_methods;
3346 struct _objc_method_list *class_methods;
3347 struct _objc_protocol_list *protocols;
3348 // Objective-C 1.0 extensions
3349 uint32_t size; // sizeof (struct _objc_category)
Mike Stump11289f42009-09-09 15:08:12 +00003350 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003351 // @property decl.
Mike Stump11289f42009-09-09 15:08:12 +00003352 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003353 */
Mike Stump11289f42009-09-09 15:08:12 +00003354
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003355 static bool objc_category = false;
3356 if (!objc_category) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003357 Result += "\nstruct _objc_category {\n";
3358 Result += "\tchar *category_name;\n";
3359 Result += "\tchar *class_name;\n";
3360 Result += "\tstruct _objc_method_list *instance_methods;\n";
3361 Result += "\tstruct _objc_method_list *class_methods;\n";
3362 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003363 Result += "\tunsigned int size;\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003364 Result += "\tstruct _objc_property_list *instance_properties;\n";
3365 Result += "};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003366 objc_category = true;
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003367 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003368 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3369 Result += FullCategoryName;
Steve Naroffb327e492008-03-12 17:18:30 +00003370 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003371 Result += IDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003372 Result += "\"\n\t, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003373 Result += ClassDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003374 Result += "\"\n";
Mike Stump11289f42009-09-09 15:08:12 +00003375
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003376 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003377 Result += "\t, (struct _objc_method_list *)"
3378 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3379 Result += FullCategoryName;
3380 Result += "\n";
3381 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003382 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003383 Result += "\t, 0\n";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003384 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003385 Result += "\t, (struct _objc_method_list *)"
3386 "&_OBJC_CATEGORY_CLASS_METHODS_";
3387 Result += FullCategoryName;
3388 Result += "\n";
3389 }
3390 else
3391 Result += "\t, 0\n";
Mike Stump11289f42009-09-09 15:08:12 +00003392
Chris Lattnerf5b77512009-02-20 18:18:36 +00003393 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump11289f42009-09-09 15:08:12 +00003394 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003395 Result += FullCategoryName;
3396 Result += "\n";
3397 }
3398 else
3399 Result += "\t, 0\n";
3400 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003401}
3402
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003403/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3404/// ivar offset.
Mike Stump11289f42009-09-09 15:08:12 +00003405void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
3406 ObjCIvarDecl *ivar,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003407 std::string &Result) {
Steve Naroffde7d0f62008-07-16 18:22:22 +00003408 if (ivar->isBitField()) {
3409 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3410 // place all bitfields at offset 0.
3411 Result += "0";
3412 } else {
3413 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003414 Result += IDecl->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003415 if (LangOpts.Microsoft)
3416 Result += "_IMPL";
3417 Result += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003418 Result += ivar->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003419 Result += ")";
3420 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003421}
3422
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003423//===----------------------------------------------------------------------===//
3424// Meta Data Emission
3425//===----------------------------------------------------------------------===//
3426
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003427void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003428 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003429 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump11289f42009-09-09 15:08:12 +00003430
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003431 // Explictly declared @interface's are already synthesized.
Steve Naroffaac654a2009-04-20 20:09:33 +00003432 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump11289f42009-09-09 15:08:12 +00003433 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003434 // produce correct synthesis as yet.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003435 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003436 }
Mike Stump11289f42009-09-09 15:08:12 +00003437
Chris Lattner30d23e82007-12-12 07:56:42 +00003438 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003439 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump11289f42009-09-09 15:08:12 +00003440 ? IDecl->ivar_size()
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003441 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003442 if (NumIvars > 0) {
3443 static bool objc_ivar = false;
3444 if (!objc_ivar) {
3445 /* struct _objc_ivar {
3446 char *ivar_name;
3447 char *ivar_type;
3448 int ivar_offset;
Mike Stump11289f42009-09-09 15:08:12 +00003449 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003450 */
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003451 Result += "\nstruct _objc_ivar {\n";
3452 Result += "\tchar *ivar_name;\n";
3453 Result += "\tchar *ivar_type;\n";
3454 Result += "\tint ivar_offset;\n";
3455 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003456
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003457 objc_ivar = true;
3458 }
3459
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003460 /* struct {
3461 int ivar_count;
3462 struct _objc_ivar ivar_list[nIvars];
Mike Stump11289f42009-09-09 15:08:12 +00003463 };
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003464 */
Mike Stump11289f42009-09-09 15:08:12 +00003465 Result += "\nstatic struct {\n";
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003466 Result += "\tint ivar_count;\n";
3467 Result += "\tstruct _objc_ivar ivar_list[";
3468 Result += utostr(NumIvars);
3469 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003470 Result += IDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003471 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003472 "{\n\t";
3473 Result += utostr(NumIvars);
3474 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003475
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003476 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor5f662052009-04-23 03:23:08 +00003477 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003478 if (!IDecl->ivar_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00003479 for (ObjCImplementationDecl::ivar_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003480 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor5f662052009-04-23 03:23:08 +00003481 IV != IVEnd; ++IV)
3482 IVars.push_back(*IV);
3483 IVI = IVars.begin();
3484 IVE = IVars.end();
Chris Lattner30d23e82007-12-12 07:56:42 +00003485 } else {
3486 IVI = CDecl->ivar_begin();
3487 IVE = CDecl->ivar_end();
3488 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003489 Result += "\t,{{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003490 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003491 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003492 std::string TmpString, StrEncoding;
3493 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3494 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003495 Result += StrEncoding;
3496 Result += "\", ";
Chris Lattner30d23e82007-12-12 07:56:42 +00003497 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003498 Result += "}\n";
Chris Lattner30d23e82007-12-12 07:56:42 +00003499 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003500 Result += "\t ,{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003501 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003502 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003503 std::string TmpString, StrEncoding;
3504 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3505 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003506 Result += StrEncoding;
3507 Result += "\", ";
Chris Lattner30d23e82007-12-12 07:56:42 +00003508 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003509 Result += "}\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003510 }
Mike Stump11289f42009-09-09 15:08:12 +00003511
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003512 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003513 }
Mike Stump11289f42009-09-09 15:08:12 +00003514
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003515 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003516 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003517 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003518
3519 // If any of our property implementations have associated getters or
3520 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003521 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3522 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003523 Prop != PropEnd; ++Prop) {
3524 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3525 continue;
3526 if (!(*Prop)->getPropertyIvarDecl())
3527 continue;
3528 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3529 if (!PD)
3530 continue;
3531 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3532 InstanceMethods.push_back(Getter);
3533 if (PD->isReadOnly())
3534 continue;
3535 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3536 InstanceMethods.push_back(Setter);
3537 }
3538 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattner86d7d912008-11-24 03:54:41 +00003539 true, "", IDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003540
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003541 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003542 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner86d7d912008-11-24 03:54:41 +00003543 false, "", IDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003544
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003545 // Protocols referenced in class declaration?
Steve Naroffd9803712009-04-29 16:37:50 +00003546 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
3547 "CLASS", CDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003548
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003549 // Declaration of class/meta-class metadata
3550 /* struct _objc_class {
3551 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003552 const char *super_class_name;
3553 char *name;
3554 long version;
3555 long info;
3556 long instance_size;
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003557 struct _objc_ivar_list *ivars;
3558 struct _objc_method_list *methods;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003559 struct objc_cache *cache;
3560 struct objc_protocol_list *protocols;
3561 const char *ivar_layout;
3562 struct _objc_class_ext *ext;
Mike Stump11289f42009-09-09 15:08:12 +00003563 };
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003564 */
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003565 static bool objc_class = false;
3566 if (!objc_class) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003567 Result += "\nstruct _objc_class {\n";
3568 Result += "\tstruct _objc_class *isa;\n";
3569 Result += "\tconst char *super_class_name;\n";
3570 Result += "\tchar *name;\n";
3571 Result += "\tlong version;\n";
3572 Result += "\tlong info;\n";
3573 Result += "\tlong instance_size;\n";
3574 Result += "\tstruct _objc_ivar_list *ivars;\n";
3575 Result += "\tstruct _objc_method_list *methods;\n";
3576 Result += "\tstruct objc_cache *cache;\n";
3577 Result += "\tstruct _objc_protocol_list *protocols;\n";
3578 Result += "\tconst char *ivar_layout;\n";
3579 Result += "\tstruct _objc_class_ext *ext;\n";
3580 Result += "};\n";
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003581 objc_class = true;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003582 }
Mike Stump11289f42009-09-09 15:08:12 +00003583
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003584 // Meta-class metadata generation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003585 ObjCInterfaceDecl *RootClass = 0;
3586 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003587 while (SuperClass) {
3588 RootClass = SuperClass;
3589 SuperClass = SuperClass->getSuperClass();
3590 }
3591 SuperClass = CDecl->getSuperClass();
Mike Stump11289f42009-09-09 15:08:12 +00003592
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003593 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003594 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003595 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003596 "{\n\t(struct _objc_class *)\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003597 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003598 Result += "\"";
3599
3600 if (SuperClass) {
3601 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003602 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003603 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003604 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003605 Result += "\"";
3606 }
3607 else {
3608 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003609 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003610 Result += "\"";
3611 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003612 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003613 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003614 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003615 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff0b844f02008-03-11 18:14:26 +00003616 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003617 Result += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003618 Result += "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003619 }
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003620 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003621 Result += ", 0\n";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003622 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003623 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003624 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003625 Result += ",0,0\n";
3626 }
Fariborz Jahanian486f7182007-10-24 20:54:23 +00003627 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003628 Result += "\t,0,0,0,0\n";
3629 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003630
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003631 // class metadata generation.
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003632 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003633 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003634 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003635 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003636 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003637 if (SuperClass) {
3638 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003639 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003640 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003641 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003642 Result += "\"";
3643 }
3644 else {
3645 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003646 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003647 Result += "\"";
3648 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003649 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003650 Result += ", 0,1";
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003651 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003652 Result += ",0";
3653 else {
3654 // class has size. Must synthesize its size.
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00003655 Result += ",sizeof(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003656 Result += CDecl->getNameAsString();
Steve Naroff14a07462008-03-10 23:33:22 +00003657 if (LangOpts.Microsoft)
3658 Result += "_IMPL";
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003659 Result += ")";
3660 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003661 if (NumIvars > 0) {
Steve Naroff17978c42008-03-11 17:37:02 +00003662 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003663 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003664 Result += "\n\t";
3665 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003666 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003667 Result += ",0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003668 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003669 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003670 Result += CDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003671 Result += ", 0\n\t";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003672 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003673 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003674 Result += ",0,0";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003675 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003676 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003677 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003678 Result += ", 0,0\n";
3679 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003680 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003681 Result += ",0,0,0\n";
3682 Result += "};\n";
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003683}
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003684
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003685/// RewriteImplementations - This routine rewrites all method implementations
3686/// and emits meta-data.
3687
Steve Narofff8cfd162008-11-13 20:07:04 +00003688void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003689 int ClsDefCount = ClassImplementation.size();
3690 int CatDefCount = CategoryImplementation.size();
Mike Stump11289f42009-09-09 15:08:12 +00003691
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003692 // Rewrite implemented methods
3693 for (int i = 0; i < ClsDefCount; i++)
3694 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump11289f42009-09-09 15:08:12 +00003695
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00003696 for (int i = 0; i < CatDefCount; i++)
3697 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofff8cfd162008-11-13 20:07:04 +00003698}
Mike Stump11289f42009-09-09 15:08:12 +00003699
Steve Narofff8cfd162008-11-13 20:07:04 +00003700void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3701 int ClsDefCount = ClassImplementation.size();
3702 int CatDefCount = CategoryImplementation.size();
3703
Steve Naroff30ac2222008-05-07 21:23:49 +00003704 // This is needed for determining instance variable offsets.
Fariborz Jahanian9ab63492010-01-07 18:31:42 +00003705 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003706 // For each implemented class, write out all its meta data.
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003707 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003708 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump11289f42009-09-09 15:08:12 +00003709
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003710 // For each implemented category, write out all its meta data.
3711 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003712 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroffd9803712009-04-29 16:37:50 +00003713
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003714 // Write objc_symtab metadata
3715 /*
3716 struct _objc_symtab
3717 {
3718 long sel_ref_cnt;
3719 SEL *refs;
3720 short cls_def_cnt;
3721 short cat_def_cnt;
3722 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump11289f42009-09-09 15:08:12 +00003723 };
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003724 */
Mike Stump11289f42009-09-09 15:08:12 +00003725
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003726 Result += "\nstruct _objc_symtab {\n";
3727 Result += "\tlong sel_ref_cnt;\n";
3728 Result += "\tSEL *refs;\n";
3729 Result += "\tshort cls_def_cnt;\n";
3730 Result += "\tshort cat_def_cnt;\n";
3731 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3732 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00003733
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003734 Result += "static struct _objc_symtab "
Steve Naroffb327e492008-03-12 17:18:30 +00003735 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003736 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003737 + ", " + utostr(CatDefCount) + "\n";
3738 for (int i = 0; i < ClsDefCount; i++) {
3739 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003740 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003741 Result += "\n";
3742 }
Mike Stump11289f42009-09-09 15:08:12 +00003743
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003744 for (int i = 0; i < CatDefCount; i++) {
3745 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003746 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003747 Result += "_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003748 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003749 Result += "\n";
3750 }
Mike Stump11289f42009-09-09 15:08:12 +00003751
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003752 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00003753
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003754 // Write objc_module metadata
Mike Stump11289f42009-09-09 15:08:12 +00003755
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003756 /*
3757 struct _objc_module {
3758 long version;
3759 long size;
3760 const char *name;
3761 struct _objc_symtab *symtab;
3762 }
3763 */
Mike Stump11289f42009-09-09 15:08:12 +00003764
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003765 Result += "\nstruct _objc_module {\n";
3766 Result += "\tlong version;\n";
3767 Result += "\tlong size;\n";
3768 Result += "\tconst char *name;\n";
3769 Result += "\tstruct _objc_symtab *symtab;\n";
3770 Result += "};\n\n";
3771 Result += "static struct _objc_module "
Steve Naroffb327e492008-03-12 17:18:30 +00003772 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003773 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003774 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003775 Result += "};\n\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00003776
3777 if (LangOpts.Microsoft) {
Steve Naroffd9803712009-04-29 16:37:50 +00003778 if (ProtocolExprDecls.size()) {
3779 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
3780 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump11289f42009-09-09 15:08:12 +00003781 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00003782 E = ProtocolExprDecls.end(); I != E; ++I) {
3783 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
3784 Result += (*I)->getNameAsString();
3785 Result += " = &_OBJC_PROTOCOL_";
3786 Result += (*I)->getNameAsString();
3787 Result += ";\n";
3788 }
3789 Result += "#pragma data_seg(pop)\n\n";
3790 }
Steve Naroff945a3b12008-03-10 20:43:59 +00003791 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroffcab93d52008-05-07 00:06:16 +00003792 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00003793 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3794 Result += "&_OBJC_MODULES;\n";
3795 Result += "#pragma data_seg(pop)\n\n";
3796 }
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003797}
Chris Lattnera7c19fe2007-10-16 22:36:42 +00003798
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00003799void RewriteObjC::RewriteByRefString(std::string &ResultStr,
3800 const std::string &Name,
3801 ValueDecl *VD) {
3802 assert(BlockByRefDeclNo.count(VD) &&
3803 "RewriteByRefString: ByRef decl missing");
3804 ResultStr += "struct __Block_byref_" + Name +
3805 "_" + utostr(BlockByRefDeclNo[VD]) ;
3806}
3807
Steve Naroff677ab3a2008-10-27 17:20:55 +00003808std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3809 const char *funcName,
3810 std::string Tag) {
3811 const FunctionType *AFT = CE->getFunctionType();
3812 QualType RT = AFT->getResultType();
3813 std::string StructRef = "struct " + Tag;
3814 std::string S = "static " + RT.getAsString() + " __" +
3815 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00003816
Steve Naroff677ab3a2008-10-27 17:20:55 +00003817 BlockDecl *BD = CE->getBlockDecl();
Mike Stump11289f42009-09-09 15:08:12 +00003818
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003819 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump11289f42009-09-09 15:08:12 +00003820 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Narofff26a1d42009-02-02 17:19:26 +00003821 // block (to reference imported block decl refs).
3822 S += "(" + StructRef + " *__cself)";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003823 } else if (BD->param_empty()) {
3824 S += "(" + StructRef + " *__cself)";
3825 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003826 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003827 assert(FT && "SynthesizeBlockFunc: No function proto");
3828 S += '(';
3829 // first add the implicit argument.
3830 S += StructRef + " *__cself, ";
3831 std::string ParamStr;
3832 for (BlockDecl::param_iterator AI = BD->param_begin(),
3833 E = BD->param_end(); AI != E; ++AI) {
3834 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003835 ParamStr = (*AI)->getNameAsString();
Douglas Gregor7de59662009-05-29 20:38:28 +00003836 (*AI)->getType().getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003837 S += ParamStr;
3838 }
3839 if (FT->isVariadic()) {
3840 if (!BD->param_empty()) S += ", ";
3841 S += "...";
3842 }
3843 S += ')';
3844 }
3845 S += " {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003846
Steve Naroff677ab3a2008-10-27 17:20:55 +00003847 // Create local declarations to avoid rewriting all closure decl ref exprs.
3848 // First, emit a declaration for all "by ref" decls.
Mike Stump11289f42009-09-09 15:08:12 +00003849 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003850 E = BlockByRefDecls.end(); I != E; ++I) {
3851 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003852 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00003853 std::string TypeString;
3854 RewriteByRefString(TypeString, Name, (*I));
3855 TypeString += " *";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00003856 Name = TypeString + Name;
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003857 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump11289f42009-09-09 15:08:12 +00003858 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003859 // Next, emit a declaration for all "by copy" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00003860 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003861 E = BlockByCopyDecls.end(); I != E; ++I) {
3862 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003863 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003864 // Handle nested closure invocation. For example:
3865 //
3866 // void (^myImportedClosure)(void);
3867 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003868 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003869 // void (^anotherClosure)(void);
3870 // anotherClosure = ^(void) {
3871 // myImportedClosure(); // import and invoke the closure
3872 // };
3873 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003874 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00003875 S += "struct __block_impl *";
3876 else
Douglas Gregor7de59662009-05-29 20:38:28 +00003877 (*I)->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003878 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003879 }
3880 std::string RewrittenStr = RewrittenBlockExprs[CE];
3881 const char *cstr = RewrittenStr.c_str();
3882 while (*cstr++ != '{') ;
3883 S += cstr;
3884 S += "\n";
3885 return S;
3886}
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00003887
Steve Naroff677ab3a2008-10-27 17:20:55 +00003888std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3889 const char *funcName,
3890 std::string Tag) {
3891 std::string StructRef = "struct " + Tag;
3892 std::string S = "static void __";
Mike Stump11289f42009-09-09 15:08:12 +00003893
Steve Naroff677ab3a2008-10-27 17:20:55 +00003894 S += funcName;
3895 S += "_block_copy_" + utostr(i);
3896 S += "(" + StructRef;
3897 S += "*dst, " + StructRef;
3898 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00003899 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003900 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00003901 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003902 S += (*I)->getNameAsString();
Steve Naroff5ac4eac2008-12-11 20:51:38 +00003903 S += ", (void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003904 S += (*I)->getNameAsString();
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003905 if (BlockByRefDecls.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003906 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003907 else
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003908 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003909 }
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003910 S += "}\n";
3911
Steve Naroff677ab3a2008-10-27 17:20:55 +00003912 S += "\nstatic void __";
3913 S += funcName;
3914 S += "_block_dispose_" + utostr(i);
3915 S += "(" + StructRef;
3916 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00003917 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003918 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00003919 S += "_Block_object_dispose((void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003920 S += (*I)->getNameAsString();
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003921 if (BlockByRefDecls.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003922 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003923 else
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003924 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003925 }
Mike Stump11289f42009-09-09 15:08:12 +00003926 S += "}\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003927 return S;
3928}
3929
Steve Naroff30484702009-12-06 21:14:13 +00003930std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3931 std::string Desc) {
Steve Naroff295570a2008-10-30 12:09:33 +00003932 std::string S = "\nstruct " + Tag;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003933 std::string Constructor = " " + Tag;
Mike Stump11289f42009-09-09 15:08:12 +00003934
Steve Naroff677ab3a2008-10-27 17:20:55 +00003935 S += " {\n struct __block_impl impl;\n";
Steve Naroff30484702009-12-06 21:14:13 +00003936 S += " struct " + Desc;
3937 S += "* Desc;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003938
Steve Naroff30484702009-12-06 21:14:13 +00003939 Constructor += "(void *fp, "; // Invoke function pointer.
3940 Constructor += "struct " + Desc; // Descriptor pointer.
3941 Constructor += " *desc";
Mike Stump11289f42009-09-09 15:08:12 +00003942
Steve Naroff677ab3a2008-10-27 17:20:55 +00003943 if (BlockDeclRefs.size()) {
3944 // Output all "by copy" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00003945 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003946 E = BlockByCopyDecls.end(); I != E; ++I) {
3947 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003948 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003949 std::string ArgName = "_" + FieldName;
3950 // Handle nested closure invocation. For example:
3951 //
3952 // void (^myImportedBlock)(void);
3953 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003954 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003955 // void (^anotherBlock)(void);
3956 // anotherBlock = ^(void) {
3957 // myImportedBlock(); // import and invoke the closure
3958 // };
3959 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003960 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00003961 S += "struct __block_impl *";
3962 Constructor += ", void *" + ArgName;
3963 } else {
Douglas Gregor7de59662009-05-29 20:38:28 +00003964 (*I)->getType().getAsStringInternal(FieldName, Context->PrintingPolicy);
3965 (*I)->getType().getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003966 Constructor += ", " + ArgName;
3967 }
3968 S += FieldName + ";\n";
3969 }
3970 // Output all "by ref" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00003971 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003972 E = BlockByRefDecls.end(); I != E; ++I) {
3973 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003974 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003975 std::string ArgName = "_" + FieldName;
3976 // Handle nested closure invocation. For example:
3977 //
3978 // void (^myImportedBlock)(void);
3979 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003980 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003981 // void (^anotherBlock)(void);
3982 // anotherBlock = ^(void) {
3983 // myImportedBlock(); // import and invoke the closure
3984 // };
3985 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003986 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00003987 S += "struct __block_impl *";
3988 Constructor += ", void *" + ArgName;
3989 } else {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00003990 std::string TypeString;
3991 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian02e07732009-12-23 02:07:37 +00003992 TypeString += " *";
3993 FieldName = TypeString + FieldName;
3994 ArgName = TypeString + ArgName;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003995 Constructor += ", " + ArgName;
3996 }
3997 S += FieldName + "; // by ref\n";
3998 }
3999 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00004000 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00004001 if (GlobalVarDecl)
4002 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4003 else
4004 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00004005 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump11289f42009-09-09 15:08:12 +00004006
Steve Naroff30484702009-12-06 21:14:13 +00004007 Constructor += " Desc = desc;\n";
Mike Stump11289f42009-09-09 15:08:12 +00004008
Steve Naroff677ab3a2008-10-27 17:20:55 +00004009 // Initialize all "by copy" arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004010 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004011 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004012 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004013 Constructor += " ";
Steve Naroffa5c0db82008-12-11 21:05:33 +00004014 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004015 Constructor += Name + " = (struct __block_impl *)_";
4016 else
4017 Constructor += Name + " = _";
4018 Constructor += Name + ";\n";
4019 }
4020 // Initialize all "by ref" arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004021 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004022 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004023 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004024 Constructor += " ";
Steve Naroffa5c0db82008-12-11 21:05:33 +00004025 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004026 Constructor += Name + " = (struct __block_impl *)_";
4027 else
4028 Constructor += Name + " = _";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004029 Constructor += Name + "->__forwarding;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004030 }
4031 } else {
4032 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00004033 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00004034 if (GlobalVarDecl)
4035 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4036 else
4037 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00004038 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4039 Constructor += " Desc = desc;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004040 }
4041 Constructor += " ";
4042 Constructor += "}\n";
4043 S += Constructor;
4044 S += "};\n";
4045 return S;
4046}
4047
Steve Naroff30484702009-12-06 21:14:13 +00004048std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
4049 std::string ImplTag, int i,
4050 const char *FunName,
4051 unsigned hasCopy) {
4052 std::string S = "\nstatic struct " + DescTag;
4053
4054 S += " {\n unsigned long reserved;\n";
4055 S += " unsigned long Block_size;\n";
4056 if (hasCopy) {
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00004057 S += " void (*copy)(struct ";
4058 S += ImplTag; S += "*, struct ";
4059 S += ImplTag; S += "*);\n";
4060
4061 S += " void (*dispose)(struct ";
4062 S += ImplTag; S += "*);\n";
Steve Naroff30484702009-12-06 21:14:13 +00004063 }
4064 S += "} ";
4065
4066 S += DescTag + "_DATA = { 0, sizeof(struct ";
4067 S += ImplTag + ")";
4068 if (hasCopy) {
4069 S += ", __" + std::string(FunName) + "_block_copy_" + utostr(i);
4070 S += ", __" + std::string(FunName) + "_block_dispose_" + utostr(i);
4071 }
4072 S += "};\n";
4073 return S;
4074}
4075
Steve Naroff677ab3a2008-10-27 17:20:55 +00004076void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004077 const char *FunName) {
4078 // Insert declaration for the function in which block literal is used.
Fariborz Jahanian5c26eee2010-01-15 18:14:52 +00004079 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004080 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004081 // Insert closures that were part of the function.
4082 for (unsigned i = 0; i < Blocks.size(); i++) {
4083
4084 CollectBlockDeclRefInfo(Blocks[i]);
4085
Steve Naroff30484702009-12-06 21:14:13 +00004086 std::string ImplTag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
4087 std::string DescTag = "__" + std::string(FunName) + "_block_desc_" + utostr(i);
Mike Stump11289f42009-09-09 15:08:12 +00004088
Steve Naroff30484702009-12-06 21:14:13 +00004089 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004090
4091 InsertText(FunLocStart, CI.c_str(), CI.size());
4092
Steve Naroff30484702009-12-06 21:14:13 +00004093 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump11289f42009-09-09 15:08:12 +00004094
Steve Naroff677ab3a2008-10-27 17:20:55 +00004095 InsertText(FunLocStart, CF.c_str(), CF.size());
4096
4097 if (ImportedBlockDecls.size()) {
Steve Naroff30484702009-12-06 21:14:13 +00004098 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004099 InsertText(FunLocStart, HF.c_str(), HF.size());
4100 }
Steve Naroff30484702009-12-06 21:14:13 +00004101 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4102 ImportedBlockDecls.size() > 0);
4103 InsertText(FunLocStart, BD.c_str(), BD.size());
Mike Stump11289f42009-09-09 15:08:12 +00004104
Steve Naroff677ab3a2008-10-27 17:20:55 +00004105 BlockDeclRefs.clear();
4106 BlockByRefDecls.clear();
4107 BlockByCopyDecls.clear();
4108 BlockCallExprs.clear();
4109 ImportedBlockDecls.clear();
4110 }
4111 Blocks.clear();
4112 RewrittenBlockExprs.clear();
4113}
4114
4115void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4116 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner86d7d912008-11-24 03:54:41 +00004117 const char *FuncName = FD->getNameAsCString();
Mike Stump11289f42009-09-09 15:08:12 +00004118
Steve Naroff677ab3a2008-10-27 17:20:55 +00004119 SynthesizeBlockLiterals(FunLocStart, FuncName);
4120}
4121
4122void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroff295570a2008-10-30 12:09:33 +00004123 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4124 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanianb5f99c32010-01-29 01:55:49 +00004125 SourceLocation FunLocStart = MD->getLocStart();
Chris Lattnere4b95692008-11-24 03:33:13 +00004126 std::string FuncName = MD->getSelector().getAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004127 // Convert colons to underscores.
4128 std::string::size_type loc = 0;
4129 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4130 FuncName.replace(loc, 1, "_");
Mike Stump11289f42009-09-09 15:08:12 +00004131
Steve Naroff677ab3a2008-10-27 17:20:55 +00004132 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
4133}
4134
4135void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
4136 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4137 CI != E; ++CI)
4138 if (*CI) {
4139 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4140 GetBlockDeclRefExprs(CBE->getBody());
4141 else
4142 GetBlockDeclRefExprs(*CI);
4143 }
4144 // Handle specific things.
4145 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
4146 // FIXME: Handle enums.
4147 if (!isa<FunctionDecl>(CDRE->getDecl()))
4148 BlockDeclRefs.push_back(CDRE);
4149 return;
4150}
4151
4152void RewriteObjC::GetBlockCallExprs(Stmt *S) {
4153 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4154 CI != E; ++CI)
4155 if (*CI) {
4156 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4157 GetBlockCallExprs(CBE->getBody());
4158 else
4159 GetBlockCallExprs(*CI);
4160 }
Mike Stump11289f42009-09-09 15:08:12 +00004161
Steve Naroff677ab3a2008-10-27 17:20:55 +00004162 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
4163 if (CE->getCallee()->getType()->isBlockPointerType()) {
4164 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
4165 }
4166 }
4167 return;
4168}
4169
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004170Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004171 // Navigate to relevant type information.
Steve Naroff677ab3a2008-10-27 17:20:55 +00004172 const BlockPointerType *CPT = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004173
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004174 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004175 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004176 } else if (const BlockDeclRefExpr *CDRE =
4177 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004178 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004179 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004180 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004181 }
4182 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4183 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4184 }
4185 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4186 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4187 else if (const ConditionalOperator *CEXPR =
4188 dyn_cast<ConditionalOperator>(BlockExp)) {
4189 Expr *LHSExp = CEXPR->getLHS();
4190 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4191 Expr *RHSExp = CEXPR->getRHS();
4192 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4193 Expr *CONDExp = CEXPR->getCond();
4194 ConditionalOperator *CondExpr =
4195 new (Context) ConditionalOperator(CONDExp,
4196 SourceLocation(), cast<Expr>(LHSStmt),
4197 SourceLocation(), cast<Expr>(RHSStmt),
4198 Exp->getType());
4199 return CondExpr;
Fariborz Jahanian6ab7ed42009-12-18 01:15:21 +00004200 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4201 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004202 } else {
4203 assert(1 && "RewriteBlockClass: Bad type");
4204 }
4205 assert(CPT && "RewriteBlockClass: Bad type");
John McCall9dd450b2009-09-21 23:43:11 +00004206 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004207 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004208 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004209 // FTP will be null for closures that don't take arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004210
Steve Naroff350b6652008-10-30 10:07:53 +00004211 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
4212 SourceLocation(),
4213 &Context->Idents.get("__block_impl"));
4214 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff677ab3a2008-10-27 17:20:55 +00004215
Steve Naroff350b6652008-10-30 10:07:53 +00004216 // Generate a funky cast.
4217 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00004218
Steve Naroff350b6652008-10-30 10:07:53 +00004219 // Push the block argument type.
4220 ArgTypes.push_back(PtrBlock);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004221 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004222 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff350b6652008-10-30 10:07:53 +00004223 E = FTP->arg_type_end(); I && (I != E); ++I) {
4224 QualType t = *I;
4225 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffa5c0db82008-12-11 21:05:33 +00004226 if (isTopLevelBlockPointerType(t)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004227 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroff350b6652008-10-30 10:07:53 +00004228 t = Context->getPointerType(BPT->getPointeeType());
4229 }
4230 ArgTypes.push_back(t);
4231 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004232 }
Steve Naroff350b6652008-10-30 10:07:53 +00004233 // Now do the pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00004234 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
Steve Naroff350b6652008-10-30 10:07:53 +00004235 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004236
Steve Naroff350b6652008-10-30 10:07:53 +00004237 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump11289f42009-09-09 15:08:12 +00004238
John McCall97513962010-01-15 18:39:57 +00004239 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4240 CastExpr::CK_Unknown,
4241 const_cast<Expr*>(BlockExp));
Steve Naroff350b6652008-10-30 10:07:53 +00004242 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00004243 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4244 BlkCast);
Steve Naroff350b6652008-10-30 10:07:53 +00004245 //PE->dump();
Mike Stump11289f42009-09-09 15:08:12 +00004246
Douglas Gregor91f84212008-12-11 16:49:14 +00004247 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00004248 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004249 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek5a201952009-02-07 01:47:29 +00004250 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4251 FD->getType());
Mike Stump11289f42009-09-09 15:08:12 +00004252
John McCall97513962010-01-15 18:39:57 +00004253 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4254 CastExpr::CK_Unknown, ME);
Ted Kremenek5a201952009-02-07 01:47:29 +00004255 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump11289f42009-09-09 15:08:12 +00004256
Steve Naroff350b6652008-10-30 10:07:53 +00004257 llvm::SmallVector<Expr*, 8> BlkExprs;
4258 // Add the implicit argument.
4259 BlkExprs.push_back(BlkCast);
4260 // Add the user arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004261 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004262 E = Exp->arg_end(); I != E; ++I) {
Steve Naroff350b6652008-10-30 10:07:53 +00004263 BlkExprs.push_back(*I);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004264 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004265 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4266 BlkExprs.size(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004267 Exp->getType(), SourceLocation());
Steve Naroff350b6652008-10-30 10:07:53 +00004268 return CE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004269}
4270
4271void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004272 Stmt *BlockCall = SynthesizeBlockCall(Exp, Exp->getCallee());
Steve Naroff350b6652008-10-30 10:07:53 +00004273 ReplaceStmt(Exp, BlockCall);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004274}
4275
Steve Naroffd9803712009-04-29 16:37:50 +00004276// We need to return the rewritten expression to handle cases where the
4277// BlockDeclRefExpr is embedded in another expression being rewritten.
4278// For example:
4279//
4280// int main() {
4281// __block Foo *f;
4282// __block int i;
Mike Stump11289f42009-09-09 15:08:12 +00004283//
Steve Naroffd9803712009-04-29 16:37:50 +00004284// void (^myblock)() = ^() {
4285// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4286// i = 77;
4287// };
4288//}
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004289Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanian25c07fa2009-12-23 19:26:34 +00004290 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004291 // for each DeclRefExp where BYREFVAR is name of the variable.
4292 ValueDecl *VD;
4293 bool isArrow = true;
4294 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4295 VD = BDRE->getDecl();
4296 else {
4297 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4298 isArrow = false;
4299 }
4300
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004301 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4302 &Context->Idents.get("__forwarding"),
4303 Context->VoidPtrTy, 0,
4304 /*BitWidth=*/0, /*Mutable=*/true);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004305 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4306 FD, SourceLocation(),
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004307 FD->getType());
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004308
4309 const char *Name = VD->getNameAsCString();
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004310 FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4311 &Context->Idents.get(Name),
4312 Context->VoidPtrTy, 0,
4313 /*BitWidth=*/0, /*Mutable=*/true);
4314 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004315 DeclRefExp->getType());
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004316
4317
4318
Steve Narofff26a1d42009-02-02 17:19:26 +00004319 // Need parens to enforce precedence.
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004320 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4321 ME);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004322 ReplaceStmt(DeclRefExp, PE);
Steve Naroffd9803712009-04-29 16:37:50 +00004323 return PE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004324}
4325
Steve Naroffc989a7b2008-11-03 23:29:32 +00004326void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4327 SourceLocation LocStart = CE->getLParenLoc();
4328 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofff4b992a2008-10-28 20:29:00 +00004329
4330 // Need to avoid trying to rewrite synthesized casts.
4331 if (LocStart.isInvalid())
4332 return;
Steve Naroff3e7ced12008-11-03 11:20:24 +00004333 // Need to avoid trying to rewrite casts contained in macros.
4334 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4335 return;
Mike Stump11289f42009-09-09 15:08:12 +00004336
Steve Naroff677ab3a2008-10-27 17:20:55 +00004337 const char *startBuf = SM->getCharacterData(LocStart);
4338 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00004339 QualType QT = CE->getType();
4340 const Type* TypePtr = QT->getAs<Type>();
4341 if (isa<TypeOfExprType>(TypePtr)) {
4342 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4343 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4344 std::string TypeAsString = "(";
4345 TypeAsString += QT.getAsString();
4346 TypeAsString += ")";
4347 ReplaceText(LocStart, endBuf-startBuf+1,
4348 TypeAsString.c_str(), TypeAsString.size());
4349 return;
4350 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004351 // advance the location to startArgList.
4352 const char *argPtr = startBuf;
Mike Stump11289f42009-09-09 15:08:12 +00004353
Steve Naroff677ab3a2008-10-27 17:20:55 +00004354 while (*argPtr++ && (argPtr < endBuf)) {
4355 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004356 case '^':
4357 // Replace the '^' with '*'.
4358 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
4359 ReplaceText(LocStart, 1, "*", 1);
4360 break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004361 }
4362 }
4363 return;
4364}
4365
4366void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4367 SourceLocation DeclLoc = FD->getLocation();
4368 unsigned parenCount = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004369
Steve Naroff677ab3a2008-10-27 17:20:55 +00004370 // We have 1 or more arguments that have closure pointers.
4371 const char *startBuf = SM->getCharacterData(DeclLoc);
4372 const char *startArgList = strchr(startBuf, '(');
Mike Stump11289f42009-09-09 15:08:12 +00004373
Steve Naroff677ab3a2008-10-27 17:20:55 +00004374 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004375
Steve Naroff677ab3a2008-10-27 17:20:55 +00004376 parenCount++;
4377 // advance the location to startArgList.
4378 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4379 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump11289f42009-09-09 15:08:12 +00004380
Steve Naroff677ab3a2008-10-27 17:20:55 +00004381 const char *argPtr = startArgList;
Mike Stump11289f42009-09-09 15:08:12 +00004382
Steve Naroff677ab3a2008-10-27 17:20:55 +00004383 while (*argPtr++ && parenCount) {
4384 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004385 case '^':
4386 // Replace the '^' with '*'.
4387 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
4388 ReplaceText(DeclLoc, 1, "*", 1);
4389 break;
4390 case '(':
4391 parenCount++;
4392 break;
4393 case ')':
4394 parenCount--;
4395 break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004396 }
4397 }
4398 return;
4399}
4400
4401bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004402 const FunctionProtoType *FTP;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004403 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004404 if (PT) {
John McCall9dd450b2009-09-21 23:43:11 +00004405 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004406 } else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004407 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004408 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall9dd450b2009-09-21 23:43:11 +00004409 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004410 }
4411 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004412 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004413 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +00004414 if (isTopLevelBlockPointerType(*I))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004415 return true;
4416 }
4417 return false;
4418}
4419
Ted Kremenek5a201952009-02-07 01:47:29 +00004420void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4421 const char *&RParen) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004422 const char *argPtr = strchr(Name, '(');
4423 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004424
Steve Naroff677ab3a2008-10-27 17:20:55 +00004425 LParen = argPtr; // output the start.
4426 argPtr++; // skip past the left paren.
4427 unsigned parenCount = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004428
Steve Naroff677ab3a2008-10-27 17:20:55 +00004429 while (*argPtr && parenCount) {
4430 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004431 case '(': parenCount++; break;
4432 case ')': parenCount--; break;
4433 default: break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004434 }
4435 if (parenCount) argPtr++;
4436 }
4437 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4438 RParen = argPtr; // output the end
4439}
4440
4441void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4442 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4443 RewriteBlockPointerFunctionArgs(FD);
4444 return;
Mike Stump11289f42009-09-09 15:08:12 +00004445 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004446 // Handle Variables and Typedefs.
4447 SourceLocation DeclLoc = ND->getLocation();
4448 QualType DeclT;
4449 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4450 DeclT = VD->getType();
4451 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4452 DeclT = TDD->getUnderlyingType();
4453 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4454 DeclT = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00004455 else
Steve Naroff677ab3a2008-10-27 17:20:55 +00004456 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump11289f42009-09-09 15:08:12 +00004457
Steve Naroff677ab3a2008-10-27 17:20:55 +00004458 const char *startBuf = SM->getCharacterData(DeclLoc);
4459 const char *endBuf = startBuf;
4460 // scan backward (from the decl location) for the end of the previous decl.
4461 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4462 startBuf--;
Mike Stump11289f42009-09-09 15:08:12 +00004463
Steve Naroff677ab3a2008-10-27 17:20:55 +00004464 // *startBuf != '^' if we are dealing with a pointer to function that
4465 // may take block argument types (which will be handled below).
4466 if (*startBuf == '^') {
4467 // Replace the '^' with '*', computing a negative offset.
4468 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
4469 ReplaceText(DeclLoc, 1, "*", 1);
4470 }
4471 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4472 // Replace the '^' with '*' for arguments.
4473 DeclLoc = ND->getLocation();
4474 startBuf = SM->getCharacterData(DeclLoc);
4475 const char *argListBegin, *argListEnd;
4476 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4477 while (argListBegin < argListEnd) {
4478 if (*argListBegin == '^') {
4479 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
4480 ReplaceText(CaretLoc, 1, "*", 1);
4481 }
4482 argListBegin++;
4483 }
4484 }
4485 return;
4486}
4487
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004488
4489/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4490/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4491/// struct Block_byref_id_object *src) {
4492/// _Block_object_assign (&_dest->object, _src->object,
4493/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4494/// [|BLOCK_FIELD_IS_WEAK]) // object
4495/// _Block_object_assign(&_dest->object, _src->object,
4496/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4497/// [|BLOCK_FIELD_IS_WEAK]) // block
4498/// }
4499/// And:
4500/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4501/// _Block_object_dispose(_src->object,
4502/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4503/// [|BLOCK_FIELD_IS_WEAK]) // object
4504/// _Block_object_dispose(_src->object,
4505/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4506/// [|BLOCK_FIELD_IS_WEAK]) // block
4507/// }
4508
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004509std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4510 int flag) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004511 std::string S;
Benjamin Kramere056cea2010-01-10 19:57:50 +00004512 if (CopyDestroyCache.count(flag))
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004513 return S;
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004514 CopyDestroyCache.insert(flag);
4515 S = "static void __Block_byref_id_object_copy_";
4516 S += utostr(flag);
4517 S += "(void *dst, void *src) {\n";
4518
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004519 // offset into the object pointer is computed as:
4520 // void * + void* + int + int + void* + void *
4521 unsigned IntSize =
4522 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4523 unsigned VoidPtrSize =
4524 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4525
4526 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/8;
4527 S += " _Block_object_assign((char*)dst + ";
4528 S += utostr(offset);
4529 S += ", *(void * *) ((char*)src + ";
4530 S += utostr(offset);
4531 S += "), ";
4532 S += utostr(flag);
4533 S += ");\n}\n";
4534
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004535 S += "static void __Block_byref_id_object_dispose_";
4536 S += utostr(flag);
4537 S += "(void *src) {\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004538 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4539 S += utostr(offset);
4540 S += "), ";
4541 S += utostr(flag);
4542 S += ");\n}\n";
4543 return S;
4544}
4545
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004546/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4547/// the declaration into:
4548/// struct __Block_byref_ND {
4549/// void *__isa; // NULL for everything except __weak pointers
4550/// struct __Block_byref_ND *__forwarding;
4551/// int32_t __flags;
4552/// int32_t __size;
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004553/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4554/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004555/// typex ND;
4556/// };
4557///
4558/// It then replaces declaration of ND variable with:
4559/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4560/// __size=sizeof(struct __Block_byref_ND),
4561/// ND=initializer-if-any};
4562///
4563///
4564void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004565 // Insert declaration for the function in which block literal is
4566 // used.
4567 if (CurFunctionDeclToDeclareForBlock)
4568 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004569 int flag = 0;
4570 int isa = 0;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004571 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4572 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian92368a12009-12-30 20:38:08 +00004573 SourceLocation X = ND->getLocEnd();
4574 X = SM->getInstantiationLoc(X);
4575 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004576 std::string Name(ND->getNameAsString());
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004577 std::string ByrefType;
4578 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004579 ByrefType += " {\n";
4580 ByrefType += " void *__isa;\n";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004581 RewriteByRefString(ByrefType, Name, ND);
4582 ByrefType += " *__forwarding;\n";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004583 ByrefType += " int __flags;\n";
4584 ByrefType += " int __size;\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004585 // Add void *__Block_byref_id_object_copy;
4586 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004587 QualType Ty = ND->getType();
4588 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4589 if (HasCopyAndDispose) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004590 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4591 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004592 }
4593
4594 Ty.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004595 ByrefType += " " + Name + ";\n";
4596 ByrefType += "};\n";
4597 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004598 SourceLocation FunLocStart;
4599 if (CurFunctionDef)
4600 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4601 else {
4602 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4603 FunLocStart = CurMethodDef->getLocStart();
4604 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004605 InsertText(FunLocStart, ByrefType.c_str(), ByrefType.size());
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004606 if (Ty.isObjCGCWeak()) {
4607 flag |= BLOCK_FIELD_IS_WEAK;
4608 isa = 1;
4609 }
4610
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004611 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004612 flag = BLOCK_BYREF_CALLER;
4613 QualType Ty = ND->getType();
4614 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4615 if (Ty->isBlockPointerType())
4616 flag |= BLOCK_FIELD_IS_BLOCK;
4617 else
4618 flag |= BLOCK_FIELD_IS_OBJECT;
4619 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004620 if (!HF.empty())
4621 InsertText(FunLocStart, HF.c_str(), HF.size());
4622 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004623
4624 // struct __Block_byref_ND ND =
4625 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4626 // initializer-if-any};
4627 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanianf7945432010-01-05 18:15:57 +00004628 unsigned flags = 0;
4629 if (HasCopyAndDispose)
4630 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004631 Name = ND->getNameAsString();
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004632 ByrefType.clear();
4633 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004634 std::string ForwardingCastType("(");
4635 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004636 if (!hasInit) {
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004637 ByrefType += " " + Name + " = {(void*)";
4638 ByrefType += utostr(isa);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004639 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004640 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004641 ByrefType += ", ";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004642 ByrefType += "sizeof(";
4643 RewriteByRefString(ByrefType, Name, ND);
4644 ByrefType += ")";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004645 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004646 ByrefType += ", __Block_byref_id_object_copy_";
4647 ByrefType += utostr(flag);
4648 ByrefType += ", __Block_byref_id_object_dispose_";
4649 ByrefType += utostr(flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004650 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004651 ByrefType += "};\n";
4652 ReplaceText(DeclLoc, endBuf-startBuf+Name.size(),
4653 ByrefType.c_str(), ByrefType.size());
4654 }
4655 else {
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004656 SourceLocation startLoc;
4657 Expr *E = ND->getInit();
4658 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4659 startLoc = ECE->getLParenLoc();
4660 else
4661 startLoc = E->getLocStart();
Fariborz Jahanianb8646ed2010-01-05 23:06:29 +00004662 startLoc = SM->getInstantiationLoc(startLoc);
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004663 endBuf = SM->getCharacterData(startLoc);
4664
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004665 ByrefType += " " + Name;
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004666 ByrefType += " = {(void*)";
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004667 ByrefType += utostr(isa);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004668 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004669 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004670 ByrefType += ", ";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004671 ByrefType += "sizeof(";
4672 RewriteByRefString(ByrefType, Name, ND);
4673 ByrefType += "), ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004674 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004675 ByrefType += "__Block_byref_id_object_copy_";
4676 ByrefType += utostr(flag);
4677 ByrefType += ", __Block_byref_id_object_dispose_";
4678 ByrefType += utostr(flag);
4679 ByrefType += ", ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004680 }
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004681 ReplaceText(DeclLoc, endBuf-startBuf,
4682 ByrefType.c_str(), ByrefType.size());
Steve Naroff13468372009-12-23 17:24:33 +00004683
4684 // Complete the newly synthesized compound expression by inserting a right
4685 // curly brace before the end of the declaration.
4686 // FIXME: This approach avoids rewriting the initializer expression. It
4687 // also assumes there is only one declarator. For example, the following
4688 // isn't currently supported by this routine (in general):
4689 //
4690 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4691 //
4692 const char *startBuf = SM->getCharacterData(startLoc);
4693 const char *semiBuf = strchr(startBuf, ';');
4694 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4695 SourceLocation semiLoc =
4696 startLoc.getFileLocWithOffset(semiBuf-startBuf);
4697
4698 InsertText(semiLoc, "}", 1);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004699 }
Fariborz Jahanian81203462009-12-22 00:48:54 +00004700 return;
4701}
4702
Mike Stump11289f42009-09-09 15:08:12 +00004703void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004704 // Add initializers for any closure decl refs.
4705 GetBlockDeclRefExprs(Exp->getBody());
4706 if (BlockDeclRefs.size()) {
4707 // Unique all "by copy" declarations.
4708 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4709 if (!BlockDeclRefs[i]->isByRef())
4710 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
4711 // Unique all "by ref" declarations.
4712 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4713 if (BlockDeclRefs[i]->isByRef()) {
4714 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
4715 }
4716 // Find any imported blocks...they will need special attention.
4717 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00004718 if (BlockDeclRefs[i]->isByRef() ||
4719 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4720 BlockDeclRefs[i]->getType()->isBlockPointerType()) {
Steve Naroff832d8902008-11-13 17:40:07 +00004721 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004722 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4723 }
4724 }
4725}
4726
Steve Narofff4b992a2008-10-28 20:29:00 +00004727FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
4728 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004729 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Mike Stump11289f42009-09-09 15:08:12 +00004730 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00004731 ID, FType, 0, FunctionDecl::Extern, false,
Douglas Gregor739ef0c2009-02-25 16:33:18 +00004732 false);
Steve Narofff4b992a2008-10-28 20:29:00 +00004733}
4734
Steve Naroffd8907b72008-10-29 18:15:37 +00004735Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004736 Blocks.push_back(Exp);
4737
4738 CollectBlockDeclRefInfo(Exp);
4739 std::string FuncName;
Mike Stump11289f42009-09-09 15:08:12 +00004740
Steve Narofff4b992a2008-10-28 20:29:00 +00004741 if (CurFunctionDef)
Chris Lattnere4b95692008-11-24 03:33:13 +00004742 FuncName = CurFunctionDef->getNameAsString();
Steve Narofff4b992a2008-10-28 20:29:00 +00004743 else if (CurMethodDef) {
Chris Lattnere4b95692008-11-24 03:33:13 +00004744 FuncName = CurMethodDef->getSelector().getAsString();
Steve Narofff4b992a2008-10-28 20:29:00 +00004745 // Convert colons to underscores.
4746 std::string::size_type loc = 0;
4747 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4748 FuncName.replace(loc, 1, "_");
Steve Naroffd8907b72008-10-29 18:15:37 +00004749 } else if (GlobalVarDecl)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004750 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump11289f42009-09-09 15:08:12 +00004751
Steve Narofff4b992a2008-10-28 20:29:00 +00004752 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump11289f42009-09-09 15:08:12 +00004753
Steve Narofff4b992a2008-10-28 20:29:00 +00004754 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4755 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump11289f42009-09-09 15:08:12 +00004756
Steve Narofff4b992a2008-10-28 20:29:00 +00004757 // Get a pointer to the function type so we can cast appropriately.
4758 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
4759
4760 FunctionDecl *FD;
4761 Expr *NewRep;
Mike Stump11289f42009-09-09 15:08:12 +00004762
Steve Narofff4b992a2008-10-28 20:29:00 +00004763 // Simulate a contructor call...
4764 FD = SynthBlockInitFunctionDecl(Tag.c_str());
Ted Kremenek5a201952009-02-07 01:47:29 +00004765 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004766
Steve Narofff4b992a2008-10-28 20:29:00 +00004767 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00004768
Steve Naroffe2514232008-10-29 21:23:59 +00004769 // Initialize the block function.
Steve Narofff4b992a2008-10-28 20:29:00 +00004770 FD = SynthBlockInitFunctionDecl(Func.c_str());
Ted Kremenek5a201952009-02-07 01:47:29 +00004771 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
4772 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00004773 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4774 CastExpr::CK_Unknown, Arg);
Mike Stump11289f42009-09-09 15:08:12 +00004775 InitExprs.push_back(castExpr);
4776
Steve Naroff30484702009-12-06 21:14:13 +00004777 // Initialize the block descriptor.
4778 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump11289f42009-09-09 15:08:12 +00004779
Steve Naroff30484702009-12-06 21:14:13 +00004780 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
4781 &Context->Idents.get(DescData.c_str()),
4782 Context->VoidPtrTy, 0,
4783 VarDecl::Static);
4784 UnaryOperator *DescRefExpr = new (Context) UnaryOperator(
4785 new (Context) DeclRefExpr(NewVD,
4786 Context->VoidPtrTy, SourceLocation()),
4787 UnaryOperator::AddrOf,
4788 Context->getPointerType(Context->VoidPtrTy),
4789 SourceLocation());
4790 InitExprs.push_back(DescRefExpr);
4791
Steve Narofff4b992a2008-10-28 20:29:00 +00004792 // Add initializers for any closure decl refs.
4793 if (BlockDeclRefs.size()) {
Steve Naroffe2514232008-10-29 21:23:59 +00004794 Expr *Exp;
Steve Narofff4b992a2008-10-28 20:29:00 +00004795 // Output all "by copy" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00004796 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00004797 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004798 if (isObjCType((*I)->getType())) {
Steve Naroffe2514232008-10-29 21:23:59 +00004799 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner86d7d912008-11-24 03:54:41 +00004800 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004801 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroffa5c0db82008-12-11 21:05:33 +00004802 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Chris Lattner86d7d912008-11-24 03:54:41 +00004803 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004804 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
John McCall97513962010-01-15 18:39:57 +00004805 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4806 CastExpr::CK_Unknown, Arg);
Steve Narofff4b992a2008-10-28 20:29:00 +00004807 } else {
Chris Lattner86d7d912008-11-24 03:54:41 +00004808 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004809 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004810 }
Mike Stump11289f42009-09-09 15:08:12 +00004811 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00004812 }
4813 // Output all "by ref" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00004814 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00004815 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004816 ValueDecl *ND = (*I);
4817 std::string Name(ND->getNameAsString());
4818 std::string RecName;
4819 RewriteByRefString(RecName, Name, ND);
4820 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
4821 + sizeof("struct"));
4822 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
4823 SourceLocation(), II);
4824 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
4825 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
4826
Chris Lattner86d7d912008-11-24 03:54:41 +00004827 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004828 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4829 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00004830 Context->getPointerType(Exp->getType()),
Steve Naroffe2514232008-10-29 21:23:59 +00004831 SourceLocation());
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004832 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CastExpr::CK_Unknown, Exp);
Mike Stump11289f42009-09-09 15:08:12 +00004833 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00004834 }
4835 }
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00004836 if (ImportedBlockDecls.size()) {
4837 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4838 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff30484702009-12-06 21:14:13 +00004839 unsigned IntSize =
4840 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00004841 Expr *FlagExp = new (Context) IntegerLiteral(llvm::APInt(IntSize, flag),
4842 Context->IntTy, SourceLocation());
4843 InitExprs.push_back(FlagExp);
Steve Naroff30484702009-12-06 21:14:13 +00004844 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004845 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4846 FType, SourceLocation());
Ted Kremenek5a201952009-02-07 01:47:29 +00004847 NewRep = new (Context) UnaryOperator(NewRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00004848 Context->getPointerType(NewRep->getType()),
Steve Narofff4b992a2008-10-28 20:29:00 +00004849 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00004850 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CastExpr::CK_Unknown,
4851 NewRep);
Steve Narofff4b992a2008-10-28 20:29:00 +00004852 BlockDeclRefs.clear();
4853 BlockByRefDecls.clear();
4854 BlockByCopyDecls.clear();
4855 ImportedBlockDecls.clear();
4856 return NewRep;
4857}
4858
4859//===----------------------------------------------------------------------===//
4860// Function Body / Expression rewriting
4861//===----------------------------------------------------------------------===//
4862
Steve Naroff4588d0f2008-12-04 16:24:46 +00004863// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
4864// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
4865// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
4866// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
4867// Since the rewriter isn't capable of rewriting rewritten code, it's important
4868// we get this right.
4869void RewriteObjC::CollectPropertySetters(Stmt *S) {
4870 // Perform a bottom up traversal of all children.
4871 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4872 CI != E; ++CI)
4873 if (*CI)
4874 CollectPropertySetters(*CI);
4875
4876 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
4877 if (BinOp->isAssignmentOp()) {
4878 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
4879 PropSetters[PRE] = BinOp;
4880 }
4881 }
4882}
4883
Steve Narofff4b992a2008-10-28 20:29:00 +00004884Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump11289f42009-09-09 15:08:12 +00004885 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00004886 isa<DoStmt>(S) || isa<ForStmt>(S))
4887 Stmts.push_back(S);
4888 else if (isa<ObjCForCollectionStmt>(S)) {
4889 Stmts.push_back(S);
Chris Lattnerb71980f2010-01-09 21:45:57 +00004890 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofff4b992a2008-10-28 20:29:00 +00004891 }
Mike Stump11289f42009-09-09 15:08:12 +00004892
Steve Narofff4b992a2008-10-28 20:29:00 +00004893 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004894
Steve Narofff4b992a2008-10-28 20:29:00 +00004895 // Perform a bottom up rewrite of all children.
4896 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4897 CI != E; ++CI)
4898 if (*CI) {
Fariborz Jahanian80fadb52010-02-05 01:35:00 +00004899 Stmt *newStmt;
4900 Stmt *S = (*CI);
4901 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
4902 Expr *OldBase = IvarRefExpr->getBase();
4903 bool replaced = false;
4904 newStmt = RewriteObjCNestedIvarRefExpr(S, replaced);
4905 if (replaced) {
4906 if (ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(newStmt))
4907 ReplaceStmt(OldBase, IRE->getBase());
4908 else
4909 ReplaceStmt(S, newStmt);
4910 }
4911 }
4912 else
4913 newStmt = RewriteFunctionBodyOrGlobalInitializer(S);
Mike Stump11289f42009-09-09 15:08:12 +00004914 if (newStmt)
Steve Narofff4b992a2008-10-28 20:29:00 +00004915 *CI = newStmt;
4916 }
Mike Stump11289f42009-09-09 15:08:12 +00004917
Steve Narofff4b992a2008-10-28 20:29:00 +00004918 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4919 // Rewrite the block body in place.
4920 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Mike Stump11289f42009-09-09 15:08:12 +00004921
Steve Narofff4b992a2008-10-28 20:29:00 +00004922 // Now we snarf the rewritten text and stash it away for later use.
Ted Kremenekdb2ef372010-01-07 18:00:35 +00004923 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroffd8907b72008-10-29 18:15:37 +00004924 RewrittenBlockExprs[BE] = Str;
Mike Stump11289f42009-09-09 15:08:12 +00004925
Steve Narofff4b992a2008-10-28 20:29:00 +00004926 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
4927 //blockTranscribed->dump();
Steve Naroffd8907b72008-10-29 18:15:37 +00004928 ReplaceStmt(S, blockTranscribed);
Steve Narofff4b992a2008-10-28 20:29:00 +00004929 return blockTranscribed;
4930 }
4931 // Handle specific things.
4932 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4933 return RewriteAtEncode(AtEncode);
Mike Stump11289f42009-09-09 15:08:12 +00004934
Steve Naroff4588d0f2008-12-04 16:24:46 +00004935 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
4936 BinaryOperator *BinOp = PropSetters[PropRefExpr];
4937 if (BinOp) {
4938 // Because the rewriter doesn't allow us to rewrite rewritten code,
4939 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroff08628db2008-12-09 12:56:34 +00004940 DisableReplaceStmt = true;
4941 // Save the source range. Even if we disable the replacement, the
4942 // rewritten node will have been inserted into the tree. If the synthesized
4943 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump11289f42009-09-09 15:08:12 +00004944 // self.errorHandler = handler ? handler :
Steve Naroff08628db2008-12-09 12:56:34 +00004945 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
4946 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroff4588d0f2008-12-04 16:24:46 +00004947 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroff08628db2008-12-09 12:56:34 +00004948 DisableReplaceStmt = false;
Steve Naroff22216db2008-12-04 23:50:32 +00004949 //
4950 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
4951 // we changed the RHS of BinOp, the rewriter would fail (since it needs
4952 // to see the original expression). Consider this example:
4953 //
4954 // Foo *obj1, *obj2;
4955 //
4956 // obj1.i = [obj2 rrrr];
4957 //
4958 // 'BinOp' for the previous expression looks like:
4959 //
4960 // (BinaryOperator 0x231ccf0 'int' '='
4961 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
4962 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
4963 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
4964 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
4965 //
4966 // 'newStmt' represents the rewritten message expression. For example:
4967 //
4968 // (CallExpr 0x231d300 'id':'struct objc_object *'
4969 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
4970 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
4971 // (CStyleCastExpr 0x231d220 'void *'
4972 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
4973 //
4974 // Note that 'newStmt' is passed to RewritePropertySetter so that it
4975 // can be used as the setter argument. ReplaceStmt() will still 'see'
4976 // the original RHS (since we haven't altered BinOp).
4977 //
Mike Stump11289f42009-09-09 15:08:12 +00004978 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff22216db2008-12-04 23:50:32 +00004979 // node. As a result, we now leak the original AST nodes.
4980 //
Steve Naroff08628db2008-12-09 12:56:34 +00004981 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroff4588d0f2008-12-04 16:24:46 +00004982 } else {
4983 return RewritePropertyGetter(PropRefExpr);
Steve Narofff326f402008-12-03 00:56:33 +00004984 }
4985 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004986 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4987 return RewriteAtSelector(AtSelector);
Mike Stump11289f42009-09-09 15:08:12 +00004988
Steve Narofff4b992a2008-10-28 20:29:00 +00004989 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4990 return RewriteObjCStringLiteral(AtString);
Mike Stump11289f42009-09-09 15:08:12 +00004991
Steve Narofff4b992a2008-10-28 20:29:00 +00004992 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00004993#if 0
Steve Narofff4b992a2008-10-28 20:29:00 +00004994 // Before we rewrite it, put the original message expression in a comment.
4995 SourceLocation startLoc = MessExpr->getLocStart();
4996 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00004997
Steve Narofff4b992a2008-10-28 20:29:00 +00004998 const char *startBuf = SM->getCharacterData(startLoc);
4999 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump11289f42009-09-09 15:08:12 +00005000
Steve Narofff4b992a2008-10-28 20:29:00 +00005001 std::string messString;
5002 messString += "// ";
5003 messString.append(startBuf, endBuf-startBuf+1);
5004 messString += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00005005
5006 // FIXME: Missing definition of
Steve Narofff4b992a2008-10-28 20:29:00 +00005007 // InsertText(clang::SourceLocation, char const*, unsigned int).
5008 // InsertText(startLoc, messString.c_str(), messString.size());
5009 // Tried this, but it didn't work either...
5010 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroff4588d0f2008-12-04 16:24:46 +00005011#endif
Steve Narofff4b992a2008-10-28 20:29:00 +00005012 return RewriteMessageExpr(MessExpr);
5013 }
Mike Stump11289f42009-09-09 15:08:12 +00005014
Steve Narofff4b992a2008-10-28 20:29:00 +00005015 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5016 return RewriteObjCTryStmt(StmtTry);
5017
5018 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5019 return RewriteObjCSynchronizedStmt(StmtTry);
5020
5021 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5022 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump11289f42009-09-09 15:08:12 +00005023
Steve Narofff4b992a2008-10-28 20:29:00 +00005024 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5025 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump11289f42009-09-09 15:08:12 +00005026
5027 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofff4b992a2008-10-28 20:29:00 +00005028 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump11289f42009-09-09 15:08:12 +00005029 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofff4b992a2008-10-28 20:29:00 +00005030 OrigStmtRange.getEnd());
5031 if (BreakStmt *StmtBreakStmt =
5032 dyn_cast<BreakStmt>(S))
5033 return RewriteBreakStmt(StmtBreakStmt);
5034 if (ContinueStmt *StmtContinueStmt =
5035 dyn_cast<ContinueStmt>(S))
5036 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump11289f42009-09-09 15:08:12 +00005037
5038 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofff4b992a2008-10-28 20:29:00 +00005039 // and cast exprs.
5040 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5041 // FIXME: What we're doing here is modifying the type-specifier that
5042 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump11289f42009-09-09 15:08:12 +00005043 // a separate type-specifier that we can rewrite.
Steve Naroffe70a52a2009-12-05 15:55:59 +00005044 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5045 // the context of an ObjCForCollectionStmt. For example:
5046 // NSArray *someArray;
5047 // for (id <FooProtocol> index in someArray) ;
5048 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5049 // and it depends on the original text locations/positions.
Benjamin Krameracc5fa12009-12-05 22:16:51 +00005050 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
Steve Naroffe70a52a2009-12-05 15:55:59 +00005051 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump11289f42009-09-09 15:08:12 +00005052
Steve Narofff4b992a2008-10-28 20:29:00 +00005053 // Blocks rewrite rules.
5054 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5055 DI != DE; ++DI) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +00005056 Decl *SD = *DI;
Steve Narofff4b992a2008-10-28 20:29:00 +00005057 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005058 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005059 RewriteBlockPointerDecl(ND);
Mike Stump11289f42009-09-09 15:08:12 +00005060 else if (ND->getType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005061 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005062 if (VarDecl *VD = dyn_cast<VarDecl>(SD))
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005063 if (VD->hasAttr<BlocksAttr>()) {
5064 static unsigned uniqueByrefDeclCount = 0;
5065 assert(!BlockByRefDeclNo.count(ND) &&
5066 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5067 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00005068 RewriteByRefVar(VD);
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00005069 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005070 }
5071 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005072 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005073 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00005074 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005075 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5076 }
5077 }
5078 }
Mike Stump11289f42009-09-09 15:08:12 +00005079
Steve Narofff4b992a2008-10-28 20:29:00 +00005080 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5081 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump11289f42009-09-09 15:08:12 +00005082
5083 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00005084 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5085 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump11289f42009-09-09 15:08:12 +00005086 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5087 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005088 && "Statement stack mismatch");
5089 Stmts.pop_back();
5090 }
5091 // Handle blocks rewriting.
5092 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
5093 if (BDRE->isByRef())
Steve Naroffd9803712009-04-29 16:37:50 +00005094 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofff4b992a2008-10-28 20:29:00 +00005095 }
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00005096 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5097 ValueDecl *VD = DRE->getDecl();
5098 if (VD->hasAttr<BlocksAttr>())
5099 return RewriteBlockDeclRefExpr(DRE);
5100 }
5101
Steve Narofff4b992a2008-10-28 20:29:00 +00005102 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroff350b6652008-10-30 10:07:53 +00005103 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00005104 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroff350b6652008-10-30 10:07:53 +00005105 ReplaceStmt(S, BlockCall);
5106 return BlockCall;
5107 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005108 }
Steve Naroffc989a7b2008-11-03 23:29:32 +00005109 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005110 RewriteCastExpr(CE);
5111 }
5112#if 0
5113 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Ted Kremenek5a201952009-02-07 01:47:29 +00005114 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00005115 // Get the new text.
5116 std::string SStr;
5117 llvm::raw_string_ostream Buf(SStr);
Eli Friedman0905f142009-05-30 05:19:26 +00005118 Replacement->printPretty(Buf, *Context);
Steve Narofff4b992a2008-10-28 20:29:00 +00005119 const std::string &Str = Buf.str();
5120
5121 printf("CAST = %s\n", &Str[0]);
5122 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5123 delete S;
5124 return Replacement;
5125 }
5126#endif
5127 // Return this stmt unmodified.
5128 return S;
5129}
5130
Steve Naroffe70a52a2009-12-05 15:55:59 +00005131void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
5132 for (RecordDecl::field_iterator i = RD->field_begin(),
5133 e = RD->field_end(); i != e; ++i) {
5134 FieldDecl *FD = *i;
5135 if (isTopLevelBlockPointerType(FD->getType()))
5136 RewriteBlockPointerDecl(FD);
5137 if (FD->getType()->isObjCQualifiedIdType() ||
5138 FD->getType()->isObjCQualifiedInterfaceType())
5139 RewriteObjCQualifiedInterfaceTypes(FD);
5140 }
5141}
5142
Steve Narofff4b992a2008-10-28 20:29:00 +00005143/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5144/// main file of the input.
5145void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5146 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffb1368882008-12-17 00:20:22 +00005147 if (FD->isOverloadedOperator())
5148 return;
Mike Stump11289f42009-09-09 15:08:12 +00005149
Steve Narofff4b992a2008-10-28 20:29:00 +00005150 // Since function prototypes don't have ParmDecl's, we check the function
5151 // prototype. This enables us to rewrite function declarations and
5152 // definitions using the same code.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005153 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005154
Sebastian Redla7b98a72009-04-26 20:35:05 +00005155 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00005156 if (CompoundStmt *Body = FD->getCompoundBody()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005157 CurFunctionDef = FD;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00005158 CurFunctionDeclToDeclareForBlock = FD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005159 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005160 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00005161 Body =
5162 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5163 FD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005164 CurrentBody = 0;
5165 if (PropParentMap) {
5166 delete PropParentMap;
5167 PropParentMap = 0;
5168 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005169 // This synthesizes and inserts the block "impl" struct, invoke function,
5170 // and any copy/dispose helper functions.
5171 InsertBlockLiteralsWithinFunction(FD);
5172 CurFunctionDef = 0;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00005173 CurFunctionDeclToDeclareForBlock = 0;
Mike Stump11289f42009-09-09 15:08:12 +00005174 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005175 return;
5176 }
5177 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00005178 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005179 CurMethodDef = MD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005180 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005181 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00005182 Body =
5183 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5184 MD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005185 CurrentBody = 0;
5186 if (PropParentMap) {
5187 delete PropParentMap;
5188 PropParentMap = 0;
5189 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005190 InsertBlockLiteralsWithinMethod(MD);
5191 CurMethodDef = 0;
5192 }
5193 }
5194 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5195 ClassImplementation.push_back(CI);
5196 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5197 CategoryImplementation.push_back(CI);
5198 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
5199 RewriteForwardClassDecl(CD);
5200 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5201 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroffa5c0db82008-12-11 21:05:33 +00005202 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005203 RewriteBlockPointerDecl(VD);
Steve Naroffd8907b72008-10-29 18:15:37 +00005204 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005205 CheckFunctionPointerDecl(VD->getType(), VD);
5206 if (VD->getInit()) {
Steve Naroffc989a7b2008-11-03 23:29:32 +00005207 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005208 RewriteCastExpr(CE);
5209 }
5210 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00005211 } else if (VD->getType()->isRecordType()) {
5212 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5213 if (RD->isDefinition())
5214 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005215 }
Steve Naroffd8907b72008-10-29 18:15:37 +00005216 if (VD->getInit()) {
5217 GlobalVarDecl = VD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005218 CollectPropertySetters(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00005219 CurrentBody = VD->getInit();
Steve Naroffd8907b72008-10-29 18:15:37 +00005220 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00005221 CurrentBody = 0;
5222 if (PropParentMap) {
5223 delete PropParentMap;
5224 PropParentMap = 0;
5225 }
Mike Stump11289f42009-09-09 15:08:12 +00005226 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner86d7d912008-11-24 03:54:41 +00005227 VD->getNameAsCString());
Steve Naroffd8907b72008-10-29 18:15:37 +00005228 GlobalVarDecl = 0;
5229
5230 // This is needed for blocks.
Steve Naroffc989a7b2008-11-03 23:29:32 +00005231 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroffd8907b72008-10-29 18:15:37 +00005232 RewriteCastExpr(CE);
5233 }
5234 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005235 return;
5236 }
5237 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005238 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005239 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00005240 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005241 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
Steve Naroffe70a52a2009-12-05 15:55:59 +00005242 else if (TD->getUnderlyingType()->isRecordType()) {
5243 RecordDecl *RD = TD->getUnderlyingType()->getAs<RecordType>()->getDecl();
5244 if (RD->isDefinition())
5245 RewriteRecordBody(RD);
5246 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005247 return;
5248 }
5249 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroffe70a52a2009-12-05 15:55:59 +00005250 if (RD->isDefinition())
5251 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005252 return;
5253 }
5254 // Nothing yet.
5255}
5256
Chris Lattnercf169832009-03-28 04:11:33 +00005257void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005258 if (Diags.hasErrorOccurred())
5259 return;
Mike Stump11289f42009-09-09 15:08:12 +00005260
Steve Narofff4b992a2008-10-28 20:29:00 +00005261 RewriteInclude();
Mike Stump11289f42009-09-09 15:08:12 +00005262
Steve Naroffd9803712009-04-29 16:37:50 +00005263 // Here's a great place to add any extra declarations that may be needed.
5264 // Write out meta data for each @protocol(<expr>).
Mike Stump11289f42009-09-09 15:08:12 +00005265 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00005266 E = ProtocolExprDecls.end(); I != E; ++I)
5267 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5268
Mike Stump11289f42009-09-09 15:08:12 +00005269 InsertText(SM->getLocForStartOfFile(MainFileID),
Steve Narofff4b992a2008-10-28 20:29:00 +00005270 Preamble.c_str(), Preamble.size(), false);
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005271 if (ClassImplementation.size() || CategoryImplementation.size())
5272 RewriteImplementations();
Steve Naroffd9803712009-04-29 16:37:50 +00005273
Steve Narofff4b992a2008-10-28 20:29:00 +00005274 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5275 // we are done.
Mike Stump11289f42009-09-09 15:08:12 +00005276 if (const RewriteBuffer *RewriteBuf =
Steve Narofff4b992a2008-10-28 20:29:00 +00005277 Rewrite.getRewriteBufferFor(MainFileID)) {
5278 //printf("Changed:\n");
5279 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5280 } else {
5281 fprintf(stderr, "No changes\n");
5282 }
Steve Narofff8cfd162008-11-13 20:07:04 +00005283
Steve Naroffd9803712009-04-29 16:37:50 +00005284 if (ClassImplementation.size() || CategoryImplementation.size() ||
5285 ProtocolExprDecls.size()) {
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005286 // Rewrite Objective-c meta data*
5287 std::string ResultStr;
5288 SynthesizeMetaDataIntoBuffer(ResultStr);
5289 // Emit metadata.
5290 *OutFile << ResultStr;
5291 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005292 OutFile->flush();
5293}
5294