blob: 301266f5870140ae4548d6a7c5292aad37b34cf6 [file] [log] [blame]
Steve Naroffb29b4272008-04-14 22:03:09 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
Chris Lattner77cd2a02007-10-11 00:43:27 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner77cd2a02007-10-11 00:43:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
Daniel Dunbar9b414d32010-06-15 17:48:49 +000014#include "clang/Rewrite/ASTConsumers.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Steve Naroff8599e7a2008-12-08 16:43:47 +000018#include "clang/AST/ParentMap.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000019#include "clang/Basic/SourceManager.h"
Steve Naroffebf2b562007-10-23 23:50:29 +000020#include "clang/Basic/IdentifierTable.h"
Chris Lattner07506182007-11-30 22:53:43 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattner26de4652007-12-02 01:13:47 +000022#include "clang/Lex/Lexer.h"
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +000023#include "llvm/Support/MemoryBuffer.h"
24#include "llvm/Support/raw_ostream.h"
Chris Lattner158ecb92007-10-25 17:07:24 +000025#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000026#include "llvm/ADT/SmallPtrSet.h"
Ted Kremeneka95d3752008-09-13 05:16:45 +000027#include "llvm/ADT/OwningPtr.h"
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +000028#include "llvm/ADT/DenseSet.h"
Fariborz Jahanian72952fc2010-03-01 23:36:21 +000029
Chris Lattner77cd2a02007-10-11 00:43:27 +000030using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000031using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000032
Chris Lattner77cd2a02007-10-11 00:43:27 +000033namespace {
Steve Naroffb29b4272008-04-14 22:03:09 +000034 class RewriteObjC : public ASTConsumer {
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000035 enum {
36 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
37 block, ... */
38 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
39 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
40 __block variable */
41 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
42 helpers */
43 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
44 support routines */
45 BLOCK_BYREF_CURRENT_MAX = 256
46 };
47
48 enum {
49 BLOCK_NEEDS_FREE = (1 << 24),
50 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
51 BLOCK_HAS_CXX_OBJ = (1 << 26),
52 BLOCK_IS_GC = (1 << 27),
53 BLOCK_IS_GLOBAL = (1 << 28),
54 BLOCK_HAS_DESCRIPTOR = (1 << 29)
55 };
56
Chris Lattner2c64b7b2007-10-16 21:07:07 +000057 Rewriter Rewrite;
Chris Lattnere365c502007-11-30 22:25:36 +000058 Diagnostic &Diags;
Steve Naroff4f943c22008-03-10 20:43:59 +000059 const LangOptions &LangOpts;
Steve Narofff69cc5d2008-01-30 19:17:43 +000060 unsigned RewriteFailedDiag;
Steve Naroff8c565152008-12-05 17:03:39 +000061 unsigned TryFinallyContainsReturnDiag;
Mike Stump1eb44332009-09-09 15:08:12 +000062
Chris Lattner01c57482007-10-17 22:35:30 +000063 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000064 SourceManager *SM;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000065 TranslationUnitDecl *TUDecl;
Chris Lattner2b2453a2009-01-17 06:22:33 +000066 FileID MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000067 const char *MainFileStart, *MainFileEnd;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000068 SourceLocation LastIncLoc;
Mike Stump1eb44332009-09-09 15:08:12 +000069
Ted Kremeneka526c5c2008-01-07 19:49:32 +000070 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
71 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
72 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Narofffbfe8252008-05-06 18:26:51 +000073 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000074 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
75 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000076 llvm::SmallVector<Stmt *, 32> Stmts;
77 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroff621edce2009-04-29 16:37:50 +000078 // Remember all the @protocol(<expr>) expressions.
79 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +000080
81 llvm::DenseSet<uint64_t> CopyDestroyCache;
82
Steve Naroffd82a9ab2008-03-15 00:55:56 +000083 unsigned NumObjCStringLiterals;
Mike Stump1eb44332009-09-09 15:08:12 +000084
Steve Naroffebf2b562007-10-23 23:50:29 +000085 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000086 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000087 FunctionDecl *MsgSendStretFunctionDecl;
88 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000089 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000090 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000091 FunctionDecl *GetMetaClassFunctionDecl;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +000092 FunctionDecl *GetSuperClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000093 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000094 FunctionDecl *CFStringFunctionDecl;
Steve Naroffc0a123c2008-03-11 17:37:02 +000095 FunctionDecl *SuperContructorFunctionDecl;
Mike Stump1eb44332009-09-09 15:08:12 +000096
Steve Naroffbeaf2992007-11-03 11:27:19 +000097 // ObjC string constant support.
Steve Naroff248a7532008-04-15 22:42:06 +000098 VarDecl *ConstantStringClassReference;
Steve Naroffbeaf2992007-11-03 11:27:19 +000099 RecordDecl *NSStringRecord;
Mike Stump1eb44332009-09-09 15:08:12 +0000100
Fariborz Jahanianb586cce2008-01-16 00:09:11 +0000101 // ObjC foreach break/continue generation support.
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000102 int BcLabelCount;
Mike Stump1eb44332009-09-09 15:08:12 +0000103
Steve Naroff874e2322007-11-15 10:28:18 +0000104 // Needed for super.
Steve Naroff54055232008-10-27 17:20:55 +0000105 ObjCMethodDecl *CurMethodDef;
Steve Naroff874e2322007-11-15 10:28:18 +0000106 RecordDecl *SuperStructDecl;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000107 RecordDecl *ConstantStringDecl;
Mike Stump1eb44332009-09-09 15:08:12 +0000108
Steve Naroff621edce2009-04-29 16:37:50 +0000109 TypeDecl *ProtocolTypeDecl;
110 QualType getProtocolType();
Mike Stump1eb44332009-09-09 15:08:12 +0000111
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000112 // Needed for header files being rewritten
113 bool IsHeader;
Mike Stump1eb44332009-09-09 15:08:12 +0000114
Steve Naroffa7b402d2008-03-28 22:26:09 +0000115 std::string InFileName;
Eli Friedman66d6f042009-05-18 22:20:00 +0000116 llvm::raw_ostream* OutFile;
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000117
118 bool SilenceRewriteMacroWarning;
Fariborz Jahanianf292fcf2010-01-07 22:51:18 +0000119 bool objc_impl_method;
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000120
Steve Naroffba92b2e2008-03-27 22:29:16 +0000121 std::string Preamble;
Steve Naroff54055232008-10-27 17:20:55 +0000122
123 // Block expressions.
124 llvm::SmallVector<BlockExpr *, 32> Blocks;
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000125 llvm::SmallVector<int, 32> InnerDeclRefsCount;
126 llvm::SmallVector<BlockDeclRefExpr *, 32> InnerDeclRefs;
127
Steve Naroff54055232008-10-27 17:20:55 +0000128 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
Mike Stump1eb44332009-09-09 15:08:12 +0000129
Steve Naroff54055232008-10-27 17:20:55 +0000130 // Block related declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +0000131 llvm::SmallVector<ValueDecl *, 8> BlockByCopyDecls;
132 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
133 llvm::SmallVector<ValueDecl *, 8> BlockByRefDecls;
134 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000135 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
Steve Naroff54055232008-10-27 17:20:55 +0000136 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +0000137 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
138
Steve Naroff54055232008-10-27 17:20:55 +0000139 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
140
Steve Naroffc77a6362008-12-04 16:24:46 +0000141 // This maps a property to it's assignment statement.
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +0000142 llvm::DenseMap<Expr *, BinaryOperator *> PropSetters;
Steve Naroff8599e7a2008-12-08 16:43:47 +0000143 // This maps a property to it's synthesied message expression.
144 // This allows us to rewrite chained getters (e.g. o.a.b.c).
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +0000145 llvm::DenseMap<Expr *, Stmt *> PropGetters;
Mike Stump1eb44332009-09-09 15:08:12 +0000146
Steve Naroff4c3580e2008-12-04 23:50:32 +0000147 // This maps an original source AST to it's rewritten form. This allows
148 // us to avoid rewriting the same node twice (which is very uncommon).
149 // This is needed to support some of the exotic property rewriting.
150 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Naroff15f081d2008-12-03 00:56:33 +0000151
Steve Naroff54055232008-10-27 17:20:55 +0000152 FunctionDecl *CurFunctionDef;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000153 FunctionDecl *CurFunctionDeclToDeclareForBlock;
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000154 VarDecl *GlobalVarDecl;
Mike Stump1eb44332009-09-09 15:08:12 +0000155
Steve Naroffb619d952008-12-09 12:56:34 +0000156 bool DisableReplaceStmt;
Mike Stump1eb44332009-09-09 15:08:12 +0000157
Nick Lewycky7e749242010-10-31 21:07:24 +0000158 static const int OBJC_ABI_VERSION = 7;
Chris Lattner77cd2a02007-10-11 00:43:27 +0000159 public:
Ted Kremeneke3a61982008-05-31 20:11:04 +0000160 virtual void Initialize(ASTContext &context);
161
Chris Lattnerf04da132007-10-24 17:06:59 +0000162 // Top Level Driver code.
Chris Lattner682bf922009-03-29 16:50:03 +0000163 virtual void HandleTopLevelDecl(DeclGroupRef D) {
164 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I)
165 HandleTopLevelSingleDecl(*I);
166 }
167 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000168 void HandleDeclInMainFile(Decl *D);
Eli Friedman66d6f042009-05-18 22:20:00 +0000169 RewriteObjC(std::string inFile, llvm::raw_ostream *OS,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000170 Diagnostic &D, const LangOptions &LOpts,
171 bool silenceMacroWarn);
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000172
173 ~RewriteObjC() {}
Mike Stump1eb44332009-09-09 15:08:12 +0000174
Chris Lattnerdacbc5d2009-03-28 04:11:33 +0000175 virtual void HandleTranslationUnit(ASTContext &C);
Mike Stump1eb44332009-09-09 15:08:12 +0000176
Fariborz Jahanian88906cd2010-02-05 16:43:40 +0000177 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000178 Stmt *ReplacingStmt = ReplacedNodes[Old];
Mike Stump1eb44332009-09-09 15:08:12 +0000179
Steve Naroff4c3580e2008-12-04 23:50:32 +0000180 if (ReplacingStmt)
181 return; // We can't rewrite the same node twice.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000182
Steve Naroffb619d952008-12-09 12:56:34 +0000183 if (DisableReplaceStmt)
184 return; // Used when rewriting the assignment of a property setter.
185
Steve Naroff4c3580e2008-12-04 23:50:32 +0000186 // If replacement succeeded or warning disabled return with no warning.
Fariborz Jahanian88906cd2010-02-05 16:43:40 +0000187 if (!Rewrite.ReplaceStmt(Old, New)) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000188 ReplacedNodes[Old] = New;
189 return;
190 }
191 if (SilenceRewriteMacroWarning)
192 return;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000193 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
194 << Old->getSourceRange();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000195 }
Steve Naroffb619d952008-12-09 12:56:34 +0000196
197 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
Nick Lewycky7e749242010-10-31 21:07:24 +0000198 // Measure the old text.
Steve Naroffb619d952008-12-09 12:56:34 +0000199 int Size = Rewrite.getRangeSize(SrcRange);
200 if (Size == -1) {
201 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
202 << Old->getSourceRange();
203 return;
204 }
205 // Get the new text.
206 std::string SStr;
207 llvm::raw_string_ostream S(SStr);
Chris Lattnere4f21422009-06-30 01:26:17 +0000208 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
Steve Naroffb619d952008-12-09 12:56:34 +0000209 const std::string &Str = S.str();
210
211 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbard7407dc2009-08-19 19:10:30 +0000212 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroffb619d952008-12-09 12:56:34 +0000213 ReplacedNodes[Old] = New;
214 return;
215 }
216 if (SilenceRewriteMacroWarning)
217 return;
218 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
219 << Old->getSourceRange();
220 }
221
Benjamin Kramerd999b372010-02-14 14:14:16 +0000222 void InsertText(SourceLocation Loc, llvm::StringRef Str,
Steve Naroffba92b2e2008-03-27 22:29:16 +0000223 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000224 // If insertion succeeded or warning disabled return with no warning.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000225 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000226 SilenceRewriteMacroWarning)
227 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000228
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000229 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
230 }
Mike Stump1eb44332009-09-09 15:08:12 +0000231
Chris Lattneraadaf782008-01-31 19:51:04 +0000232 void ReplaceText(SourceLocation Start, unsigned OrigLength,
Benjamin Kramerd999b372010-02-14 14:14:16 +0000233 llvm::StringRef Str) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000234 // If removal succeeded or warning disabled return with no warning.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000235 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
Chris Lattneraadaf782008-01-31 19:51:04 +0000236 SilenceRewriteMacroWarning)
237 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000238
Chris Lattneraadaf782008-01-31 19:51:04 +0000239 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
240 }
Mike Stump1eb44332009-09-09 15:08:12 +0000241
Chris Lattnerf04da132007-10-24 17:06:59 +0000242 // Syntactic Rewriting.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000243 void RewriteInclude();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000244 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffa0876e82008-12-02 17:36:43 +0000245 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
246 ObjCImplementationDecl *IMD,
247 ObjCCategoryImplDecl *CID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000248 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000249 void RewriteImplementationDecl(Decl *Dcl);
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000250 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
251 ObjCMethodDecl *MDecl, std::string &ResultStr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000252 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
253 const FunctionType *&FPRetType);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000254 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
255 ValueDecl *VD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000256 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
257 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
258 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
259 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff6327e0d2009-01-11 01:06:09 +0000260 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff09b266e2007-10-30 23:14:51 +0000261 void RewriteFunctionDecl(FunctionDecl *FD);
Daniel Dunbarfa297fb2010-06-30 19:16:53 +0000262 void RewriteBlockPointerType(std::string& Str, QualType Type);
263 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000264 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000265 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +0000266 void RewriteTypeOfDecl(VarDecl *VD);
Steve Naroff4f95b752008-07-29 18:15:38 +0000267 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffd5255f52007-11-01 13:24:47 +0000268 bool needToScanForQualifiers(QualType T);
Steve Naroff874e2322007-11-15 10:28:18 +0000269 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000270 QualType getConstantStringStructType();
Fariborz Jahanian1f906222010-05-25 15:56:08 +0000271 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
Steve Naroffbaf58c32008-05-31 14:15:04 +0000272 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Mike Stump1eb44332009-09-09 15:08:12 +0000273
Chris Lattnerf04da132007-10-24 17:06:59 +0000274 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000275 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroffc77a6362008-12-04 16:24:46 +0000276 void CollectPropertySetters(Stmt *S);
Mike Stump1eb44332009-09-09 15:08:12 +0000277
Steve Naroff8599e7a2008-12-08 16:43:47 +0000278 Stmt *CurrentBody;
279 ParentMap *PropParentMap; // created lazily.
Mike Stump1eb44332009-09-09 15:08:12 +0000280
Chris Lattnere64b7772007-10-24 16:57:36 +0000281 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +0000282 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart,
283 bool &replaced);
284 Stmt *RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +0000285 Stmt *RewritePropertyOrImplicitGetter(Expr *PropOrGetterRefExpr);
286 Stmt *RewritePropertyOrImplicitSetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroffb619d952008-12-09 12:56:34 +0000287 SourceRange SrcRange);
Steve Naroffb42f8412007-11-05 14:50:49 +0000288 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000289 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000290 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000291 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffb85e77a2009-12-05 21:43:12 +0000292 void WarnAboutReturnGotoStmts(Stmt *S);
293 void HasReturnStmts(Stmt *S, bool &hasReturns);
294 void RewriteTryReturnStmts(Stmt *S);
295 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000296 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000297 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000298 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000299 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
300 SourceLocation OrigEnd);
Mike Stump1eb44332009-09-09 15:08:12 +0000301 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
Fariborz Jahanian1d35b162010-02-22 20:48:10 +0000302 Expr **args, unsigned nargs,
303 SourceLocation StartLoc=SourceLocation(),
304 SourceLocation EndLoc=SourceLocation());
305 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
306 SourceLocation StartLoc=SourceLocation(),
307 SourceLocation EndLoc=SourceLocation());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000308 Stmt *RewriteBreakStmt(BreakStmt *S);
309 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000310 void SynthCountByEnumWithState(std::string &buf);
Mike Stump1eb44332009-09-09 15:08:12 +0000311
Steve Naroff09b266e2007-10-30 23:14:51 +0000312 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000313 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000314 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000315 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000316 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000317 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000318 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000319 void SynthGetSuperClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000320 void SynthSelGetUidFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000321 void SynthSuperContructorFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000322
Chris Lattnerf04da132007-10-24 17:06:59 +0000323 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000324 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000325 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000326
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000327 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000328 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000329
Douglas Gregor653f1b12009-04-23 01:02:12 +0000330 template<typename MethodIterator>
331 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
332 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000333 bool IsInstanceMethod,
Daniel Dunbar4087f272010-08-17 22:39:59 +0000334 llvm::StringRef prefix,
335 llvm::StringRef ClassName,
Chris Lattner158ecb92007-10-25 17:07:24 +0000336 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000337
Steve Naroff621edce2009-04-29 16:37:50 +0000338 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
Daniel Dunbar4087f272010-08-17 22:39:59 +0000339 llvm::StringRef prefix,
340 llvm::StringRef ClassName,
Steve Naroff621edce2009-04-29 16:37:50 +0000341 std::string &Result);
342 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
Daniel Dunbar4087f272010-08-17 22:39:59 +0000343 llvm::StringRef prefix,
344 llvm::StringRef ClassName,
Steve Naroff621edce2009-04-29 16:37:50 +0000345 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000346 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000347 std::string &Result);
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000348 void SynthesizeIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000349 std::string &Result);
Steve Narofface66252008-11-13 20:07:04 +0000350 void RewriteImplementations();
351 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000352
Steve Naroff54055232008-10-27 17:20:55 +0000353 // Block rewriting.
Mike Stump1eb44332009-09-09 15:08:12 +0000354 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff54055232008-10-27 17:20:55 +0000355 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
Mike Stump1eb44332009-09-09 15:08:12 +0000356
Steve Naroff54055232008-10-27 17:20:55 +0000357 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
358 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
Mike Stump1eb44332009-09-09 15:08:12 +0000359
360 // Block specific rewrite rules.
Steve Naroff54055232008-10-27 17:20:55 +0000361 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000362 void RewriteByRefVar(VarDecl *VD);
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +0000363 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +0000364 Stmt *RewriteBlockDeclRefExpr(Expr *VD);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +0000365 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
Steve Naroff54055232008-10-27 17:20:55 +0000366 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Mike Stump1eb44332009-09-09 15:08:12 +0000367
368 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Daniel Dunbar4087f272010-08-17 22:39:59 +0000369 llvm::StringRef funcName, std::string Tag);
Mike Stump1eb44332009-09-09 15:08:12 +0000370 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Daniel Dunbar4087f272010-08-17 22:39:59 +0000371 llvm::StringRef funcName, std::string Tag);
Steve Naroff01aec112009-12-06 21:14:13 +0000372 std::string SynthesizeBlockImpl(BlockExpr *CE,
373 std::string Tag, std::string Desc);
374 std::string SynthesizeBlockDescriptor(std::string DescTag,
375 std::string ImplTag,
Daniel Dunbar4087f272010-08-17 22:39:59 +0000376 int i, llvm::StringRef funcName,
Steve Naroff01aec112009-12-06 21:14:13 +0000377 unsigned hasCopy);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +0000378 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff54055232008-10-27 17:20:55 +0000379 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
Daniel Dunbar4087f272010-08-17 22:39:59 +0000380 llvm::StringRef FunName);
Steve Naroff3d7e7862009-12-05 15:55:59 +0000381 void RewriteRecordBody(RecordDecl *RD);
Mike Stump1eb44332009-09-09 15:08:12 +0000382
Steve Naroff54055232008-10-27 17:20:55 +0000383 void CollectBlockDeclRefInfo(BlockExpr *Exp);
Steve Naroff54055232008-10-27 17:20:55 +0000384 void GetBlockDeclRefExprs(Stmt *S);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000385 void GetInnerBlockDeclRefExprs(Stmt *S,
386 llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +0000387 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
Mike Stump1eb44332009-09-09 15:08:12 +0000388
Steve Naroff54055232008-10-27 17:20:55 +0000389 // We avoid calling Type::isBlockPointerType(), since it operates on the
390 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000391 bool isTopLevelBlockPointerType(QualType T) {
392 return isa<BlockPointerType>(T);
393 }
Mike Stump1eb44332009-09-09 15:08:12 +0000394
Fariborz Jahanian4fc84532010-05-25 17:12:52 +0000395 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
396 /// to a function pointer type and upon success, returns true; false
397 /// otherwise.
398 bool convertBlockPointerToFunctionPointer(QualType &T) {
399 if (isTopLevelBlockPointerType(T)) {
400 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
401 T = Context->getPointerType(BPT->getPointeeType());
402 return true;
403 }
404 return false;
405 }
406
Steve Naroff54055232008-10-27 17:20:55 +0000407 // FIXME: This predicate seems like it would be useful to add to ASTContext.
408 bool isObjCType(QualType T) {
409 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
410 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000411
Steve Naroff54055232008-10-27 17:20:55 +0000412 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000413
Steve Naroff54055232008-10-27 17:20:55 +0000414 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
415 OCT == Context->getCanonicalType(Context->getObjCClassType()))
416 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000417
Ted Kremenek6217b802009-07-29 21:53:49 +0000418 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000419 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000420 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff54055232008-10-27 17:20:55 +0000421 return true;
422 }
423 return false;
424 }
425 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Fariborz Jahaniane985d012010-11-03 23:29:24 +0000426 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
Ted Kremenek8189cde2009-02-07 01:47:29 +0000427 void GetExtentOfArgList(const char *Name, const char *&LParen,
428 const char *&RParen);
Steve Naroffb2f9e512008-11-03 23:29:32 +0000429 void RewriteCastExpr(CStyleCastExpr *CE);
Mike Stump1eb44332009-09-09 15:08:12 +0000430
Daniel Dunbar4087f272010-08-17 22:39:59 +0000431 FunctionDecl *SynthBlockInitFunctionDecl(llvm::StringRef name);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000432 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
433 const llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs);
Mike Stump1eb44332009-09-09 15:08:12 +0000434
Steve Naroff621edce2009-04-29 16:37:50 +0000435 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump1eb44332009-09-09 15:08:12 +0000436 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroff621edce2009-04-29 16:37:50 +0000437 if (From[i] == '"')
438 To += "\\\"";
439 else
440 To += From[i];
441 }
442 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000443 };
John McCall9d125032010-01-15 18:39:57 +0000444
445 // Helper function: create a CStyleCastExpr with trivial type source info.
446 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
John McCall2de56d12010-08-25 11:45:40 +0000447 CastKind Kind, Expr *E) {
John McCall9d125032010-01-15 18:39:57 +0000448 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
John McCallf871d0c2010-08-07 06:22:56 +0000449 return CStyleCastExpr::Create(*Ctx, Ty, Kind, E, 0, TInfo,
450 SourceLocation(), SourceLocation());
John McCall9d125032010-01-15 18:39:57 +0000451 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000452}
453
Mike Stump1eb44332009-09-09 15:08:12 +0000454void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
455 NamedDecl *D) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000456 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000457 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +0000458 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000459 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff54055232008-10-27 17:20:55 +0000460 // All the args are checked/rewritten. Don't call twice!
461 RewriteBlockPointerDecl(D);
462 break;
463 }
464 }
465}
466
467void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000468 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +0000469 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor72564e72009-02-26 23:50:07 +0000470 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff54055232008-10-27 17:20:55 +0000471}
472
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000473static bool IsHeaderFile(const std::string &Filename) {
474 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump1eb44332009-09-09 15:08:12 +0000475
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000476 if (DotPos == std::string::npos) {
477 // no file extension
Mike Stump1eb44332009-09-09 15:08:12 +0000478 return false;
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000479 }
Mike Stump1eb44332009-09-09 15:08:12 +0000480
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000481 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
482 // C header: .h
483 // C++ header: .hh or .H;
484 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump1eb44332009-09-09 15:08:12 +0000485}
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000486
Eli Friedman66d6f042009-05-18 22:20:00 +0000487RewriteObjC::RewriteObjC(std::string inFile, llvm::raw_ostream* OS,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000488 Diagnostic &D, const LangOptions &LOpts,
489 bool silenceMacroWarn)
490 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
491 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Naroffa7b402d2008-03-28 22:26:09 +0000492 IsHeader = IsHeaderFile(inFile);
Mike Stump1eb44332009-09-09 15:08:12 +0000493 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000494 "rewriting sub-expression within a macro (may not be correct)");
Mike Stump1eb44332009-09-09 15:08:12 +0000495 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000496 "rewriter doesn't support user-specified control flow semantics "
497 "for @try/@finally (code may not execute properly)");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000498}
499
Eli Friedmanbce831b2009-05-18 22:29:17 +0000500ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
501 llvm::raw_ostream* OS,
Mike Stump1eb44332009-09-09 15:08:12 +0000502 Diagnostic &Diags,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000503 const LangOptions &LOpts,
504 bool SilenceRewriteMacroWarning) {
505 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere365c502007-11-30 22:25:36 +0000506}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000507
Steve Naroffb29b4272008-04-14 22:03:09 +0000508void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000509 Context = &context;
510 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000511 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000512 MsgSendFunctionDecl = 0;
513 MsgSendSuperFunctionDecl = 0;
514 MsgSendStretFunctionDecl = 0;
515 MsgSendSuperStretFunctionDecl = 0;
516 MsgSendFpretFunctionDecl = 0;
517 GetClassFunctionDecl = 0;
518 GetMetaClassFunctionDecl = 0;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000519 GetSuperClassFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000520 SelGetUidFunctionDecl = 0;
521 CFStringFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000522 ConstantStringClassReference = 0;
523 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000524 CurMethodDef = 0;
525 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000526 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000527 GlobalVarDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000528 SuperStructDecl = 0;
Steve Naroff621edce2009-04-29 16:37:50 +0000529 ProtocolTypeDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000530 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000531 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000532 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000533 NumObjCStringLiterals = 0;
Steve Naroff68272b82008-12-08 20:01:41 +0000534 PropParentMap = 0;
535 CurrentBody = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000536 DisableReplaceStmt = false;
Fariborz Jahanianf292fcf2010-01-07 22:51:18 +0000537 objc_impl_method = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000538
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000539 // Get the ID and start/end of the main file.
540 MainFileID = SM->getMainFileID();
541 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
542 MainFileStart = MainBuf->getBufferStart();
543 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000544
Chris Lattner2c78b872009-04-14 23:22:57 +0000545 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump1eb44332009-09-09 15:08:12 +0000546
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000547 // declaring objc_selector outside the parameter list removes a silly
548 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000549 if (IsHeader)
Steve Naroff62c26322009-02-03 20:39:18 +0000550 Preamble = "#pragma once\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000551 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff46a98a72008-12-23 20:11:22 +0000552 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000553 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000554 if (LangOpts.Microsoft) {
555 // Add a constructor for creating temporary objects.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000556 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
557 ": ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000558 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000559 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000560 Preamble += "};\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000561 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
562 Preamble += "typedef struct objc_object Protocol;\n";
563 Preamble += "#define _REWRITER_typedef_Protocol\n";
564 Preamble += "#endif\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000565 if (LangOpts.Microsoft) {
566 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
567 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
568 } else
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000569 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000570 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000571 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000572 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000573 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000574 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000575 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000576 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000577 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000578 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000579 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000580 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000581 Preamble += "(const char *);\n";
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000582 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
583 Preamble += "(struct objc_class *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000584 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000585 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000586 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
587 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
588 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
589 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
590 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000591 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000592 // @synchronized hooks.
Steve Naroff4ebd7162008-12-08 17:30:33 +0000593 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
594 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
595 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000596 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
597 Preamble += "struct __objcFastEnumerationState {\n\t";
598 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000599 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000600 Preamble += "unsigned long *mutationsPtr;\n\t";
601 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000602 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000603 Preamble += "#define __FASTENUMERATIONSTATE\n";
604 Preamble += "#endif\n";
605 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
606 Preamble += "struct __NSConstantStringImpl {\n";
607 Preamble += " int *isa;\n";
608 Preamble += " int flags;\n";
609 Preamble += " char *str;\n";
610 Preamble += " long length;\n";
611 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000612 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
613 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
614 Preamble += "#else\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000615 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000616 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000617 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
618 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000619 // Blocks preamble.
620 Preamble += "#ifndef BLOCK_IMPL\n";
621 Preamble += "#define BLOCK_IMPL\n";
622 Preamble += "struct __block_impl {\n";
623 Preamble += " void *isa;\n";
624 Preamble += " int Flags;\n";
Steve Naroff01aec112009-12-06 21:14:13 +0000625 Preamble += " int Reserved;\n";
Steve Naroff54055232008-10-27 17:20:55 +0000626 Preamble += " void *FuncPtr;\n";
627 Preamble += "};\n";
Steve Naroff5bc60d02008-12-16 15:50:30 +0000628 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
Steve Naroffc9c1e9c2009-12-06 01:52:22 +0000629 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000630 Preamble += "extern \"C\" __declspec(dllexport) "
631 "void _Block_object_assign(void *, const void *, const int);\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000632 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
633 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
634 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
635 Preamble += "#else\n";
Steve Naroffcd826372010-01-05 18:09:31 +0000636 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
637 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000638 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
639 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
640 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000641 Preamble += "#endif\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000642 if (LangOpts.Microsoft) {
Steve Naroff4ebd7162008-12-08 17:30:33 +0000643 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
644 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Chris Lattner553e5832010-04-13 17:33:56 +0000645 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
Steve Naroffa48396e2008-10-27 18:50:14 +0000646 Preamble += "#define __attribute__(X)\n";
Chris Lattner553e5832010-04-13 17:33:56 +0000647 Preamble += "#endif\n";
Fariborz Jahanian34204192010-01-15 22:29:39 +0000648 Preamble += "#define __weak\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000649 }
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000650 else {
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000651 Preamble += "#define __block\n";
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000652 Preamble += "#define __weak\n";
653 }
Fariborz Jahaniandf496522010-03-02 01:19:04 +0000654 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
655 // as this avoids warning in any 64bit/32bit compilation model.
656 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000657}
658
659
Chris Lattnerf04da132007-10-24 17:06:59 +0000660//===----------------------------------------------------------------------===//
661// Top Level Driver Code
662//===----------------------------------------------------------------------===//
663
Chris Lattner682bf922009-03-29 16:50:03 +0000664void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremeneke50187a2010-02-05 21:28:51 +0000665 if (Diags.hasErrorOccurred())
666 return;
667
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000668 // Two cases: either the decl could be in the main file, or it could be in a
669 // #included file. If the former, rewrite it now. If the later, check to see
670 // if we rewrote the #include/#import.
671 SourceLocation Loc = D->getLocation();
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000672 Loc = SM->getInstantiationLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000673
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000674 // If this is for a builtin, ignore it.
675 if (Loc.isInvalid()) return;
676
Steve Naroffebf2b562007-10-23 23:50:29 +0000677 // Look for built-in declarations that we need to refer during the rewrite.
678 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000679 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000680 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000681 // declared in <Foundation/NSString.h>
Daniel Dunbar4087f272010-08-17 22:39:59 +0000682 if (FVD->getName() == "_NSConstantStringClassReference") {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000683 ConstantStringClassReference = FVD;
684 return;
685 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000686 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000687 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000688 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000689 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000690 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000691 RewriteProtocolDecl(PD);
Mike Stump1eb44332009-09-09 15:08:12 +0000692 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000693 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000694 RewriteForwardProtocolDecl(FP);
Douglas Gregord0434102009-01-09 00:49:46 +0000695 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
696 // Recurse into linkage specifications
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000697 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
698 DIEnd = LSD->decls_end();
Douglas Gregord0434102009-01-09 00:49:46 +0000699 DI != DIEnd; ++DI)
Chris Lattner682bf922009-03-29 16:50:03 +0000700 HandleTopLevelSingleDecl(*DI);
Steve Naroffebf2b562007-10-23 23:50:29 +0000701 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000702 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000703 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000704 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000705}
706
Chris Lattnerf04da132007-10-24 17:06:59 +0000707//===----------------------------------------------------------------------===//
708// Syntactic (non-AST) Rewriting Code
709//===----------------------------------------------------------------------===//
710
Steve Naroffb29b4272008-04-14 22:03:09 +0000711void RewriteObjC::RewriteInclude() {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000712 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000713 llvm::StringRef MainBuf = SM->getBufferData(MainFileID);
714 const char *MainBufStart = MainBuf.begin();
715 const char *MainBufEnd = MainBuf.end();
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000716 size_t ImportLen = strlen("import");
Mike Stump1eb44332009-09-09 15:08:12 +0000717
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000718 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000719 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
720 if (*BufPtr == '#') {
721 if (++BufPtr == MainBufEnd)
722 return;
723 while (*BufPtr == ' ' || *BufPtr == '\t')
724 if (++BufPtr == MainBufEnd)
725 return;
726 if (!strncmp(BufPtr, "import", ImportLen)) {
727 // replace import with include
Mike Stump1eb44332009-09-09 15:08:12 +0000728 SourceLocation ImportLoc =
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000729 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Benjamin Kramerd999b372010-02-14 14:14:16 +0000730 ReplaceText(ImportLoc, ImportLen, "include");
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000731 BufPtr += ImportLen;
732 }
733 }
734 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000735}
736
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000737static std::string getIvarAccessString(ObjCIvarDecl *OID) {
738 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000739 std::string S;
740 S = "((struct ";
741 S += ClassDecl->getIdentifier()->getName();
742 S += "_IMPL *)self)->";
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +0000743 S += OID->getName();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000744 return S;
745}
746
Steve Naroffa0876e82008-12-02 17:36:43 +0000747void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
748 ObjCImplementationDecl *IMD,
749 ObjCCategoryImplDecl *CID) {
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000750 static bool objcGetPropertyDefined = false;
751 static bool objcSetPropertyDefined = false;
Steve Naroffd40910b2008-12-01 20:33:01 +0000752 SourceLocation startLoc = PID->getLocStart();
Benjamin Kramerd999b372010-02-14 14:14:16 +0000753 InsertText(startLoc, "// ");
Steve Naroffeb0646c2008-12-02 15:48:25 +0000754 const char *startBuf = SM->getCharacterData(startLoc);
755 assert((*startBuf == '@') && "bogus @synthesize location");
756 const char *semiBuf = strchr(startBuf, ';');
757 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek8189cde2009-02-07 01:47:29 +0000758 SourceLocation onePastSemiLoc =
759 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000760
761 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
762 return; // FIXME: is this correct?
Mike Stump1eb44332009-09-09 15:08:12 +0000763
Steve Naroffeb0646c2008-12-02 15:48:25 +0000764 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000765 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000766 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000767
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000768 if (!OID)
769 return;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000770 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000771 if (!PD->getGetterMethodDecl()->isDefined()) {
772 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
773 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
774 ObjCPropertyDecl::OBJC_PR_copy));
775 std::string Getr;
776 if (GenGetProperty && !objcGetPropertyDefined) {
777 objcGetPropertyDefined = true;
778 // FIXME. Is this attribute correct in all cases?
779 Getr = "\nextern \"C\" __declspec(dllimport) "
780 "id objc_getProperty(id, SEL, long, bool);\n";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000781 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000782 RewriteObjCMethodDecl(OID->getContainingInterface(),
783 PD->getGetterMethodDecl(), Getr);
784 Getr += "{ ";
785 // Synthesize an explicit cast to gain access to the ivar.
786 // See objc-act.c:objc_synthesize_new_getter() for details.
787 if (GenGetProperty) {
788 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
789 Getr += "typedef ";
790 const FunctionType *FPRetType = 0;
791 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
792 FPRetType);
793 Getr += " _TYPE";
794 if (FPRetType) {
795 Getr += ")"; // close the precedence "scope" for "*".
796
797 // Now, emit the argument types (if any).
798 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
799 Getr += "(";
800 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
801 if (i) Getr += ", ";
802 std::string ParamStr = FT->getArgType(i).getAsString(
803 Context->PrintingPolicy);
804 Getr += ParamStr;
805 }
806 if (FT->isVariadic()) {
807 if (FT->getNumArgs()) Getr += ", ";
808 Getr += "...";
809 }
810 Getr += ")";
811 } else
812 Getr += "()";
813 }
814 Getr += ";\n";
815 Getr += "return (_TYPE)";
816 Getr += "objc_getProperty(self, _cmd, ";
817 SynthesizeIvarOffsetComputation(OID, Getr);
818 Getr += ", 1)";
819 }
820 else
821 Getr += "return " + getIvarAccessString(OID);
822 Getr += "; }";
823 InsertText(onePastSemiLoc, Getr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000824 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000825
826 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
Steve Naroffeb0646c2008-12-02 15:48:25 +0000827 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000828
Steve Naroffeb0646c2008-12-02 15:48:25 +0000829 // Generate the 'setter' function.
830 std::string Setr;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000831 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
832 ObjCPropertyDecl::OBJC_PR_copy);
833 if (GenSetProperty && !objcSetPropertyDefined) {
834 objcSetPropertyDefined = true;
835 // FIXME. Is this attribute correct in all cases?
836 Setr = "\nextern \"C\" __declspec(dllimport) "
837 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
838 }
839
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000840 RewriteObjCMethodDecl(OID->getContainingInterface(),
841 PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000842 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000843 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff15f081d2008-12-03 00:56:33 +0000844 // See objc-act.c:objc_synthesize_new_setter() for details.
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000845 if (GenSetProperty) {
846 Setr += "objc_setProperty (self, _cmd, ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000847 SynthesizeIvarOffsetComputation(OID, Setr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000848 Setr += ", (id)";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000849 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000850 Setr += ", ";
851 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
852 Setr += "0, ";
853 else
854 Setr += "1, ";
855 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
856 Setr += "1)";
857 else
858 Setr += "0)";
859 }
860 else {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000861 Setr += getIvarAccessString(OID) + " = ";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000862 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000863 }
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000864 Setr += "; }";
Benjamin Kramerd999b372010-02-14 14:14:16 +0000865 InsertText(onePastSemiLoc, Setr);
Steve Naroffd40910b2008-12-01 20:33:01 +0000866}
Chris Lattner8a12c272007-10-11 18:38:32 +0000867
Steve Naroffb29b4272008-04-14 22:03:09 +0000868void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000869 // Get the start location and compute the semi location.
870 SourceLocation startLoc = ClassDecl->getLocation();
871 const char *startBuf = SM->getCharacterData(startLoc);
872 const char *semiPtr = strchr(startBuf, ';');
Mike Stump1eb44332009-09-09 15:08:12 +0000873
Chris Lattnerf04da132007-10-24 17:06:59 +0000874 // Translate to typedef's that forward reference structs with the same name
875 // as the class. As a convenience, we include the original declaration
876 // as a comment.
877 std::string typedefString;
Fariborz Jahanian91fbd122010-01-11 22:48:40 +0000878 typedefString += "// @class ";
879 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
880 I != E; ++I) {
881 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
882 typedefString += ForwardDecl->getNameAsString();
883 if (I+1 != E)
884 typedefString += ", ";
885 else
886 typedefString += ";\n";
887 }
888
Chris Lattner67956052009-02-20 18:04:31 +0000889 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
890 I != E; ++I) {
Ted Kremenek321c22f2009-11-18 00:28:11 +0000891 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
Steve Naroff32174822007-11-09 12:50:28 +0000892 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000893 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000894 typedefString += "\n";
895 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000896 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000897 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000898 typedefString += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000899 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000900 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000901 }
Mike Stump1eb44332009-09-09 15:08:12 +0000902
Steve Naroff934f2762007-10-24 22:48:43 +0000903 // Replace the @class with typedefs corresponding to the classes.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000904 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
Chris Lattnerf04da132007-10-24 17:06:59 +0000905}
906
Steve Naroffb29b4272008-04-14 22:03:09 +0000907void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000908 // When method is a synthesized one, such as a getter/setter there is
909 // nothing to rewrite.
910 if (Method->isSynthesized())
911 return;
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000912 SourceLocation LocStart = Method->getLocStart();
913 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000914
Chris Lattner30fc9332009-02-04 01:06:56 +0000915 if (SM->getInstantiationLineNumber(LocEnd) >
916 SM->getInstantiationLineNumber(LocStart)) {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000917 InsertText(LocStart, "#if 0\n");
918 ReplaceText(LocEnd, 1, ";\n#endif\n");
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000919 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000920 InsertText(LocStart, "// ");
Steve Naroff423cb562007-10-30 13:30:57 +0000921 }
922}
923
Mike Stump1eb44332009-09-09 15:08:12 +0000924void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000925 SourceLocation Loc = prop->getAtLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000926
Benjamin Kramerd999b372010-02-14 14:14:16 +0000927 ReplaceText(Loc, 0, "// ");
Steve Naroff6327e0d2009-01-11 01:06:09 +0000928 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000929}
930
Steve Naroffb29b4272008-04-14 22:03:09 +0000931void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000932 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000933
Steve Naroff423cb562007-10-30 13:30:57 +0000934 // FIXME: handle category headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000935 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +0000936
Fariborz Jahanian13751e32010-02-10 01:15:09 +0000937 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
938 E = CatDecl->prop_end(); I != E; ++I)
939 RewriteProperty(*I);
940
Mike Stump1eb44332009-09-09 15:08:12 +0000941 for (ObjCCategoryDecl::instmeth_iterator
942 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000943 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000944 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +0000945 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000946 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000947 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000948 RewriteMethodDeclaration(*I);
949
Steve Naroff423cb562007-10-30 13:30:57 +0000950 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +0000951 ReplaceText(CatDecl->getAtEndRange().getBegin(),
952 strlen("@end"), "/* @end */");
Steve Naroff423cb562007-10-30 13:30:57 +0000953}
954
Steve Naroffb29b4272008-04-14 22:03:09 +0000955void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000956 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000957
Steve Naroff752d6ef2007-10-30 16:42:30 +0000958 // FIXME: handle protocol headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000959 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +0000960
961 for (ObjCProtocolDecl::instmeth_iterator
962 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000963 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000964 RewriteMethodDeclaration(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000965 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000966 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000967 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000968 RewriteMethodDeclaration(*I);
969
Fariborz Jahanian07acdf42010-09-24 18:36:58 +0000970 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
971 E = PDecl->prop_end(); I != E; ++I)
972 RewriteProperty(*I);
973
Steve Naroff752d6ef2007-10-30 16:42:30 +0000974 // Lastly, comment out the @end.
Ted Kremenek782f2f52010-01-07 01:20:12 +0000975 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +0000976 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
Steve Naroff8cc764c2007-11-14 15:03:57 +0000977
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000978 // Must comment out @optional/@required
979 const char *startBuf = SM->getCharacterData(LocStart);
980 const char *endBuf = SM->getCharacterData(LocEnd);
981 for (const char *p = startBuf; p < endBuf; p++) {
982 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
Steve Naroff8cc764c2007-11-14 15:03:57 +0000983 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +0000984 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
Mike Stump1eb44332009-09-09 15:08:12 +0000985
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000986 }
987 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
Steve Naroff8cc764c2007-11-14 15:03:57 +0000988 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +0000989 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
Mike Stump1eb44332009-09-09 15:08:12 +0000990
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000991 }
992 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000993}
994
Steve Naroffb29b4272008-04-14 22:03:09 +0000995void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000996 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000997 if (LocStart.isInvalid())
998 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000999 // FIXME: handle forward protocol that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001000 ReplaceText(LocStart, 0, "// ");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001001}
1002
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001003void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1004 const FunctionType *&FPRetType) {
1005 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001006 ResultStr += "id";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001007 else if (T->isFunctionPointerType() ||
1008 T->isBlockPointerType()) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001009 // needs special handling, since pointer-to-functions have special
1010 // syntax (where a decaration models use).
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001011 QualType retType = T;
Steve Narofff4312dc2008-12-11 19:29:16 +00001012 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00001013 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001014 PointeeTy = PT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001015 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001016 PointeeTy = BPT->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00001017 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001018 ResultStr += FPRetType->getResultType().getAsString(
1019 Context->PrintingPolicy);
Steve Narofff4312dc2008-12-11 19:29:16 +00001020 ResultStr += "(*";
Steve Naroff76e429d2008-07-16 14:40:40 +00001021 }
1022 } else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001023 ResultStr += T.getAsString(Context->PrintingPolicy);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001024}
1025
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001026void RewriteObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1027 ObjCMethodDecl *OMD,
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001028 std::string &ResultStr) {
1029 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1030 const FunctionType *FPRetType = 0;
1031 ResultStr += "\nstatic ";
1032 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001033 ResultStr += " ";
Mike Stump1eb44332009-09-09 15:08:12 +00001034
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001035 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001036 std::string NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001037
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001038 if (OMD->isInstanceMethod())
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001039 NameStr += "_I_";
1040 else
1041 NameStr += "_C_";
Mike Stump1eb44332009-09-09 15:08:12 +00001042
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001043 NameStr += IDecl->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001044 NameStr += "_";
Mike Stump1eb44332009-09-09 15:08:12 +00001045
1046 if (ObjCCategoryImplDecl *CID =
Steve Naroff3e0a5402009-01-08 19:41:02 +00001047 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001048 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001049 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001050 }
Mike Stump1eb44332009-09-09 15:08:12 +00001051 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +00001052 {
1053 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001054 int len = selString.size();
1055 for (int i = 0; i < len; i++)
1056 if (selString[i] == ':')
1057 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001058 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001059 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001060 // Remember this name for metadata emission
1061 MethodInternalNames[OMD] = NameStr;
1062 ResultStr += NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001063
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001064 // Rewrite arguments
1065 ResultStr += "(";
Mike Stump1eb44332009-09-09 15:08:12 +00001066
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001067 // invisible arguments
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001068 if (OMD->isInstanceMethod()) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001069 QualType selfTy = Context->getObjCInterfaceType(IDecl);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001070 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +00001071 if (!LangOpts.Microsoft) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001072 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
Steve Naroff05b8c782008-03-12 00:25:36 +00001073 ResultStr += "struct ";
1074 }
1075 // When rewriting for Microsoft, explicitly omit the structure name.
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001076 ResultStr += IDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001077 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001078 }
1079 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001080 ResultStr += Context->getObjCClassType().getAsString(
1081 Context->PrintingPolicy);
Mike Stump1eb44332009-09-09 15:08:12 +00001082
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001083 ResultStr += " self, ";
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001084 ResultStr += Context->getObjCSelType().getAsString(Context->PrintingPolicy);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001085 ResultStr += " _cmd";
Mike Stump1eb44332009-09-09 15:08:12 +00001086
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001087 // Method arguments.
Chris Lattner89951a82009-02-20 18:43:26 +00001088 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1089 E = OMD->param_end(); PI != E; ++PI) {
1090 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001091 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +00001092 if (PDecl->getType()->isObjCQualifiedIdType()) {
1093 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001094 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +00001095 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001096 std::string Name = PDecl->getNameAsString();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00001097 QualType QT = PDecl->getType();
1098 // Make sure we convert "t (^)(...)" to "t (*)(...)".
1099 if (convertBlockPointerToFunctionPointer(QT))
1100 QT.getAsStringInternal(Name, Context->PrintingPolicy);
1101 else
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001102 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroff543409e2008-04-18 21:13:19 +00001103 ResultStr += Name;
1104 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001105 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +00001106 if (OMD->isVariadic())
1107 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001108 ResultStr += ") ";
Mike Stump1eb44332009-09-09 15:08:12 +00001109
Steve Naroff76e429d2008-07-16 14:40:40 +00001110 if (FPRetType) {
1111 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump1eb44332009-09-09 15:08:12 +00001112
Steve Naroff76e429d2008-07-16 14:40:40 +00001113 // Now, emit the argument types (if any).
Douglas Gregor72564e72009-02-26 23:50:07 +00001114 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001115 ResultStr += "(";
1116 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1117 if (i) ResultStr += ", ";
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001118 std::string ParamStr = FT->getArgType(i).getAsString(
1119 Context->PrintingPolicy);
Steve Naroff76e429d2008-07-16 14:40:40 +00001120 ResultStr += ParamStr;
1121 }
1122 if (FT->isVariadic()) {
1123 if (FT->getNumArgs()) ResultStr += ", ";
1124 ResultStr += "...";
1125 }
1126 ResultStr += ")";
1127 } else {
1128 ResultStr += "()";
1129 }
1130 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001131}
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001132void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001133 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1134 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump1eb44332009-09-09 15:08:12 +00001135
Fariborz Jahaniana1352162010-02-15 21:11:41 +00001136 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
Mike Stump1eb44332009-09-09 15:08:12 +00001137
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001138 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001139 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1140 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001141 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001142 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001143 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001144 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001145 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001146 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redld3a413d2009-04-26 20:35:05 +00001147
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001148 const char *startBuf = SM->getCharacterData(LocStart);
1149 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001150 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001151 }
Mike Stump1eb44332009-09-09 15:08:12 +00001152
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001153 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001154 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1155 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001156 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001157 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001158 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001159 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001160 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001161 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001162
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001163 const char *startBuf = SM->getCharacterData(LocStart);
1164 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001165 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001166 }
Steve Naroffd40910b2008-12-01 20:33:01 +00001167 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001168 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001169 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001170 I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +00001171 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001172 }
1173
Benjamin Kramerd999b372010-02-14 14:14:16 +00001174 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001175}
1176
Steve Naroffb29b4272008-04-14 22:03:09 +00001177void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001178 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001179 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001180 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001181 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001182 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001183 ResultStr += "\n";
1184 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001185 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001186 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001187 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001188 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001189 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001190 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001191 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001192 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001193 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump1eb44332009-09-09 15:08:12 +00001194
1195 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001196 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff6327e0d2009-01-11 01:06:09 +00001197 RewriteProperty(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001198 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001199 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001200 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001201 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001202 for (ObjCInterfaceDecl::classmeth_iterator
1203 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001204 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001205 RewriteMethodDeclaration(*I);
1206
Steve Naroff2feac5e2007-10-30 03:43:13 +00001207 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001208 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1209 "/* @end */");
Steve Naroffbef11852007-10-26 20:53:56 +00001210}
1211
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001212Stmt *RewriteObjC::RewritePropertyOrImplicitSetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroffb619d952008-12-09 12:56:34 +00001213 SourceRange SrcRange) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001214 ObjCMethodDecl *OMD = 0;
1215 QualType Ty;
1216 Selector Sel;
Duncan Sands54bd4572010-10-20 08:21:16 +00001217 Stmt *Receiver = 0;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001218 bool Super = false;
1219 QualType SuperTy;
1220 SourceLocation SuperLocation;
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001221 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr or ObjCImplicitSetterGetterRefExpr.
Steve Naroffc77a6362008-12-04 16:24:46 +00001222 // This allows us to reuse all the fun and games in SynthMessageExpr().
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001223 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS())) {
1224 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1225 OMD = PDecl->getSetterMethodDecl();
1226 Ty = PDecl->getType();
1227 Sel = PDecl->getSetterName();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001228 Super = PropRefExpr->isSuperReceiver();
1229 if (!Super)
1230 Receiver = PropRefExpr->getBase();
1231 else {
1232 SuperTy = PropRefExpr->getSuperType();
1233 SuperLocation = PropRefExpr->getSuperLocation();
1234 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001235 }
1236 else if (ObjCImplicitSetterGetterRefExpr *ImplicitRefExpr =
1237 dyn_cast<ObjCImplicitSetterGetterRefExpr>(BinOp->getLHS())) {
1238 OMD = ImplicitRefExpr->getSetterMethod();
1239 Sel = OMD->getSelector();
1240 Ty = ImplicitRefExpr->getType();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001241 Super = ImplicitRefExpr->isSuperReceiver();
1242 if (!Super)
1243 Receiver = ImplicitRefExpr->getBase();
1244 else {
1245 SuperTy = ImplicitRefExpr->getSuperType();
1246 SuperLocation = ImplicitRefExpr->getSuperLocation();
1247 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001248 }
1249
1250 assert(OMD && "RewritePropertyOrImplicitSetter - null OMD");
Steve Naroffc77a6362008-12-04 16:24:46 +00001251 llvm::SmallVector<Expr *, 1> ExprVec;
1252 ExprVec.push_back(newStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001253
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001254 ObjCMessageExpr *MsgExpr;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001255 if (Super)
Douglas Gregor04badcf2010-04-21 00:45:42 +00001256 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001257 Ty.getNonReferenceType(),
Douglas Gregor04badcf2010-04-21 00:45:42 +00001258 /*FIXME?*/SourceLocation(),
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001259 SuperLocation,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001260 /*IsInstanceSuper=*/true,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001261 SuperTy,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001262 Sel, OMD,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001263 &ExprVec[0], 1,
1264 /*FIXME:*/SourceLocation());
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001265 else {
1266 // FIXME. Refactor this into common code with that in
1267 // RewritePropertyOrImplicitGetter
1268 assert(Receiver && "RewritePropertyOrImplicitSetter - null Receiver");
1269 if (Expr *Exp = dyn_cast<Expr>(Receiver))
1270 if (PropGetters[Exp])
1271 // This allows us to handle chain/nested property/implicit getters.
1272 Receiver = PropGetters[Exp];
1273
Douglas Gregor04badcf2010-04-21 00:45:42 +00001274 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001275 Ty.getNonReferenceType(),
Douglas Gregor04badcf2010-04-21 00:45:42 +00001276 /*FIXME: */SourceLocation(),
1277 cast<Expr>(Receiver),
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001278 Sel, OMD,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001279 &ExprVec[0], 1,
1280 /*FIXME:*/SourceLocation());
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001281 }
Steve Naroffc77a6362008-12-04 16:24:46 +00001282 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001283
Steve Naroffc77a6362008-12-04 16:24:46 +00001284 // Now do the actual rewrite.
Steve Naroffb619d952008-12-09 12:56:34 +00001285 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffe58ee0c2008-12-10 14:53:27 +00001286 //delete BinOp;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001287 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1288 // to things that stay around.
1289 Context->Deallocate(MsgExpr);
Steve Naroffc77a6362008-12-04 16:24:46 +00001290 return ReplacingStmt;
Steve Naroff15f081d2008-12-03 00:56:33 +00001291}
1292
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001293Stmt *RewriteObjC::RewritePropertyOrImplicitGetter(Expr *PropOrGetterRefExpr) {
1294 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr or ImplicitGetter.
Steve Naroff15f081d2008-12-03 00:56:33 +00001295 // This allows us to reuse all the fun and games in SynthMessageExpr().
Ted Kremenek3b562af2010-10-19 23:10:22 +00001296 Stmt *Receiver = 0;
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001297 ObjCMethodDecl *OMD = 0;
1298 QualType Ty;
1299 Selector Sel;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001300 bool Super = false;
1301 QualType SuperTy;
1302 SourceLocation SuperLocation;
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001303 if (ObjCPropertyRefExpr *PropRefExpr =
1304 dyn_cast<ObjCPropertyRefExpr>(PropOrGetterRefExpr)) {
1305 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1306 OMD = PDecl->getGetterMethodDecl();
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001307 Ty = PDecl->getType();
1308 Sel = PDecl->getGetterName();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001309 Super = PropRefExpr->isSuperReceiver();
1310 if (!Super)
1311 Receiver = PropRefExpr->getBase();
1312 else {
1313 SuperTy = PropRefExpr->getSuperType();
1314 SuperLocation = PropRefExpr->getSuperLocation();
1315 }
Steve Naroff8599e7a2008-12-08 16:43:47 +00001316 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001317 else if (ObjCImplicitSetterGetterRefExpr *ImplicitRefExpr =
1318 dyn_cast<ObjCImplicitSetterGetterRefExpr>(PropOrGetterRefExpr)) {
1319 OMD = ImplicitRefExpr->getGetterMethod();
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001320 Sel = OMD->getSelector();
1321 Ty = ImplicitRefExpr->getType();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001322 Super = ImplicitRefExpr->isSuperReceiver();
1323 if (!Super)
1324 Receiver = ImplicitRefExpr->getBase();
1325 else {
1326 SuperTy = ImplicitRefExpr->getSuperType();
1327 SuperLocation = ImplicitRefExpr->getSuperLocation();
1328 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001329 }
1330
1331 assert (OMD && "RewritePropertyOrImplicitGetter - OMD is null");
1332
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001333 ObjCMessageExpr *MsgExpr;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001334 if (Super)
Douglas Gregor04badcf2010-04-21 00:45:42 +00001335 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001336 Ty.getNonReferenceType(),
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001337 /*FIXME?*/SourceLocation(),
1338 SuperLocation,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001339 /*IsInstanceSuper=*/true,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001340 SuperTy,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001341 Sel, OMD,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001342 0, 0,
1343 /*FIXME:*/SourceLocation());
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001344 else {
1345 assert (Receiver && "RewritePropertyOrImplicitGetter - Receiver is null");
1346 if (Expr *Exp = dyn_cast<Expr>(Receiver))
1347 if (PropGetters[Exp])
1348 // This allows us to handle chain/nested property/implicit getters.
1349 Receiver = PropGetters[Exp];
Douglas Gregor04badcf2010-04-21 00:45:42 +00001350 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001351 Ty.getNonReferenceType(),
Douglas Gregor04badcf2010-04-21 00:45:42 +00001352 /*FIXME:*/SourceLocation(),
1353 cast<Expr>(Receiver),
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001354 Sel, OMD,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001355 0, 0,
1356 /*FIXME:*/SourceLocation());
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001357 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001358
Steve Naroff4c3580e2008-12-04 23:50:32 +00001359 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001360
1361 if (!PropParentMap)
1362 PropParentMap = new ParentMap(CurrentBody);
1363
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001364 Stmt *Parent = PropParentMap->getParent(PropOrGetterRefExpr);
1365 if (Parent && (isa<ObjCPropertyRefExpr>(Parent) ||
1366 isa<ObjCImplicitSetterGetterRefExpr>(Parent))) {
Steve Naroff8599e7a2008-12-08 16:43:47 +00001367 // We stash away the ReplacingStmt since actually doing the
1368 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001369 PropGetters[PropOrGetterRefExpr] = ReplacingStmt;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001370 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1371 // to things that stay around.
1372 Context->Deallocate(MsgExpr);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001373 return PropOrGetterRefExpr; // return the original...
Steve Naroff8599e7a2008-12-08 16:43:47 +00001374 } else {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001375 ReplaceStmt(PropOrGetterRefExpr, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001376 // delete PropRefExpr; elsewhere...
Ted Kremenek8189cde2009-02-07 01:47:29 +00001377 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1378 // to things that stay around.
1379 Context->Deallocate(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001380 return ReplacingStmt;
1381 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001382}
1383
Mike Stump1eb44332009-09-09 15:08:12 +00001384Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001385 SourceLocation OrigStart,
1386 bool &replaced) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001387 ObjCIvarDecl *D = IV->getDecl();
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001388 const Expr *BaseExpr = IV->getBase();
Steve Naroff54055232008-10-27 17:20:55 +00001389 if (CurMethodDef) {
Fariborz Jahanian8f095432010-01-26 18:28:51 +00001390 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001391 ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001392 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanianffbdead2010-01-26 20:37:44 +00001393 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
Steve Narofff0757612008-05-08 17:52:16 +00001394 // lookup which class implements the instance variable.
1395 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001396 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001397 clsDeclared);
Steve Narofff0757612008-05-08 17:52:16 +00001398 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001399
Steve Narofff0757612008-05-08 17:52:16 +00001400 // Synthesize an explicit cast to gain access to the ivar.
1401 std::string RecName = clsDeclared->getIdentifier()->getName();
1402 RecName += "_IMPL";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001403 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001404 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001405 SourceLocation(), II);
Steve Narofff0757612008-05-08 17:52:16 +00001406 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1407 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001408 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
John McCall2de56d12010-08-25 11:45:40 +00001409 CK_Unknown,
John McCall9d125032010-01-15 18:39:57 +00001410 IV->getBase());
Steve Narofff0757612008-05-08 17:52:16 +00001411 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001412 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1413 IV->getBase()->getLocEnd(),
1414 castExpr);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001415 replaced = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001416 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +00001417 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001418 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1419 IV->getLocation(),
1420 D->getType());
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001421 // delete IV; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Narofff0757612008-05-08 17:52:16 +00001422 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001423 }
Fariborz Jahanian7e20ffe2010-01-28 01:41:20 +00001424 // Get the new text
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001425 // Cannot delete IV->getBase(), since PE points to it.
1426 // Replace the old base with the cast. This is important when doing
1427 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001428 IV->setBase(PE);
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001429 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001430 }
Steve Naroff84472a82008-04-18 21:55:08 +00001431 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001432 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump1eb44332009-09-09 15:08:12 +00001433
Steve Naroff9f525972008-05-06 23:20:07 +00001434 // Explicit ivar refs need to have a cast inserted.
1435 // FIXME: consider sharing some of this code with the code above.
Fariborz Jahanian26337b22010-01-12 17:31:23 +00001436 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Fariborz Jahanianc374cd92010-01-11 17:50:35 +00001437 ObjCInterfaceType *iFaceDecl =
1438 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001439 // lookup which class implements the instance variable.
1440 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001441 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001442 clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001443 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001444
Steve Naroff9f525972008-05-06 23:20:07 +00001445 // Synthesize an explicit cast to gain access to the ivar.
1446 std::string RecName = clsDeclared->getIdentifier()->getName();
1447 RecName += "_IMPL";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001448 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001449 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001450 SourceLocation(), II);
Steve Naroff9f525972008-05-06 23:20:07 +00001451 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1452 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001453 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
John McCall2de56d12010-08-25 11:45:40 +00001454 CK_Unknown,
John McCall9d125032010-01-15 18:39:57 +00001455 IV->getBase());
Steve Naroff9f525972008-05-06 23:20:07 +00001456 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001457 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner8d366162008-05-28 16:38:23 +00001458 IV->getBase()->getLocEnd(), castExpr);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001459 replaced = true;
Steve Naroff9f525972008-05-06 23:20:07 +00001460 // Cannot delete IV->getBase(), since PE points to it.
1461 // Replace the old base with the cast. This is important when doing
1462 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001463 IV->setBase(PE);
Steve Naroff9f525972008-05-06 23:20:07 +00001464 return IV;
1465 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001466 }
Steve Naroff84472a82008-04-18 21:55:08 +00001467 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +00001468}
1469
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001470Stmt *RewriteObjC::RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced) {
1471 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1472 CI != E; ++CI) {
1473 if (*CI) {
1474 Stmt *newStmt = RewriteObjCNestedIvarRefExpr(*CI, replaced);
1475 if (newStmt)
1476 *CI = newStmt;
1477 }
1478 }
1479 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
1480 SourceRange OrigStmtRange = S->getSourceRange();
1481 Stmt *newStmt = RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin(),
1482 replaced);
1483 return newStmt;
Fariborz Jahanian376338a2010-02-05 17:48:10 +00001484 }
1485 if (ObjCMessageExpr *MsgRefExpr = dyn_cast<ObjCMessageExpr>(S)) {
1486 Stmt *newStmt = SynthMessageExpr(MsgRefExpr);
1487 return newStmt;
1488 }
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001489 return S;
1490}
1491
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001492/// SynthCountByEnumWithState - To print:
1493/// ((unsigned int (*)
1494/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001495/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001496/// sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001497/// "countByEnumeratingWithState:objects:count:"),
1498/// &enumState,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001499/// (id *)items, (unsigned int)16)
1500///
Steve Naroffb29b4272008-04-14 22:03:09 +00001501void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001502 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1503 "id *, unsigned int))(void *)objc_msgSend)";
1504 buf += "\n\t\t";
1505 buf += "((id)l_collection,\n\t\t";
1506 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1507 buf += "\n\t\t";
1508 buf += "&enumState, "
1509 "(id *)items, (unsigned int)16)";
1510}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001511
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001512/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1513/// statement to exit to its outer synthesized loop.
1514///
Steve Naroffb29b4272008-04-14 22:03:09 +00001515Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001516 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1517 return S;
1518 // replace break with goto __break_label
1519 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001520
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001521 SourceLocation startLoc = S->getLocStart();
1522 buf = "goto __break_label_";
1523 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001524 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001525
1526 return 0;
1527}
1528
1529/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1530/// statement to continue with its inner synthesized loop.
1531///
Steve Naroffb29b4272008-04-14 22:03:09 +00001532Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001533 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1534 return S;
1535 // replace continue with goto __continue_label
1536 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001537
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001538 SourceLocation startLoc = S->getLocStart();
1539 buf = "goto __continue_label_";
1540 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001541 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001542
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001543 return 0;
1544}
1545
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001546/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001547/// It rewrites:
1548/// for ( type elem in collection) { stmts; }
Mike Stump1eb44332009-09-09 15:08:12 +00001549
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001550/// Into:
1551/// {
Mike Stump1eb44332009-09-09 15:08:12 +00001552/// type elem;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001553/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001554/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001555/// id l_collection = (id)collection;
Mike Stump1eb44332009-09-09 15:08:12 +00001556/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001557/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001558/// if (limit) {
1559/// unsigned long startMutations = *enumState.mutationsPtr;
1560/// do {
1561/// unsigned long counter = 0;
1562/// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001563/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001564/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001565/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001566/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001567/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001568/// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001569/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001570/// objects:items count:16]);
1571/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001572/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001573/// }
1574/// else
1575/// elem = nil;
1576/// }
1577///
Steve Naroffb29b4272008-04-14 22:03:09 +00001578Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001579 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001580 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001581 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001582 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump1eb44332009-09-09 15:08:12 +00001583 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001584 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001585
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001586 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001587 const char *startBuf = SM->getCharacterData(startLoc);
Daniel Dunbar4087f272010-08-17 22:39:59 +00001588 llvm::StringRef elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001589 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001590 std::string buf;
1591 buf = "\n{\n\t";
1592 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1593 // type elem;
Chris Lattner7e24e822009-03-28 06:33:19 +00001594 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001595 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001596 if (ElementType->isObjCQualifiedIdType() ||
1597 ElementType->isObjCQualifiedInterfaceType())
1598 // Simply use 'id' for all qualified types.
1599 elementTypeAsString = "id";
1600 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001601 elementTypeAsString = ElementType.getAsString(Context->PrintingPolicy);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001602 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001603 buf += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00001604 elementName = D->getName();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001605 buf += elementName;
1606 buf += ";\n\t";
1607 }
Chris Lattner06767512008-04-08 05:52:18 +00001608 else {
1609 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Daniel Dunbar4087f272010-08-17 22:39:59 +00001610 elementName = DR->getDecl()->getName();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001611 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1612 if (VD->getType()->isObjCQualifiedIdType() ||
1613 VD->getType()->isObjCQualifiedInterfaceType())
1614 // Simply use 'id' for all qualified types.
1615 elementTypeAsString = "id";
1616 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001617 elementTypeAsString = VD->getType().getAsString(Context->PrintingPolicy);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001618 }
Mike Stump1eb44332009-09-09 15:08:12 +00001619
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001620 // struct __objcFastEnumerationState enumState = { 0 };
1621 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1622 // id items[16];
1623 buf += "id items[16];\n\t";
1624 // id l_collection = (id)
1625 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001626 // Find start location of 'collection' the hard way!
1627 const char *startCollectionBuf = startBuf;
1628 startCollectionBuf += 3; // skip 'for'
1629 startCollectionBuf = strchr(startCollectionBuf, '(');
1630 startCollectionBuf++; // skip '('
1631 // find 'in' and skip it.
1632 while (*startCollectionBuf != ' ' ||
1633 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1634 (*(startCollectionBuf+3) != ' ' &&
1635 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1636 startCollectionBuf++;
1637 startCollectionBuf += 3;
Mike Stump1eb44332009-09-09 15:08:12 +00001638
1639 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001640 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001641 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001642 SourceLocation rightParenLoc = S->getRParenLoc();
1643 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1644 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001645 buf = ";\n\t";
Mike Stump1eb44332009-09-09 15:08:12 +00001646
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001647 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1648 // objects:items count:16];
1649 // which is synthesized into:
Mike Stump1eb44332009-09-09 15:08:12 +00001650 // unsigned int limit =
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001651 // ((unsigned int (*)
1652 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001653 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001654 // sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001655 // "countByEnumeratingWithState:objects:count:"),
1656 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001657 // (id *)items, (unsigned int)16);
1658 buf += "unsigned long limit =\n\t\t";
1659 SynthCountByEnumWithState(buf);
1660 buf += ";\n\t";
1661 /// if (limit) {
1662 /// unsigned long startMutations = *enumState.mutationsPtr;
1663 /// do {
1664 /// unsigned long counter = 0;
1665 /// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001666 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001667 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001668 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001669 buf += "if (limit) {\n\t";
1670 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1671 buf += "do {\n\t\t";
1672 buf += "unsigned long counter = 0;\n\t\t";
1673 buf += "do {\n\t\t\t";
1674 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1675 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1676 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001677 buf += " = (";
1678 buf += elementTypeAsString;
1679 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001680 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001681 ReplaceText(lparenLoc, 1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001682
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001683 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001684 /// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001685 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001686 /// objects:items count:16]);
1687 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001688 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001689 /// }
1690 /// else
1691 /// elem = nil;
1692 /// }
Mike Stump1eb44332009-09-09 15:08:12 +00001693 ///
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001694 buf = ";\n\t";
1695 buf += "__continue_label_";
1696 buf += utostr(ObjCBcLabelNo.back());
1697 buf += ": ;";
1698 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001699 buf += "} while (counter < limit);\n\t";
1700 buf += "} while (limit = ";
1701 SynthCountByEnumWithState(buf);
1702 buf += ");\n\t";
1703 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001704 buf += " = ((";
1705 buf += elementTypeAsString;
1706 buf += ")0);\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001707 buf += "__break_label_";
1708 buf += utostr(ObjCBcLabelNo.back());
1709 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001710 buf += "}\n\t";
1711 buf += "else\n\t\t";
1712 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001713 buf += " = ((";
1714 buf += elementTypeAsString;
1715 buf += ")0);\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001716 buf += "}\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001717
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001718 // Insert all these *after* the statement body.
Sebastian Redld3a413d2009-04-26 20:35:05 +00001719 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Naroff600e4e82008-07-21 18:26:02 +00001720 if (isa<CompoundStmt>(S->getBody())) {
1721 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001722 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001723 } else {
1724 /* Need to treat single statements specially. For example:
1725 *
1726 * for (A *a in b) if (stuff()) break;
1727 * for (A *a in b) xxxyy;
1728 *
1729 * The following code simply scans ahead to the semi to find the actual end.
1730 */
1731 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1732 const char *semiBuf = strchr(stmtBuf, ';');
1733 assert(semiBuf && "Can't find ';'");
1734 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001735 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001736 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001737 Stmts.pop_back();
1738 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001739 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001740}
1741
Mike Stump1eb44332009-09-09 15:08:12 +00001742/// RewriteObjCSynchronizedStmt -
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001743/// This routine rewrites @synchronized(expr) stmt;
1744/// into:
1745/// objc_sync_enter(expr);
1746/// @try stmt @finally { objc_sync_exit(expr); }
1747///
Steve Naroffb29b4272008-04-14 22:03:09 +00001748Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001749 // Get the start location and compute the semi location.
1750 SourceLocation startLoc = S->getLocStart();
1751 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001752
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001753 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump1eb44332009-09-09 15:08:12 +00001754
1755 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001756 buf = "objc_sync_enter((id)";
1757 const char *lparenBuf = startBuf;
1758 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramerd999b372010-02-14 14:14:16 +00001759 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001760 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1761 // the sync expression is typically a message expression that's already
Steve Naroffc7089f12008-08-19 13:04:19 +00001762 // been rewritten! (which implies the SourceLocation's are invalid).
1763 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001764 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001765 while (*endBuf != ')') endBuf--;
1766 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001767 buf = ");\n";
1768 // declare a new scope with two variables, _stack and _rethrow.
1769 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1770 buf += "int buf[18/*32-bit i386*/];\n";
1771 buf += "char *pointers[4];} _stack;\n";
1772 buf += "id volatile _rethrow = 0;\n";
1773 buf += "objc_exception_try_enter(&_stack);\n";
1774 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001775 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001776 startLoc = S->getSynchBody()->getLocEnd();
1777 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001778
Steve Naroffc7089f12008-08-19 13:04:19 +00001779 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001780 SourceLocation lastCurlyLoc = startLoc;
1781 buf = "}\nelse {\n";
1782 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroff621edce2009-04-29 16:37:50 +00001783 buf += "}\n";
1784 buf += "{ /* implicit finally clause */\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001785 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb85e77a2009-12-05 21:43:12 +00001786
1787 std::string syncBuf;
1788 syncBuf += " objc_sync_exit(";
John McCall9d125032010-01-15 18:39:57 +00001789 Expr *syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCall2de56d12010-08-25 11:45:40 +00001790 CK_Unknown,
John McCall9d125032010-01-15 18:39:57 +00001791 S->getSynchExpr());
Ted Kremeneka95d3752008-09-13 05:16:45 +00001792 std::string syncExprBufS;
1793 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00001794 syncExpr->printPretty(syncExprBuf, *Context, 0,
1795 PrintingPolicy(LangOpts));
Steve Naroffb85e77a2009-12-05 21:43:12 +00001796 syncBuf += syncExprBuf.str();
1797 syncBuf += ");";
1798
1799 buf += syncBuf;
1800 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001801 buf += "}\n";
1802 buf += "}";
Mike Stump1eb44332009-09-09 15:08:12 +00001803
Benjamin Kramerd999b372010-02-14 14:14:16 +00001804 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001805
1806 bool hasReturns = false;
1807 HasReturnStmts(S->getSynchBody(), hasReturns);
1808 if (hasReturns)
1809 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1810
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001811 return 0;
1812}
1813
Steve Naroffb85e77a2009-12-05 21:43:12 +00001814void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1815{
Steve Naroff8c565152008-12-05 17:03:39 +00001816 // Perform a bottom up traversal of all children.
1817 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1818 CI != E; ++CI)
1819 if (*CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001820 WarnAboutReturnGotoStmts(*CI);
Steve Naroff8c565152008-12-05 17:03:39 +00001821
Steve Naroffb85e77a2009-12-05 21:43:12 +00001822 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001823 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff8c565152008-12-05 17:03:39 +00001824 TryFinallyContainsReturnDiag);
1825 }
1826 return;
1827}
1828
Steve Naroffb85e77a2009-12-05 21:43:12 +00001829void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1830{
1831 // Perform a bottom up traversal of all children.
1832 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1833 CI != E; ++CI)
1834 if (*CI)
1835 HasReturnStmts(*CI, hasReturns);
1836
1837 if (isa<ReturnStmt>(S))
1838 hasReturns = true;
1839 return;
1840}
1841
1842void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1843 // Perform a bottom up traversal of all children.
1844 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1845 CI != E; ++CI)
1846 if (*CI) {
1847 RewriteTryReturnStmts(*CI);
1848 }
1849 if (isa<ReturnStmt>(S)) {
1850 SourceLocation startLoc = S->getLocStart();
1851 const char *startBuf = SM->getCharacterData(startLoc);
1852
1853 const char *semiBuf = strchr(startBuf, ';');
1854 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1855 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1856
1857 std::string buf;
1858 buf = "{ objc_exception_try_exit(&_stack); return";
1859
Benjamin Kramerd999b372010-02-14 14:14:16 +00001860 ReplaceText(startLoc, 6, buf);
1861 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001862 }
1863 return;
1864}
1865
1866void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1867 // Perform a bottom up traversal of all children.
1868 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1869 CI != E; ++CI)
1870 if (*CI) {
1871 RewriteSyncReturnStmts(*CI, syncExitBuf);
1872 }
1873 if (isa<ReturnStmt>(S)) {
1874 SourceLocation startLoc = S->getLocStart();
1875 const char *startBuf = SM->getCharacterData(startLoc);
1876
1877 const char *semiBuf = strchr(startBuf, ';');
1878 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1879 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1880
1881 std::string buf;
1882 buf = "{ objc_exception_try_exit(&_stack);";
1883 buf += syncExitBuf;
1884 buf += " return";
1885
Benjamin Kramerd999b372010-02-14 14:14:16 +00001886 ReplaceText(startLoc, 6, buf);
1887 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001888 }
1889 return;
1890}
1891
Steve Naroffb29b4272008-04-14 22:03:09 +00001892Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001893 // Get the start location and compute the semi location.
1894 SourceLocation startLoc = S->getLocStart();
1895 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001896
Steve Naroff75730982007-11-07 04:08:17 +00001897 assert((*startBuf == '@') && "bogus @try location");
1898
1899 std::string buf;
1900 // declare a new scope with two variables, _stack and _rethrow.
1901 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1902 buf += "int buf[18/*32-bit i386*/];\n";
1903 buf += "char *pointers[4];} _stack;\n";
1904 buf += "id volatile _rethrow = 0;\n";
1905 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001906 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001907
Benjamin Kramerd999b372010-02-14 14:14:16 +00001908 ReplaceText(startLoc, 4, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001909
Steve Naroff75730982007-11-07 04:08:17 +00001910 startLoc = S->getTryBody()->getLocEnd();
1911 startBuf = SM->getCharacterData(startLoc);
1912
1913 assert((*startBuf == '}') && "bogus @try block");
Mike Stump1eb44332009-09-09 15:08:12 +00001914
Steve Naroff75730982007-11-07 04:08:17 +00001915 SourceLocation lastCurlyLoc = startLoc;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001916 if (S->getNumCatchStmts()) {
Steve Naroffc9ba1722008-07-16 15:31:30 +00001917 startLoc = startLoc.getFileLocWithOffset(1);
1918 buf = " /* @catch begin */ else {\n";
1919 buf += " id _caught = objc_exception_extract(&_stack);\n";
1920 buf += " objc_exception_try_enter (&_stack);\n";
1921 buf += " if (_setjmp(_stack.buf))\n";
1922 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1923 buf += " else { /* @catch continue */";
Mike Stump1eb44332009-09-09 15:08:12 +00001924
Benjamin Kramerd999b372010-02-14 14:14:16 +00001925 InsertText(startLoc, buf);
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001926 } else { /* no catch list */
1927 buf = "}\nelse {\n";
1928 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1929 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001930 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffc9ba1722008-07-16 15:31:30 +00001931 }
Steve Naroff75730982007-11-07 04:08:17 +00001932 bool sawIdTypedCatch = false;
1933 Stmt *lastCatchBody = 0;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001934 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1935 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Douglas Gregorc00d8e12010-04-26 16:46:50 +00001936 VarDecl *catchDecl = Catch->getCatchParamDecl();
Steve Naroff75730982007-11-07 04:08:17 +00001937
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001938 if (I == 0)
Steve Naroff75730982007-11-07 04:08:17 +00001939 buf = "if ("; // we are generating code for the first catch clause
1940 else
1941 buf = "else if (";
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001942 startLoc = Catch->getLocStart();
Steve Naroff75730982007-11-07 04:08:17 +00001943 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001944
Steve Naroff75730982007-11-07 04:08:17 +00001945 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump1eb44332009-09-09 15:08:12 +00001946
Steve Naroff75730982007-11-07 04:08:17 +00001947 const char *lParenLoc = strchr(startBuf, '(');
1948
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001949 if (Catch->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001950 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001951 lastCatchBody = Catch->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001952 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1953 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001954 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
Chris Lattner06767512008-04-08 05:52:18 +00001955 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001956 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001957
Steve Naroffe12e6922008-02-01 20:02:07 +00001958 buf += "1) { id _tmp = _caught;";
Daniel Dunbard7407dc2009-08-19 19:10:30 +00001959 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff7ba138a2009-03-03 19:52:17 +00001960 } else if (catchDecl) {
1961 QualType t = catchDecl->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001962 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001963 buf += "1) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001964 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroff75730982007-11-07 04:08:17 +00001965 sawIdTypedCatch = true;
John McCall506b57e2010-05-17 21:00:27 +00001966 } else if (const ObjCObjectPointerType *Ptr =
1967 t->getAs<ObjCObjectPointerType>()) {
1968 // Should be a pointer to a class.
1969 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1970 if (IDecl) {
Steve Naroff21867b12007-11-07 18:43:40 +00001971 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
John McCall506b57e2010-05-17 21:00:27 +00001972 buf += IDecl->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001973 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001974 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroff75730982007-11-07 04:08:17 +00001975 }
1976 }
1977 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001978 lastCatchBody = Catch->getCatchBody();
1979 SourceLocation rParenLoc = Catch->getRParenLoc();
Steve Naroff75730982007-11-07 04:08:17 +00001980 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1981 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1982 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1983 assert((*rParenBuf == ')') && "bogus @catch paren location");
1984 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001985
Mike Stump1eb44332009-09-09 15:08:12 +00001986 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroff75730982007-11-07 04:08:17 +00001987 // declares the @catch parameter).
Benjamin Kramerd999b372010-02-14 14:14:16 +00001988 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff7ba138a2009-03-03 19:52:17 +00001989 } else {
Steve Naroff75730982007-11-07 04:08:17 +00001990 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001991 }
Steve Naroff75730982007-11-07 04:08:17 +00001992 }
1993 // Complete the catch list...
1994 if (lastCatchBody) {
1995 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001996 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1997 "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001998
Steve Naroff378f47a2008-09-11 15:29:03 +00001999 // Insert the last (implicit) else clause *before* the right curly brace.
2000 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
2001 buf = "} /* last catch end */\n";
2002 buf += "else {\n";
2003 buf += " _rethrow = _caught;\n";
2004 buf += " objc_exception_try_exit(&_stack);\n";
2005 buf += "} } /* @catch end */\n";
2006 if (!S->getFinallyStmt())
2007 buf += "}\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002008 InsertText(bodyLoc, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00002009
Steve Naroff75730982007-11-07 04:08:17 +00002010 // Set lastCurlyLoc
2011 lastCurlyLoc = lastCatchBody->getLocEnd();
2012 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002013 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00002014 startLoc = finalStmt->getLocStart();
2015 startBuf = SM->getCharacterData(startLoc);
2016 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump1eb44332009-09-09 15:08:12 +00002017
Benjamin Kramerd999b372010-02-14 14:14:16 +00002018 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump1eb44332009-09-09 15:08:12 +00002019
Steve Naroff75730982007-11-07 04:08:17 +00002020 Stmt *body = finalStmt->getFinallyBody();
2021 SourceLocation startLoc = body->getLocStart();
2022 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00002023 assert(*SM->getCharacterData(startLoc) == '{' &&
2024 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002025 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner06767512008-04-08 05:52:18 +00002026 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002027
Steve Naroff75730982007-11-07 04:08:17 +00002028 startLoc = startLoc.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002029 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Steve Naroff75730982007-11-07 04:08:17 +00002030 endLoc = endLoc.getFileLocWithOffset(-1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002031 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump1eb44332009-09-09 15:08:12 +00002032
Steve Naroff75730982007-11-07 04:08:17 +00002033 // Set lastCurlyLoc
2034 lastCurlyLoc = body->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00002035
Steve Naroff8c565152008-12-05 17:03:39 +00002036 // Now check for any return/continue/go statements within the @try.
Steve Naroffb85e77a2009-12-05 21:43:12 +00002037 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00002038 } else { /* no finally clause - make sure we synthesize an implicit one */
2039 buf = "{ /* implicit finally clause */\n";
2040 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
2041 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
2042 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002043 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00002044
2045 // Now check for any return/continue/go statements within the @try.
2046 // The implicit finally clause won't called if the @try contains any
2047 // jump statements.
2048 bool hasReturns = false;
2049 HasReturnStmts(S->getTryBody(), hasReturns);
2050 if (hasReturns)
2051 RewriteTryReturnStmts(S->getTryBody());
Steve Naroff75730982007-11-07 04:08:17 +00002052 }
2053 // Now emit the final closing curly brace...
2054 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002055 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002056 return 0;
2057}
2058
Mike Stump1eb44332009-09-09 15:08:12 +00002059// This can't be done with ReplaceStmt(S, ThrowExpr), since
2060// the throw expression is typically a message expression that's already
Steve Naroff2bd03922007-11-07 15:32:26 +00002061// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00002062Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00002063 // Get the start location and compute the semi location.
2064 SourceLocation startLoc = S->getLocStart();
2065 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00002066
Steve Naroff2bd03922007-11-07 15:32:26 +00002067 assert((*startBuf == '@') && "bogus @throw location");
2068
2069 std::string buf;
2070 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00002071 if (S->getThrowExpr())
2072 buf = "objc_exception_throw(";
2073 else // add an implicit argument
2074 buf = "objc_exception_throw(_caught";
Mike Stump1eb44332009-09-09 15:08:12 +00002075
Steve Naroff4ba0acb2008-07-25 15:41:30 +00002076 // handle "@ throw" correctly.
2077 const char *wBuf = strchr(startBuf, 'w');
2078 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramerd999b372010-02-14 14:14:16 +00002079 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00002080
Steve Naroff2bd03922007-11-07 15:32:26 +00002081 const char *semiBuf = strchr(startBuf, ';');
2082 assert((*semiBuf == ';') && "@throw: can't find ';'");
2083 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002084 ReplaceText(semiLoc, 1, ");");
Steve Naroff2bd03922007-11-07 15:32:26 +00002085 return 0;
2086}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002087
Steve Naroffb29b4272008-04-14 22:03:09 +00002088Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00002089 // Create a new string expression.
2090 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002091 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002092 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattner2085fd62009-02-18 06:40:38 +00002093 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
2094 StrEncoding.length(), false,StrType,
2095 SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002096 ReplaceStmt(Exp, Replacement);
Mike Stump1eb44332009-09-09 15:08:12 +00002097
Chris Lattner07506182007-11-30 22:53:43 +00002098 // Replace this subexpr in the parent.
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002099 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00002100 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00002101}
2102
Steve Naroffb29b4272008-04-14 22:03:09 +00002103Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff1a937642008-12-22 22:16:07 +00002104 if (!SelGetUidFunctionDecl)
2105 SynthSelGetUidFunctionDecl();
Steve Naroffb42f8412007-11-05 14:50:49 +00002106 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2107 // Create a call to sel_registerName("selName").
2108 llvm::SmallVector<Expr*, 8> SelExprs;
2109 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002110 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002111 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00002112 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00002113 false, argType, SourceLocation()));
Steve Naroffb42f8412007-11-05 14:50:49 +00002114 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2115 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002116 ReplaceStmt(Exp, SelExp);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002117 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00002118 return SelExp;
2119}
2120
Steve Naroffb29b4272008-04-14 22:03:09 +00002121CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002122 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2123 SourceLocation EndLoc) {
Steve Naroffebf2b562007-10-23 23:50:29 +00002124 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00002125 QualType msgSendType = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002126
Steve Naroffebf2b562007-10-23 23:50:29 +00002127 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002128 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002129
Steve Naroffebf2b562007-10-23 23:50:29 +00002130 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00002131 QualType pToFunc = Context->getPointerType(msgSendType);
Anders Carlsson88465d32010-04-23 22:18:37 +00002132 ImplicitCastExpr *ICE =
John McCall2de56d12010-08-25 11:45:40 +00002133 ImplicitCastExpr::Create(*Context, pToFunc, CK_Unknown,
John McCall5baba9d2010-08-25 10:28:54 +00002134 DRE, 0, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00002135
John McCall183700f2009-09-21 23:43:11 +00002136 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002137
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002138 CallExpr *Exp =
Douglas Gregor5291c3c2010-07-13 08:18:22 +00002139 new (Context) CallExpr(*Context, ICE, args, nargs,
2140 FT->getCallResultType(*Context), EndLoc);
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002141 return Exp;
Steve Naroff934f2762007-10-24 22:48:43 +00002142}
2143
Steve Naroffd5255f52007-11-01 13:24:47 +00002144static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2145 const char *&startRef, const char *&endRef) {
2146 while (startBuf < endBuf) {
2147 if (*startBuf == '<')
2148 startRef = startBuf; // mark the start.
2149 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00002150 if (startRef && *startRef == '<') {
2151 endRef = startBuf; // mark the end.
2152 return true;
2153 }
2154 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002155 }
2156 startBuf++;
2157 }
2158 return false;
2159}
2160
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002161static void scanToNextArgument(const char *&argRef) {
2162 int angle = 0;
2163 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2164 if (*argRef == '<')
2165 angle++;
2166 else if (*argRef == '>')
2167 angle--;
2168 argRef++;
2169 }
2170 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2171}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002172
Steve Naroffb29b4272008-04-14 22:03:09 +00002173bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian32132a02010-02-03 21:29:28 +00002174 if (T->isObjCQualifiedIdType())
2175 return true;
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002176 if (const PointerType *PT = T->getAs<PointerType>()) {
2177 if (PT->getPointeeType()->isObjCQualifiedIdType())
2178 return true;
2179 }
2180 if (T->isObjCObjectPointerType()) {
2181 T = T->getPointeeType();
2182 return T->isObjCQualifiedInterfaceType();
2183 }
Fariborz Jahanian24f9cab2010-09-30 20:41:32 +00002184 if (T->isArrayType()) {
2185 QualType ElemTy = Context->getBaseElementType(T);
2186 return needToScanForQualifiers(ElemTy);
2187 }
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002188 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002189}
2190
Steve Naroff4f95b752008-07-29 18:15:38 +00002191void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2192 QualType Type = E->getType();
2193 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00002194 SourceLocation Loc, EndLoc;
Mike Stump1eb44332009-09-09 15:08:12 +00002195
Steve Naroffcda658e2008-11-19 21:15:47 +00002196 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2197 Loc = ECE->getLParenLoc();
2198 EndLoc = ECE->getRParenLoc();
2199 } else {
2200 Loc = E->getLocStart();
2201 EndLoc = E->getLocEnd();
2202 }
2203 // This will defend against trying to rewrite synthesized expressions.
2204 if (Loc.isInvalid() || EndLoc.isInvalid())
2205 return;
2206
Steve Naroff4f95b752008-07-29 18:15:38 +00002207 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00002208 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00002209 const char *startRef = 0, *endRef = 0;
2210 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2211 // Get the locations of the startRef, endRef.
2212 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
2213 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
2214 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002215 InsertText(LessLoc, "/*");
2216 InsertText(GreaterLoc, "*/");
Steve Naroff4f95b752008-07-29 18:15:38 +00002217 }
2218 }
2219}
2220
Steve Naroffb29b4272008-04-14 22:03:09 +00002221void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002222 SourceLocation Loc;
2223 QualType Type;
Douglas Gregor72564e72009-02-26 23:50:07 +00002224 const FunctionProtoType *proto = 0;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002225 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2226 Loc = VD->getLocation();
2227 Type = VD->getType();
2228 }
2229 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2230 Loc = FD->getLocation();
2231 // Check for ObjC 'id' and class types that have been adorned with protocol
2232 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall183700f2009-09-21 23:43:11 +00002233 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002234 assert(funcType && "missing function type");
Douglas Gregor72564e72009-02-26 23:50:07 +00002235 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002236 if (!proto)
2237 return;
2238 Type = proto->getResultType();
2239 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00002240 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2241 Loc = FD->getLocation();
2242 Type = FD->getType();
2243 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002244 else
2245 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002246
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002247 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00002248 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002249
Steve Naroffd5255f52007-11-01 13:24:47 +00002250 const char *endBuf = SM->getCharacterData(Loc);
2251 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00002252 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00002253 startBuf--; // scan backward (from the decl location) for return type.
2254 const char *startRef = 0, *endRef = 0;
2255 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2256 // Get the locations of the startRef, endRef.
2257 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2258 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2259 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002260 InsertText(LessLoc, "/*");
2261 InsertText(GreaterLoc, "*/");
Steve Naroff9165ad32007-10-31 04:38:33 +00002262 }
2263 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002264 if (!proto)
2265 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00002266 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002267 const char *startBuf = SM->getCharacterData(Loc);
2268 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00002269 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2270 if (needToScanForQualifiers(proto->getArgType(i))) {
2271 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002272
Steve Naroffd5255f52007-11-01 13:24:47 +00002273 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002274 // scan forward (from the decl location) for argument types.
2275 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00002276 const char *startRef = 0, *endRef = 0;
2277 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2278 // Get the locations of the startRef, endRef.
Mike Stump1eb44332009-09-09 15:08:12 +00002279 SourceLocation LessLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002280 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002281 SourceLocation GreaterLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002282 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002283 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002284 InsertText(LessLoc, "/*");
2285 InsertText(GreaterLoc, "*/");
Steve Naroffd5255f52007-11-01 13:24:47 +00002286 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002287 startBuf = ++endBuf;
2288 }
2289 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00002290 // If the function name is derived from a macro expansion, then the
2291 // argument buffer will not follow the name. Need to speak with Chris.
2292 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002293 startBuf++; // scan forward (from the decl location) for argument types.
2294 startBuf++;
2295 }
Steve Naroffd5255f52007-11-01 13:24:47 +00002296 }
Steve Naroff9165ad32007-10-31 04:38:33 +00002297}
2298
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002299void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2300 QualType QT = ND->getType();
2301 const Type* TypePtr = QT->getAs<Type>();
2302 if (!isa<TypeOfExprType>(TypePtr))
2303 return;
2304 while (isa<TypeOfExprType>(TypePtr)) {
2305 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2306 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2307 TypePtr = QT->getAs<Type>();
2308 }
2309 // FIXME. This will not work for multiple declarators; as in:
2310 // __typeof__(a) b,c,d;
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002311 std::string TypeAsString(QT.getAsString(Context->PrintingPolicy));
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002312 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2313 const char *startBuf = SM->getCharacterData(DeclLoc);
2314 if (ND->getInit()) {
2315 std::string Name(ND->getNameAsString());
2316 TypeAsString += " " + Name + " = ";
2317 Expr *E = ND->getInit();
2318 SourceLocation startLoc;
2319 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2320 startLoc = ECE->getLParenLoc();
2321 else
2322 startLoc = E->getLocStart();
2323 startLoc = SM->getInstantiationLoc(startLoc);
2324 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002325 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002326 }
2327 else {
2328 SourceLocation X = ND->getLocEnd();
2329 X = SM->getInstantiationLoc(X);
2330 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002331 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002332 }
2333}
2334
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002335// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00002336void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002337 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2338 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002339 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002340 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002341 &ArgTys[0], ArgTys.size(),
2342 false /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002343 false, false, 0, 0,
2344 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002345 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002346 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002347 SelGetUidIdent, getFuncType, 0,
John McCalld931b082010-08-26 03:08:43 +00002348 SC_Extern,
2349 SC_None, false);
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002350}
2351
Steve Naroffb29b4272008-04-14 22:03:09 +00002352void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002353 // declared in <objc/objc.h>
Douglas Gregor51efe562009-01-09 01:47:02 +00002354 if (FD->getIdentifier() &&
Daniel Dunbar4087f272010-08-17 22:39:59 +00002355 FD->getName() == "sel_registerName") {
Steve Naroff09b266e2007-10-30 23:14:51 +00002356 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00002357 return;
2358 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002359 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00002360}
2361
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002362void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2363 std::string TypeString(Type.getAsString(Context->PrintingPolicy));
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002364 const char *argPtr = TypeString.c_str();
2365 if (!strchr(argPtr, '^')) {
2366 Str += TypeString;
2367 return;
2368 }
2369 while (*argPtr) {
2370 Str += (*argPtr == '^' ? '*' : *argPtr);
2371 argPtr++;
2372 }
2373}
2374
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002375// FIXME. Consolidate this routine with RewriteBlockPointerType.
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002376void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2377 ValueDecl *VD) {
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002378 QualType Type = VD->getType();
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002379 std::string TypeString(Type.getAsString(Context->PrintingPolicy));
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002380 const char *argPtr = TypeString.c_str();
2381 int paren = 0;
2382 while (*argPtr) {
2383 switch (*argPtr) {
2384 case '(':
2385 Str += *argPtr;
2386 paren++;
2387 break;
2388 case ')':
2389 Str += *argPtr;
2390 paren--;
2391 break;
2392 case '^':
2393 Str += '*';
2394 if (paren == 1)
2395 Str += VD->getNameAsString();
2396 break;
2397 default:
2398 Str += *argPtr;
2399 break;
2400 }
2401 argPtr++;
2402 }
2403}
2404
2405
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002406void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2407 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2408 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2409 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2410 if (!proto)
2411 return;
2412 QualType Type = proto->getResultType();
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002413 std::string FdStr = Type.getAsString(Context->PrintingPolicy);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002414 FdStr += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00002415 FdStr += FD->getName();
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002416 FdStr += "(";
2417 unsigned numArgs = proto->getNumArgs();
2418 for (unsigned i = 0; i < numArgs; i++) {
2419 QualType ArgType = proto->getArgType(i);
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002420 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002421 if (i+1 < numArgs)
2422 FdStr += ", ";
2423 }
2424 FdStr += ");\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002425 InsertText(FunLocStart, FdStr);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002426 CurFunctionDeclToDeclareForBlock = 0;
2427}
2428
Steve Naroffc0a123c2008-03-11 17:37:02 +00002429// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00002430void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002431 if (SuperContructorFunctionDecl)
2432 return;
Steve Naroff46a98a72008-12-23 20:11:22 +00002433 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroffc0a123c2008-03-11 17:37:02 +00002434 llvm::SmallVector<QualType, 16> ArgTys;
2435 QualType argT = Context->getObjCIdType();
2436 assert(!argT.isNull() && "Can't find 'id' type");
2437 ArgTys.push_back(argT);
2438 ArgTys.push_back(argT);
2439 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2440 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002441 false, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002442 false, false, 0, 0,
2443 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002444 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002445 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002446 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002447 SC_Extern,
2448 SC_None, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002449}
2450
Steve Naroff09b266e2007-10-30 23:14:51 +00002451// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002452void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002453 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2454 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002455 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002456 assert(!argT.isNull() && "Can't find 'id' type");
2457 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002458 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002459 assert(!argT.isNull() && "Can't find 'SEL' type");
2460 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002461 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002462 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002463 true /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002464 false, false, 0, 0,
2465 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002466 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002467 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002468 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002469 SC_Extern,
2470 SC_None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002471}
2472
Steve Naroff874e2322007-11-15 10:28:18 +00002473// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002474void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00002475 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2476 llvm::SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002477 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002478 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002479 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002480 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2481 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2482 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002483 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002484 assert(!argT.isNull() && "Can't find 'SEL' type");
2485 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002486 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00002487 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002488 true /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002489 false, false, 0, 0,
2490 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002491 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002492 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002493 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002494 SC_Extern,
2495 SC_None, false);
Steve Naroff874e2322007-11-15 10:28:18 +00002496}
2497
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002498// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002499void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002500 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2501 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002502 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002503 assert(!argT.isNull() && "Can't find 'id' type");
2504 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002505 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002506 assert(!argT.isNull() && "Can't find 'SEL' type");
2507 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002508 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002509 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002510 true /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002511 false, false, 0, 0,
2512 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002513 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002514 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002515 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002516 SC_Extern,
2517 SC_None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002518}
2519
Mike Stump1eb44332009-09-09 15:08:12 +00002520// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002521// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002522void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump1eb44332009-09-09 15:08:12 +00002523 IdentifierInfo *msgSendIdent =
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002524 &Context->Idents.get("objc_msgSendSuper_stret");
2525 llvm::SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002526 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002527 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002528 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002529 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2530 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2531 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002532 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002533 assert(!argT.isNull() && "Can't find 'SEL' type");
2534 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002535 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002536 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002537 true /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002538 false, false, 0, 0,
2539 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002540 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002541 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002542 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002543 SC_Extern,
2544 SC_None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002545}
2546
Steve Naroff1284db82008-05-08 22:02:18 +00002547// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002548void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002549 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2550 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002551 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002552 assert(!argT.isNull() && "Can't find 'id' type");
2553 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002554 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002555 assert(!argT.isNull() && "Can't find 'SEL' type");
2556 ArgTys.push_back(argT);
Steve Naroff1284db82008-05-08 22:02:18 +00002557 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002558 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002559 true /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002560 false, false, 0, 0,
2561 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002562 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002563 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002564 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002565 SC_Extern,
2566 SC_None, false);
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002567}
2568
Steve Naroff09b266e2007-10-30 23:14:51 +00002569// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002570void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002571 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2572 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002573 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002574 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002575 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002576 false /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002577 false, false, 0, 0,
2578 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002579 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002580 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002581 getClassIdent, getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002582 SC_Extern,
2583 SC_None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002584}
2585
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002586// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2587void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2588 IdentifierInfo *getSuperClassIdent =
2589 &Context->Idents.get("class_getSuperclass");
2590 llvm::SmallVector<QualType, 16> ArgTys;
2591 ArgTys.push_back(Context->getObjCClassType());
2592 QualType getClassType = Context->getFunctionType(Context->getObjCClassType(),
2593 &ArgTys[0], ArgTys.size(),
2594 false /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002595 false, false, 0, 0,
2596 FunctionType::ExtInfo());
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002597 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002598 SourceLocation(),
2599 getSuperClassIdent,
2600 getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002601 SC_Extern,
2602 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002603 false);
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002604}
2605
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002606// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002607void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002608 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2609 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002610 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002611 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002612 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002613 false /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002614 false, false, 0, 0,
2615 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002616 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002617 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002618 getClassIdent, getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002619 SC_Extern,
2620 SC_None, false);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002621}
2622
Steve Naroffb29b4272008-04-14 22:03:09 +00002623Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002624 QualType strType = getConstantStringStructType();
2625
2626 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002627
2628 std::string tmpName = InFileName;
2629 unsigned i;
2630 for (i=0; i < tmpName.length(); i++) {
2631 char c = tmpName.at(i);
2632 // replace any non alphanumeric characters with '_'.
2633 if (!isalpha(c) && (c < '0' || c > '9'))
2634 tmpName[i] = '_';
2635 }
2636 S += tmpName;
2637 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002638 S += utostr(NumObjCStringLiterals++);
2639
Steve Naroffba92b2e2008-03-27 22:29:16 +00002640 Preamble += "static __NSConstantStringImpl " + S;
2641 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2642 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002643 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002644 std::string prettyBufS;
2645 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00002646 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2647 PrintingPolicy(LangOpts));
Steve Naroffba92b2e2008-03-27 22:29:16 +00002648 Preamble += prettyBuf.str();
2649 Preamble += ",";
Steve Narofffd5b76f2009-12-06 01:48:44 +00002650 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002651
2652 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Benjamin Kramerd999b372010-02-14 14:14:16 +00002653 &Context->Idents.get(S), strType, 0,
John McCalld931b082010-08-26 03:08:43 +00002654 SC_Static, SC_None);
Ted Kremenek8189cde2009-02-07 01:47:29 +00002655 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00002656 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002657 Context->getPointerType(DRE->getType()),
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002658 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002659 // cast to NSConstantString *
John McCall9d125032010-01-15 18:39:57 +00002660 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
John McCall2de56d12010-08-25 11:45:40 +00002661 CK_Unknown, Unop);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002662 ReplaceStmt(Exp, cast);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002663 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002664 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002665}
2666
Steve Naroff874e2322007-11-15 10:28:18 +00002667// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002668QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002669 if (!SuperStructDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002670 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002671 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002672 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002673 QualType FieldTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00002674
Steve Naroff874e2322007-11-15 10:28:18 +00002675 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002676 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002677 // struct objc_class *super;
Mike Stump1eb44332009-09-09 15:08:12 +00002678 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor44b43212008-12-11 16:49:14 +00002679
Steve Naroff874e2322007-11-15 10:28:18 +00002680 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002681 for (unsigned i = 0; i < 2; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002682 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2683 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002684 FieldTypes[i], 0,
2685 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002686 /*Mutable=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002687 }
Mike Stump1eb44332009-09-09 15:08:12 +00002688
Douglas Gregor838db382010-02-11 01:19:42 +00002689 SuperStructDecl->completeDefinition();
Steve Naroff874e2322007-11-15 10:28:18 +00002690 }
2691 return Context->getTagDeclType(SuperStructDecl);
2692}
2693
Steve Naroffb29b4272008-04-14 22:03:09 +00002694QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002695 if (!ConstantStringDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002696 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002697 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002698 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002699 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002700
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002701 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002702 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002703 // int flags;
Mike Stump1eb44332009-09-09 15:08:12 +00002704 FieldTypes[1] = Context->IntTy;
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002705 // char *str;
Mike Stump1eb44332009-09-09 15:08:12 +00002706 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002707 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002708 FieldTypes[3] = Context->LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002709
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002710 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002711 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002712 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2713 ConstantStringDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00002714 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002715 FieldTypes[i], 0,
Douglas Gregor44b43212008-12-11 16:49:14 +00002716 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002717 /*Mutable=*/true));
Douglas Gregor44b43212008-12-11 16:49:14 +00002718 }
2719
Douglas Gregor838db382010-02-11 01:19:42 +00002720 ConstantStringDecl->completeDefinition();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002721 }
2722 return Context->getTagDeclType(ConstantStringDecl);
2723}
2724
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002725Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2726 SourceLocation StartLoc,
2727 SourceLocation EndLoc) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002728 if (!SelGetUidFunctionDecl)
2729 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002730 if (!MsgSendFunctionDecl)
2731 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002732 if (!MsgSendSuperFunctionDecl)
2733 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002734 if (!MsgSendStretFunctionDecl)
2735 SynthMsgSendStretFunctionDecl();
2736 if (!MsgSendSuperStretFunctionDecl)
2737 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002738 if (!MsgSendFpretFunctionDecl)
2739 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002740 if (!GetClassFunctionDecl)
2741 SynthGetClassFunctionDecl();
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002742 if (!GetSuperClassFunctionDecl)
2743 SynthGetSuperClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002744 if (!GetMetaClassFunctionDecl)
2745 SynthGetMetaClassFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002746
Steve Naroff874e2322007-11-15 10:28:18 +00002747 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002748 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2749 // May need to use objc_msgSend_stret() as well.
2750 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroff621edce2009-04-29 16:37:50 +00002751 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2752 QualType resultType = mDecl->getResultType();
Douglas Gregorfb87b892010-04-26 21:31:17 +00002753 if (resultType->isRecordType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002754 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002755 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002756 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002757 }
Mike Stump1eb44332009-09-09 15:08:12 +00002758
Steve Naroff934f2762007-10-24 22:48:43 +00002759 // Synthesize a call to objc_msgSend().
2760 llvm::SmallVector<Expr*, 8> MsgExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002761 switch (Exp->getReceiverKind()) {
2762 case ObjCMessageExpr::SuperClass: {
2763 MsgSendFlavor = MsgSendSuperFunctionDecl;
2764 if (MsgSendStretFlavor)
2765 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2766 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump1eb44332009-09-09 15:08:12 +00002767
Douglas Gregor04badcf2010-04-21 00:45:42 +00002768 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00002769
Douglas Gregor04badcf2010-04-21 00:45:42 +00002770 llvm::SmallVector<Expr*, 4> InitExprs;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002771
Douglas Gregor04badcf2010-04-21 00:45:42 +00002772 // set the receiver to self, the first argument to all methods.
2773 InitExprs.push_back(
2774 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCall2de56d12010-08-25 11:45:40 +00002775 CK_Unknown,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002776 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
2777 Context->getObjCIdType(),
2778 SourceLocation()))
2779 ); // set the 'receiver'.
Mike Stump1eb44332009-09-09 15:08:12 +00002780
Douglas Gregor04badcf2010-04-21 00:45:42 +00002781 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2782 llvm::SmallVector<Expr*, 8> ClsExprs;
2783 QualType argType = Context->getPointerType(Context->CharTy);
2784 ClsExprs.push_back(StringLiteral::Create(*Context,
2785 ClassDecl->getIdentifier()->getNameStart(),
2786 ClassDecl->getIdentifier()->getLength(),
2787 false, argType, SourceLocation()));
2788 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2789 &ClsExprs[0],
2790 ClsExprs.size(),
2791 StartLoc,
2792 EndLoc);
2793 // (Class)objc_getClass("CurrentClass")
2794 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2795 Context->getObjCClassType(),
John McCall2de56d12010-08-25 11:45:40 +00002796 CK_Unknown, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002797 ClsExprs.clear();
2798 ClsExprs.push_back(ArgExpr);
2799 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2800 &ClsExprs[0], ClsExprs.size(),
2801 StartLoc, EndLoc);
2802
2803 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2804 // To turn off a warning, type-cast to 'id'
2805 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2806 NoTypeInfoCStyleCastExpr(Context,
2807 Context->getObjCIdType(),
John McCall2de56d12010-08-25 11:45:40 +00002808 CK_Unknown, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002809 // struct objc_super
2810 QualType superType = getSuperStructType();
2811 Expr *SuperRep;
Steve Naroff621edce2009-04-29 16:37:50 +00002812
Douglas Gregor04badcf2010-04-21 00:45:42 +00002813 if (LangOpts.Microsoft) {
2814 SynthSuperContructorFunctionDecl();
2815 // Simulate a contructor call...
2816 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
2817 superType, SourceLocation());
2818 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2819 InitExprs.size(),
2820 superType, SourceLocation());
2821 // The code for super is a little tricky to prevent collision with
2822 // the structure definition in the header. The rewriter has it's own
2823 // internal definition (__rw_objc_super) that is uses. This is why
2824 // we need the cast below. For example:
2825 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2826 //
John McCall2de56d12010-08-25 11:45:40 +00002827 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002828 Context->getPointerType(SuperRep->getType()),
2829 SourceLocation());
2830 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2831 Context->getPointerType(superType),
John McCall2de56d12010-08-25 11:45:40 +00002832 CK_Unknown, SuperRep);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002833 } else {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002834 // (struct objc_super) { <exprs from above> }
2835 InitListExpr *ILE =
2836 new (Context) InitListExpr(*Context, SourceLocation(),
2837 &InitExprs[0], InitExprs.size(),
2838 SourceLocation());
2839 TypeSourceInfo *superTInfo
2840 = Context->getTrivialTypeSourceInfo(superType);
2841 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2842 superType, ILE, false);
2843 // struct objc_super *
John McCall2de56d12010-08-25 11:45:40 +00002844 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002845 Context->getPointerType(SuperRep->getType()),
2846 SourceLocation());
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002847 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002848 MsgExprs.push_back(SuperRep);
2849 break;
Steve Naroff6568d4d2007-11-14 23:54:14 +00002850 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002851
2852 case ObjCMessageExpr::Class: {
2853 llvm::SmallVector<Expr*, 8> ClsExprs;
2854 QualType argType = Context->getPointerType(Context->CharTy);
2855 ObjCInterfaceDecl *Class
John McCall506b57e2010-05-17 21:00:27 +00002856 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00002857 IdentifierInfo *clsName = Class->getIdentifier();
2858 ClsExprs.push_back(StringLiteral::Create(*Context,
2859 clsName->getNameStart(),
2860 clsName->getLength(),
2861 false, argType,
2862 SourceLocation()));
2863 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2864 &ClsExprs[0],
2865 ClsExprs.size(),
2866 StartLoc, EndLoc);
2867 MsgExprs.push_back(Cls);
2868 break;
2869 }
2870
2871 case ObjCMessageExpr::SuperInstance:{
2872 MsgSendFlavor = MsgSendSuperFunctionDecl;
2873 if (MsgSendStretFlavor)
2874 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2875 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2876 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2877 llvm::SmallVector<Expr*, 4> InitExprs;
2878
2879 InitExprs.push_back(
2880 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCall2de56d12010-08-25 11:45:40 +00002881 CK_Unknown,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002882 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
2883 Context->getObjCIdType(),
2884 SourceLocation()))
2885 ); // set the 'receiver'.
2886
2887 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2888 llvm::SmallVector<Expr*, 8> ClsExprs;
2889 QualType argType = Context->getPointerType(Context->CharTy);
2890 ClsExprs.push_back(StringLiteral::Create(*Context,
2891 ClassDecl->getIdentifier()->getNameStart(),
2892 ClassDecl->getIdentifier()->getLength(),
2893 false, argType, SourceLocation()));
2894 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2895 &ClsExprs[0],
2896 ClsExprs.size(),
2897 StartLoc, EndLoc);
2898 // (Class)objc_getClass("CurrentClass")
2899 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2900 Context->getObjCClassType(),
John McCall2de56d12010-08-25 11:45:40 +00002901 CK_Unknown, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002902 ClsExprs.clear();
2903 ClsExprs.push_back(ArgExpr);
2904 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2905 &ClsExprs[0], ClsExprs.size(),
2906 StartLoc, EndLoc);
2907
2908 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2909 // To turn off a warning, type-cast to 'id'
2910 InitExprs.push_back(
2911 // set 'super class', using class_getSuperclass().
2912 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCall2de56d12010-08-25 11:45:40 +00002913 CK_Unknown, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002914 // struct objc_super
2915 QualType superType = getSuperStructType();
2916 Expr *SuperRep;
2917
2918 if (LangOpts.Microsoft) {
2919 SynthSuperContructorFunctionDecl();
2920 // Simulate a contructor call...
2921 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
2922 superType, SourceLocation());
2923 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2924 InitExprs.size(),
2925 superType, SourceLocation());
2926 // The code for super is a little tricky to prevent collision with
2927 // the structure definition in the header. The rewriter has it's own
2928 // internal definition (__rw_objc_super) that is uses. This is why
2929 // we need the cast below. For example:
2930 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2931 //
John McCall2de56d12010-08-25 11:45:40 +00002932 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002933 Context->getPointerType(SuperRep->getType()),
2934 SourceLocation());
2935 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2936 Context->getPointerType(superType),
John McCall2de56d12010-08-25 11:45:40 +00002937 CK_Unknown, SuperRep);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002938 } else {
2939 // (struct objc_super) { <exprs from above> }
2940 InitListExpr *ILE =
2941 new (Context) InitListExpr(*Context, SourceLocation(),
2942 &InitExprs[0], InitExprs.size(),
2943 SourceLocation());
2944 TypeSourceInfo *superTInfo
2945 = Context->getTrivialTypeSourceInfo(superType);
2946 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2947 superType, ILE, false);
2948 }
2949 MsgExprs.push_back(SuperRep);
2950 break;
2951 }
2952
2953 case ObjCMessageExpr::Instance: {
2954 // Remove all type-casts because it may contain objc-style types; e.g.
2955 // Foo<Proto> *.
2956 Expr *recExpr = Exp->getInstanceReceiver();
2957 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2958 recExpr = CE->getSubExpr();
2959 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCall2de56d12010-08-25 11:45:40 +00002960 CK_Unknown, recExpr);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002961 MsgExprs.push_back(recExpr);
2962 break;
2963 }
2964 }
2965
Steve Naroffbeaf2992007-11-03 11:27:19 +00002966 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002967 llvm::SmallVector<Expr*, 8> SelExprs;
2968 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002969 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002970 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00002971 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00002972 false, argType, SourceLocation()));
Steve Naroff934f2762007-10-24 22:48:43 +00002973 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002974 &SelExprs[0], SelExprs.size(),
2975 StartLoc,
2976 EndLoc);
Steve Naroff934f2762007-10-24 22:48:43 +00002977 MsgExprs.push_back(SelExp);
Mike Stump1eb44332009-09-09 15:08:12 +00002978
Steve Naroff934f2762007-10-24 22:48:43 +00002979 // Now push any user supplied arguments.
2980 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002981 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002982 // Make all implicit casts explicit...ICE comes in handy:-)
2983 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2984 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregor49badde2008-10-27 19:41:14 +00002985 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002986 ? Context->getObjCIdType()
Douglas Gregor49badde2008-10-27 19:41:14 +00002987 : ICE->getType();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00002988 // Make sure we convert "type (^)(...)" to "type (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00002989 (void)convertBlockPointerToFunctionPointer(type);
John McCall2de56d12010-08-25 11:45:40 +00002990 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK_Unknown,
John McCall9d125032010-01-15 18:39:57 +00002991 userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002992 }
2993 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002994 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002995 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002996 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002997 userExpr = CE->getSubExpr();
John McCall9d125032010-01-15 18:39:57 +00002998 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCall2de56d12010-08-25 11:45:40 +00002999 CK_Unknown, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00003000 }
Mike Stump1eb44332009-09-09 15:08:12 +00003001 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00003002 MsgExprs.push_back(userExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00003003 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3004 // out the argument in the original expression (since we aren't deleting
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003005 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00003006 //Exp->setArg(i, 0);
Steve Naroff934f2762007-10-24 22:48:43 +00003007 }
Steve Naroffab972d32007-11-04 22:37:50 +00003008 // Generate the funky cast.
3009 CastExpr *cast;
3010 llvm::SmallVector<QualType, 8> ArgTypes;
3011 QualType returnType;
Mike Stump1eb44332009-09-09 15:08:12 +00003012
Steve Naroffab972d32007-11-04 22:37:50 +00003013 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00003014 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3015 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3016 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003017 ArgTypes.push_back(Context->getObjCIdType());
3018 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner89951a82009-02-20 18:43:26 +00003019 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00003020 // Push any user argument types.
Chris Lattner89951a82009-02-20 18:43:26 +00003021 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3022 E = OMD->param_end(); PI != E; ++PI) {
3023 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump1eb44332009-09-09 15:08:12 +00003024 ? Context->getObjCIdType()
Chris Lattner89951a82009-02-20 18:43:26 +00003025 : (*PI)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00003026 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003027 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroff352336b2007-11-05 14:36:37 +00003028 ArgTypes.push_back(t);
3029 }
Chris Lattner89951a82009-02-20 18:43:26 +00003030 returnType = OMD->getResultType()->isObjCQualifiedIdType()
3031 ? Context->getObjCIdType() : OMD->getResultType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003032 (void)convertBlockPointerToFunctionPointer(returnType);
Steve Naroffab972d32007-11-04 22:37:50 +00003033 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003034 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00003035 }
3036 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00003037 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003038
Steve Naroffab972d32007-11-04 22:37:50 +00003039 // Create a reference to the objc_msgSend() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003040 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003041 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00003042
Mike Stump1eb44332009-09-09 15:08:12 +00003043 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Naroffab972d32007-11-04 22:37:50 +00003044 // If we don't do this cast, we get the following bizarre warning/note:
3045 // xx.m:13: warning: function called through a non-compatible type
3046 // xx.m:13: note: if this code is reached, the program will abort
John McCall9d125032010-01-15 18:39:57 +00003047 cast = NoTypeInfoCStyleCastExpr(Context,
3048 Context->getPointerType(Context->VoidTy),
John McCall2de56d12010-08-25 11:45:40 +00003049 CK_Unknown, DRE);
Mike Stump1eb44332009-09-09 15:08:12 +00003050
Steve Naroffab972d32007-11-04 22:37:50 +00003051 // Now do the "normal" pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00003052 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00003053 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00003054 // If we don't have a method decl, force a variadic cast.
Douglas Gregorce056bc2010-02-21 22:15:06 +00003055 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00003056 false, false, 0, 0,
3057 FunctionType::ExtInfo());
Steve Naroffab972d32007-11-04 22:37:50 +00003058 castType = Context->getPointerType(castType);
John McCall2de56d12010-08-25 11:45:40 +00003059 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_Unknown,
John McCall9d125032010-01-15 18:39:57 +00003060 cast);
Steve Naroffab972d32007-11-04 22:37:50 +00003061
3062 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003063 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003064
John McCall183700f2009-09-21 23:43:11 +00003065 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003066 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003067 MsgExprs.size(),
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003068 FT->getResultType(), EndLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003069 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003070 if (MsgSendStretFlavor) {
3071 // We have the method which returns a struct/union. Must also generate
3072 // call to objc_msgSend_stret and hang both varieties on a conditional
3073 // expression which dictate which one to envoke depending on size of
3074 // method's return type.
Mike Stump1eb44332009-09-09 15:08:12 +00003075
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003076 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003077 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003078 SourceLocation());
3079 // Need to cast objc_msgSend_stret to "void *" (see above comment).
John McCall9d125032010-01-15 18:39:57 +00003080 cast = NoTypeInfoCStyleCastExpr(Context,
3081 Context->getPointerType(Context->VoidTy),
John McCall2de56d12010-08-25 11:45:40 +00003082 CK_Unknown, STDRE);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003083 // Now do the "normal" pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00003084 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00003085 &ArgTypes[0], ArgTypes.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00003086 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00003087 false, false, 0, 0,
3088 FunctionType::ExtInfo());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003089 castType = Context->getPointerType(castType);
John McCall2de56d12010-08-25 11:45:40 +00003090 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_Unknown,
John McCall9d125032010-01-15 18:39:57 +00003091 cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003092
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003093 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003094 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003095
John McCall183700f2009-09-21 23:43:11 +00003096 FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003097 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003098 MsgExprs.size(),
Ted Kremenek668bf912009-02-09 20:51:47 +00003099 FT->getResultType(), SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00003100
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003101 // Build sizeof(returnType)
Mike Stump1eb44332009-09-09 15:08:12 +00003102 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
John McCalla93c9342009-12-07 02:54:59 +00003103 Context->getTrivialTypeSourceInfo(returnType),
Sebastian Redl05189992008-11-11 17:56:53 +00003104 Context->getSizeType(),
3105 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003106 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3107 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3108 // For X86 it is more complicated and some kind of target specific routine
3109 // is needed to decide what to do.
Mike Stump1eb44332009-09-09 15:08:12 +00003110 unsigned IntSize =
Chris Lattner98be4942008-03-05 18:54:05 +00003111 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00003112 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3113 llvm::APInt(IntSize, 8),
3114 Context->IntTy,
3115 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00003116 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
John McCall2de56d12010-08-25 11:45:40 +00003117 BO_LE,
Mike Stump1eb44332009-09-09 15:08:12 +00003118 Context->IntTy,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003119 SourceLocation());
3120 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump1eb44332009-09-09 15:08:12 +00003121 ConditionalOperator *CondExpr =
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00003122 new (Context) ConditionalOperator(lessThanExpr,
3123 SourceLocation(), CE,
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00003124 SourceLocation(), STCE, (Expr*)0,
3125 returnType);
3126 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3127 CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003128 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003129 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003130 return ReplacingStmt;
3131}
3132
Steve Naroffb29b4272008-04-14 22:03:09 +00003133Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003134 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3135 Exp->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00003136
Steve Naroff934f2762007-10-24 22:48:43 +00003137 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00003138 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00003139
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003140 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003141 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00003142}
3143
Steve Naroff621edce2009-04-29 16:37:50 +00003144// typedef struct objc_object Protocol;
3145QualType RewriteObjC::getProtocolType() {
3146 if (!ProtocolTypeDecl) {
John McCalla93c9342009-12-07 02:54:59 +00003147 TypeSourceInfo *TInfo
3148 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroff621edce2009-04-29 16:37:50 +00003149 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00003150 SourceLocation(),
Steve Naroff621edce2009-04-29 16:37:50 +00003151 &Context->Idents.get("Protocol"),
John McCalla93c9342009-12-07 02:54:59 +00003152 TInfo);
Steve Naroff621edce2009-04-29 16:37:50 +00003153 }
3154 return Context->getTypeDeclType(ProtocolTypeDecl);
3155}
3156
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003157/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroff621edce2009-04-29 16:37:50 +00003158/// a synthesized/forward data reference (to the protocol's metadata).
3159/// The forward references (and metadata) are generated in
3160/// RewriteObjC::HandleTranslationUnit().
Steve Naroffb29b4272008-04-14 22:03:09 +00003161Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroff621edce2009-04-29 16:37:50 +00003162 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3163 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00003164 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00003165 ID, getProtocolType(), 0,
John McCalld931b082010-08-26 03:08:43 +00003166 SC_Extern, SC_None);
Steve Naroff621edce2009-04-29 16:37:50 +00003167 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00003168 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
Steve Naroff621edce2009-04-29 16:37:50 +00003169 Context->getPointerType(DRE->getType()),
3170 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00003171 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
John McCall2de56d12010-08-25 11:45:40 +00003172 CK_Unknown,
John McCall9d125032010-01-15 18:39:57 +00003173 DerefExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00003174 ReplaceStmt(Exp, castExpr);
3175 ProtocolExprDecls.insert(Exp->getProtocol());
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003176 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00003177 return castExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00003178
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003179}
3180
Mike Stump1eb44332009-09-09 15:08:12 +00003181bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffbaf58c32008-05-31 14:15:04 +00003182 const char *endBuf) {
3183 while (startBuf < endBuf) {
3184 if (*startBuf == '#') {
3185 // Skip whitespace.
3186 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3187 ;
3188 if (!strncmp(startBuf, "if", strlen("if")) ||
3189 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3190 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3191 !strncmp(startBuf, "define", strlen("define")) ||
3192 !strncmp(startBuf, "undef", strlen("undef")) ||
3193 !strncmp(startBuf, "else", strlen("else")) ||
3194 !strncmp(startBuf, "elif", strlen("elif")) ||
3195 !strncmp(startBuf, "endif", strlen("endif")) ||
3196 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3197 !strncmp(startBuf, "include", strlen("include")) ||
3198 !strncmp(startBuf, "import", strlen("import")) ||
3199 !strncmp(startBuf, "include_next", strlen("include_next")))
3200 return true;
3201 }
3202 startBuf++;
3203 }
3204 return false;
3205}
3206
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003207/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003208/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00003209void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003210 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003211 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Daniel Dunbar4087f272010-08-17 22:39:59 +00003212 assert(CDecl->getName() != "" &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003213 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003214 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003215 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003216 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003217 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003218 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00003219 SourceLocation LocStart = CDecl->getLocStart();
3220 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00003221
Steve Narofffea763e82007-11-14 19:25:57 +00003222 const char *startBuf = SM->getCharacterData(LocStart);
3223 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump1eb44332009-09-09 15:08:12 +00003224
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003225 // If no ivars and no root or if its root, directly or indirectly,
3226 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003227 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
3228 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner2c78b872009-04-14 23:22:57 +00003229 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003230 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003231 return;
3232 }
Mike Stump1eb44332009-09-09 15:08:12 +00003233
3234 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003235 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003236 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003237 Result += CDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00003238 if (LangOpts.Microsoft)
3239 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00003240
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003241 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00003242 const char *cursor = strchr(startBuf, '{');
Mike Stump1eb44332009-09-09 15:08:12 +00003243 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003244 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00003245 // If the buffer contains preprocessor directives, we do more fine-grained
3246 // rewrites. This is intended to fix code that looks like (which occurs in
3247 // NSURL.h, for example):
3248 //
3249 // #ifdef XYZ
3250 // @interface Foo : NSObject
3251 // #else
3252 // @interface FooBar : NSObject
3253 // #endif
3254 // {
3255 // int i;
3256 // }
3257 // @end
3258 //
3259 // This clause is segregated to avoid breaking the common case.
3260 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003261 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffbaf58c32008-05-31 14:15:04 +00003262 CDecl->getClassLoc();
3263 const char *endHeader = SM->getCharacterData(L);
Chris Lattner2c78b872009-04-14 23:22:57 +00003264 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003265
Chris Lattnercafeb352009-02-20 18:18:36 +00003266 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00003267 // advance to the end of the referenced protocols.
3268 while (endHeader < cursor && *endHeader != '>') endHeader++;
3269 endHeader++;
3270 }
3271 // rewrite the original header
Benjamin Kramerd999b372010-02-14 14:14:16 +00003272 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003273 } else {
3274 // rewrite the original header *without* disturbing the '{'
Benjamin Kramerd999b372010-02-14 14:14:16 +00003275 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003276 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003277 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00003278 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003279 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003280 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003281 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003282 Result += "_IVARS;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003283
Steve Narofffea763e82007-11-14 19:25:57 +00003284 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00003285 SourceLocation OnePastCurly =
3286 LocStart.getFileLocWithOffset(cursor-startBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003287 InsertText(OnePastCurly, Result);
Steve Narofffea763e82007-11-14 19:25:57 +00003288 }
3289 cursor++; // past '{'
Mike Stump1eb44332009-09-09 15:08:12 +00003290
Steve Narofffea763e82007-11-14 19:25:57 +00003291 // Now comment out any visibility specifiers.
3292 while (cursor < endBuf) {
3293 if (*cursor == '@') {
3294 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00003295 // Skip whitespace.
3296 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3297 /*scan*/;
3298
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003299 // FIXME: presence of @public, etc. inside comment results in
3300 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00003301 if (!strncmp(cursor, "public", strlen("public")) ||
3302 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00003303 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00003304 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramerd999b372010-02-14 14:14:16 +00003305 InsertText(atLoc, "// ");
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003306 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00003307 // FIXME: If there are cases where '<' is used in ivar declaration part
3308 // of user code, then scan the ivar list and use needToScanForQualifiers
3309 // for type checking.
3310 else if (*cursor == '<') {
3311 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003312 InsertText(atLoc, "/* ");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003313 cursor = strchr(cursor, '>');
3314 cursor++;
3315 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003316 InsertText(atLoc, " */");
Steve Naroffced80a82008-10-30 12:09:33 +00003317 } else if (*cursor == '^') { // rewrite block specifier.
3318 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003319 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003320 }
Steve Narofffea763e82007-11-14 19:25:57 +00003321 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003322 }
Steve Narofffea763e82007-11-14 19:25:57 +00003323 // Don't forget to add a ';'!!
Benjamin Kramerd999b372010-02-14 14:14:16 +00003324 InsertText(LocEnd.getFileLocWithOffset(1), ";");
Steve Narofffea763e82007-11-14 19:25:57 +00003325 } else { // we don't have any instance variables - insert super struct.
Chris Lattner2c78b872009-04-14 23:22:57 +00003326 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Narofffea763e82007-11-14 19:25:57 +00003327 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003328 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003329 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003330 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003331 Result += "_IVARS;\n};\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00003332 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003333 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003334 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003335 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00003336 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003337}
3338
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003339// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003340/// class methods.
Douglas Gregor653f1b12009-04-23 01:02:12 +00003341template<typename MethodIterator>
3342void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
3343 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00003344 bool IsInstanceMethod,
Daniel Dunbar4087f272010-08-17 22:39:59 +00003345 llvm::StringRef prefix,
3346 llvm::StringRef ClassName,
Chris Lattner158ecb92007-10-25 17:07:24 +00003347 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003348 if (MethodBegin == MethodEnd) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003349
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003350 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003351 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003352 SEL _cmd;
3353 char *method_types;
3354 void *_imp;
3355 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003356 */
Chris Lattner158ecb92007-10-25 17:07:24 +00003357 Result += "\nstruct _objc_method {\n";
3358 Result += "\tSEL _cmd;\n";
3359 Result += "\tchar *method_types;\n";
3360 Result += "\tvoid *_imp;\n";
3361 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003362
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003363 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00003364 }
Mike Stump1eb44332009-09-09 15:08:12 +00003365
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003366 // Build _objc_method_list for class's methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003367
Steve Naroff946a6932008-03-11 00:12:29 +00003368 /* struct {
3369 struct _objc_method_list *next_method;
3370 int method_count;
3371 struct _objc_method method_list[];
3372 }
3373 */
Douglas Gregor653f1b12009-04-23 01:02:12 +00003374 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroff946a6932008-03-11 00:12:29 +00003375 Result += "\nstatic struct {\n";
3376 Result += "\tstruct _objc_method_list *next_method;\n";
3377 Result += "\tint method_count;\n";
3378 Result += "\tstruct _objc_method method_list[";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003379 Result += utostr(NumMethods);
Steve Naroff946a6932008-03-11 00:12:29 +00003380 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003381 Result += prefix;
3382 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
3383 Result += "_METHODS_";
3384 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003385 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003386 Result += IsInstanceMethod ? "inst" : "cls";
3387 Result += "_meth\")))= ";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003388 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003389
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003390 Result += "\t,{{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003391 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003392 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003393 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003394 Result += "\", \"";
3395 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003396 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003397 Result += MethodInternalNames[*MethodBegin];
3398 Result += "}\n";
3399 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3400 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003401 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003402 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003403 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003404 Result += "\", \"";
3405 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003406 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003407 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00003408 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003409 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003410 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003411}
3412
Steve Naroff621edce2009-04-29 16:37:50 +00003413/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00003414void RewriteObjC::
Daniel Dunbar4087f272010-08-17 22:39:59 +00003415RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, llvm::StringRef prefix,
3416 llvm::StringRef ClassName, std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003417 static bool objc_protocol_methods = false;
Steve Naroff621edce2009-04-29 16:37:50 +00003418
3419 // Output struct protocol_methods holder of method selector and type.
3420 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3421 /* struct protocol_methods {
3422 SEL _cmd;
3423 char *method_types;
3424 }
3425 */
3426 Result += "\nstruct _protocol_methods {\n";
3427 Result += "\tstruct objc_selector *_cmd;\n";
3428 Result += "\tchar *method_types;\n";
3429 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003430
Steve Naroff621edce2009-04-29 16:37:50 +00003431 objc_protocol_methods = true;
3432 }
3433 // Do not synthesize the protocol more than once.
3434 if (ObjCSynthesizedProtocols.count(PDecl))
3435 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003436
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003437 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3438 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3439 PDecl->instmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003440 /* struct _objc_protocol_method_list {
3441 int protocol_method_count;
3442 struct protocol_methods protocols[];
3443 }
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003444 */
Steve Naroff621edce2009-04-29 16:37:50 +00003445 Result += "\nstatic struct {\n";
3446 Result += "\tint protocol_method_count;\n";
3447 Result += "\tstruct _protocol_methods protocol_methods[";
3448 Result += utostr(NumMethods);
3449 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3450 Result += PDecl->getNameAsString();
3451 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3452 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003453
Steve Naroff621edce2009-04-29 16:37:50 +00003454 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003455 for (ObjCProtocolDecl::instmeth_iterator
3456 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003457 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003458 if (I == PDecl->instmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003459 Result += "\t ,{{(struct objc_selector *)\"";
3460 else
3461 Result += "\t ,{(struct objc_selector *)\"";
Daniel Dunbar4087f272010-08-17 22:39:59 +00003462 Result += (*I)->getSelector().getAsString();
Steve Naroff621edce2009-04-29 16:37:50 +00003463 std::string MethodTypeString;
3464 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3465 Result += "\", \"";
3466 Result += MethodTypeString;
3467 Result += "\"}\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003468 }
Steve Naroff621edce2009-04-29 16:37:50 +00003469 Result += "\t }\n};\n";
3470 }
Mike Stump1eb44332009-09-09 15:08:12 +00003471
Steve Naroff621edce2009-04-29 16:37:50 +00003472 // Output class methods declared in this protocol.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003473 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3474 PDecl->classmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003475 if (NumMethods > 0) {
3476 /* struct _objc_protocol_method_list {
3477 int protocol_method_count;
3478 struct protocol_methods protocols[];
3479 }
3480 */
3481 Result += "\nstatic struct {\n";
3482 Result += "\tint protocol_method_count;\n";
3483 Result += "\tstruct _protocol_methods protocol_methods[";
3484 Result += utostr(NumMethods);
3485 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3486 Result += PDecl->getNameAsString();
3487 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3488 "{\n\t";
3489 Result += utostr(NumMethods);
3490 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003491
Steve Naroff621edce2009-04-29 16:37:50 +00003492 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003493 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003494 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003495 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003496 if (I == PDecl->classmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003497 Result += "\t ,{{(struct objc_selector *)\"";
3498 else
3499 Result += "\t ,{(struct objc_selector *)\"";
Daniel Dunbar4087f272010-08-17 22:39:59 +00003500 Result += (*I)->getSelector().getAsString();
Steve Naroff621edce2009-04-29 16:37:50 +00003501 std::string MethodTypeString;
3502 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3503 Result += "\", \"";
3504 Result += MethodTypeString;
3505 Result += "\"}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003506 }
Steve Naroff621edce2009-04-29 16:37:50 +00003507 Result += "\t }\n};\n";
3508 }
3509
3510 // Output:
3511 /* struct _objc_protocol {
3512 // Objective-C 1.0 extensions
3513 struct _objc_protocol_extension *isa;
3514 char *protocol_name;
3515 struct _objc_protocol **protocol_list;
3516 struct _objc_protocol_method_list *instance_methods;
3517 struct _objc_protocol_method_list *class_methods;
Mike Stump1eb44332009-09-09 15:08:12 +00003518 };
Steve Naroff621edce2009-04-29 16:37:50 +00003519 */
3520 static bool objc_protocol = false;
3521 if (!objc_protocol) {
3522 Result += "\nstruct _objc_protocol {\n";
3523 Result += "\tstruct _objc_protocol_extension *isa;\n";
3524 Result += "\tchar *protocol_name;\n";
3525 Result += "\tstruct _objc_protocol **protocol_list;\n";
3526 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3527 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003528 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003529
Steve Naroff621edce2009-04-29 16:37:50 +00003530 objc_protocol = true;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003531 }
Mike Stump1eb44332009-09-09 15:08:12 +00003532
Steve Naroff621edce2009-04-29 16:37:50 +00003533 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3534 Result += PDecl->getNameAsString();
3535 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3536 "{\n\t0, \"";
3537 Result += PDecl->getNameAsString();
3538 Result += "\", 0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003539 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003540 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3541 Result += PDecl->getNameAsString();
3542 Result += ", ";
3543 }
3544 else
3545 Result += "0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003546 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003547 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3548 Result += PDecl->getNameAsString();
3549 Result += "\n";
3550 }
3551 else
3552 Result += "0\n";
3553 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003554
Steve Naroff621edce2009-04-29 16:37:50 +00003555 // Mark this protocol as having been generated.
3556 if (!ObjCSynthesizedProtocols.insert(PDecl))
3557 assert(false && "protocol already synthesized");
3558
3559}
3560
3561void RewriteObjC::
3562RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
Daniel Dunbar4087f272010-08-17 22:39:59 +00003563 llvm::StringRef prefix, llvm::StringRef ClassName,
Steve Naroff621edce2009-04-29 16:37:50 +00003564 std::string &Result) {
3565 if (Protocols.empty()) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003566
Steve Naroff621edce2009-04-29 16:37:50 +00003567 for (unsigned i = 0; i != Protocols.size(); i++)
3568 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3569
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003570 // Output the top lovel protocol meta-data for the class.
3571 /* struct _objc_protocol_list {
3572 struct _objc_protocol_list *next;
3573 int protocol_count;
3574 struct _objc_protocol *class_protocols[];
3575 }
3576 */
3577 Result += "\nstatic struct {\n";
3578 Result += "\tstruct _objc_protocol_list *next;\n";
3579 Result += "\tint protocol_count;\n";
3580 Result += "\tstruct _objc_protocol *class_protocols[";
3581 Result += utostr(Protocols.size());
3582 Result += "];\n} _OBJC_";
3583 Result += prefix;
3584 Result += "_PROTOCOLS_";
3585 Result += ClassName;
3586 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3587 "{\n\t0, ";
3588 Result += utostr(Protocols.size());
3589 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003590
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003591 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003592 Result += Protocols[0]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003593 Result += " \n";
Mike Stump1eb44332009-09-09 15:08:12 +00003594
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003595 for (unsigned i = 1; i != Protocols.size(); i++) {
3596 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003597 Result += Protocols[i]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003598 Result += "\n";
3599 }
3600 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003601}
3602
Steve Naroff621edce2009-04-29 16:37:50 +00003603
Mike Stump1eb44332009-09-09 15:08:12 +00003604/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003605/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00003606void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003607 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003608 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003609 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003610 ObjCCategoryDecl *CDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00003611 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003612 CDecl = CDecl->getNextClassCategory())
3613 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3614 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003615
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003616 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00003617 FullCategoryName += '_';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003618 FullCategoryName += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003619
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003620 // Build _objc_method_list for class's instance methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003621 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003622 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003623
3624 // If any of our property implementations have associated getters or
3625 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003626 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3627 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003628 Prop != PropEnd; ++Prop) {
3629 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3630 continue;
3631 if (!(*Prop)->getPropertyIvarDecl())
3632 continue;
3633 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3634 if (!PD)
3635 continue;
3636 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3637 InstanceMethods.push_back(Getter);
3638 if (PD->isReadOnly())
3639 continue;
3640 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3641 InstanceMethods.push_back(Setter);
3642 }
3643 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003644 true, "CATEGORY_", FullCategoryName.c_str(),
3645 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003646
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003647 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003648 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003649 false, "CATEGORY_", FullCategoryName.c_str(),
3650 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003651
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003652 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00003653 // Null CDecl is case of a category implementation with no category interface
3654 if (CDecl)
Steve Naroff621edce2009-04-29 16:37:50 +00003655 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Daniel Dunbar4087f272010-08-17 22:39:59 +00003656 FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003657 /* struct _objc_category {
3658 char *category_name;
3659 char *class_name;
3660 struct _objc_method_list *instance_methods;
3661 struct _objc_method_list *class_methods;
3662 struct _objc_protocol_list *protocols;
3663 // Objective-C 1.0 extensions
3664 uint32_t size; // sizeof (struct _objc_category)
Mike Stump1eb44332009-09-09 15:08:12 +00003665 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003666 // @property decl.
Mike Stump1eb44332009-09-09 15:08:12 +00003667 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003668 */
Mike Stump1eb44332009-09-09 15:08:12 +00003669
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003670 static bool objc_category = false;
3671 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003672 Result += "\nstruct _objc_category {\n";
3673 Result += "\tchar *category_name;\n";
3674 Result += "\tchar *class_name;\n";
3675 Result += "\tstruct _objc_method_list *instance_methods;\n";
3676 Result += "\tstruct _objc_method_list *class_methods;\n";
3677 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003678 Result += "\tunsigned int size;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003679 Result += "\tstruct _objc_property_list *instance_properties;\n";
3680 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003681 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003682 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003683 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3684 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003685 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003686 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003687 Result += "\"\n\t, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003688 Result += ClassDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003689 Result += "\"\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003690
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003691 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003692 Result += "\t, (struct _objc_method_list *)"
3693 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3694 Result += FullCategoryName;
3695 Result += "\n";
3696 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003697 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003698 Result += "\t, 0\n";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003699 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003700 Result += "\t, (struct _objc_method_list *)"
3701 "&_OBJC_CATEGORY_CLASS_METHODS_";
3702 Result += FullCategoryName;
3703 Result += "\n";
3704 }
3705 else
3706 Result += "\t, 0\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003707
Chris Lattnercafeb352009-02-20 18:18:36 +00003708 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003709 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003710 Result += FullCategoryName;
3711 Result += "\n";
3712 }
3713 else
3714 Result += "\t, 0\n";
3715 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003716}
3717
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003718/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3719/// ivar offset.
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003720void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003721 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00003722 if (ivar->isBitField()) {
3723 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3724 // place all bitfields at offset 0.
3725 Result += "0";
3726 } else {
3727 Result += "__OFFSETOFIVAR__(struct ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003728 Result += ivar->getContainingInterface()->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003729 if (LangOpts.Microsoft)
3730 Result += "_IMPL";
3731 Result += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003732 Result += ivar->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003733 Result += ")";
3734 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003735}
3736
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003737//===----------------------------------------------------------------------===//
3738// Meta Data Emission
3739//===----------------------------------------------------------------------===//
3740
Steve Naroffb29b4272008-04-14 22:03:09 +00003741void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003742 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003743 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00003744
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003745 // Explictly declared @interface's are already synthesized.
Steve Naroff33feeb02009-04-20 20:09:33 +00003746 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003747 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003748 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003749 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003750 }
Mike Stump1eb44332009-09-09 15:08:12 +00003751
Chris Lattnerbe6df082007-12-12 07:56:42 +00003752 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003753 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump1eb44332009-09-09 15:08:12 +00003754 ? IDecl->ivar_size()
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003755 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003756 if (NumIvars > 0) {
3757 static bool objc_ivar = false;
3758 if (!objc_ivar) {
3759 /* struct _objc_ivar {
3760 char *ivar_name;
3761 char *ivar_type;
3762 int ivar_offset;
Mike Stump1eb44332009-09-09 15:08:12 +00003763 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003764 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003765 Result += "\nstruct _objc_ivar {\n";
3766 Result += "\tchar *ivar_name;\n";
3767 Result += "\tchar *ivar_type;\n";
3768 Result += "\tint ivar_offset;\n";
3769 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003770
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003771 objc_ivar = true;
3772 }
3773
Steve Naroff946a6932008-03-11 00:12:29 +00003774 /* struct {
3775 int ivar_count;
3776 struct _objc_ivar ivar_list[nIvars];
Mike Stump1eb44332009-09-09 15:08:12 +00003777 };
Steve Naroff946a6932008-03-11 00:12:29 +00003778 */
Mike Stump1eb44332009-09-09 15:08:12 +00003779 Result += "\nstatic struct {\n";
Steve Naroff946a6932008-03-11 00:12:29 +00003780 Result += "\tint ivar_count;\n";
3781 Result += "\tstruct _objc_ivar ivar_list[";
3782 Result += utostr(NumIvars);
3783 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003784 Result += IDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003785 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003786 "{\n\t";
3787 Result += utostr(NumIvars);
3788 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003789
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003790 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003791 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003792 if (!IDecl->ivar_empty()) {
Fariborz Jahanian11062e12010-02-19 00:31:17 +00003793 for (ObjCInterfaceDecl::ivar_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003794 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003795 IV != IVEnd; ++IV)
3796 IVars.push_back(*IV);
Fariborz Jahanian11062e12010-02-19 00:31:17 +00003797 IVI = IDecl->ivar_begin();
3798 IVE = IDecl->ivar_end();
Chris Lattnerbe6df082007-12-12 07:56:42 +00003799 } else {
3800 IVI = CDecl->ivar_begin();
3801 IVE = CDecl->ivar_end();
3802 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003803 Result += "\t,{{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003804 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003805 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003806 std::string TmpString, StrEncoding;
3807 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3808 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003809 Result += StrEncoding;
3810 Result += "\", ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003811 SynthesizeIvarOffsetComputation(*IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003812 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003813 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003814 Result += "\t ,{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003815 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003816 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003817 std::string TmpString, StrEncoding;
3818 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3819 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003820 Result += StrEncoding;
3821 Result += "\", ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003822 SynthesizeIvarOffsetComputation((*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003823 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003824 }
Mike Stump1eb44332009-09-09 15:08:12 +00003825
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003826 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003827 }
Mike Stump1eb44332009-09-09 15:08:12 +00003828
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003829 // Build _objc_method_list for class's instance methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003830 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003831 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003832
3833 // If any of our property implementations have associated getters or
3834 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003835 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3836 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003837 Prop != PropEnd; ++Prop) {
3838 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3839 continue;
3840 if (!(*Prop)->getPropertyIvarDecl())
3841 continue;
3842 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3843 if (!PD)
3844 continue;
3845 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanianec3683b2010-10-19 23:47:54 +00003846 if (!Getter->isDefined())
3847 InstanceMethods.push_back(Getter);
Douglas Gregor653f1b12009-04-23 01:02:12 +00003848 if (PD->isReadOnly())
3849 continue;
3850 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanianec3683b2010-10-19 23:47:54 +00003851 if (!Setter->isDefined())
3852 InstanceMethods.push_back(Setter);
Douglas Gregor653f1b12009-04-23 01:02:12 +00003853 }
3854 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003855 true, "", IDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003856
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003857 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003858 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003859 false, "", IDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003860
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003861 // Protocols referenced in class declaration?
Steve Naroff621edce2009-04-29 16:37:50 +00003862 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003863 "CLASS", CDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003864
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003865 // Declaration of class/meta-class metadata
3866 /* struct _objc_class {
3867 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003868 const char *super_class_name;
3869 char *name;
3870 long version;
3871 long info;
3872 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003873 struct _objc_ivar_list *ivars;
3874 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003875 struct objc_cache *cache;
3876 struct objc_protocol_list *protocols;
3877 const char *ivar_layout;
3878 struct _objc_class_ext *ext;
Mike Stump1eb44332009-09-09 15:08:12 +00003879 };
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003880 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003881 static bool objc_class = false;
3882 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003883 Result += "\nstruct _objc_class {\n";
3884 Result += "\tstruct _objc_class *isa;\n";
3885 Result += "\tconst char *super_class_name;\n";
3886 Result += "\tchar *name;\n";
3887 Result += "\tlong version;\n";
3888 Result += "\tlong info;\n";
3889 Result += "\tlong instance_size;\n";
3890 Result += "\tstruct _objc_ivar_list *ivars;\n";
3891 Result += "\tstruct _objc_method_list *methods;\n";
3892 Result += "\tstruct objc_cache *cache;\n";
3893 Result += "\tstruct _objc_protocol_list *protocols;\n";
3894 Result += "\tconst char *ivar_layout;\n";
3895 Result += "\tstruct _objc_class_ext *ext;\n";
3896 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003897 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003898 }
Mike Stump1eb44332009-09-09 15:08:12 +00003899
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003900 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003901 ObjCInterfaceDecl *RootClass = 0;
3902 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003903 while (SuperClass) {
3904 RootClass = SuperClass;
3905 SuperClass = SuperClass->getSuperClass();
3906 }
3907 SuperClass = CDecl->getSuperClass();
Mike Stump1eb44332009-09-09 15:08:12 +00003908
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003909 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003910 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003911 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003912 "{\n\t(struct _objc_class *)\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003913 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003914 Result += "\"";
3915
3916 if (SuperClass) {
3917 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003918 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003919 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003920 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003921 Result += "\"";
3922 }
3923 else {
3924 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003925 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003926 Result += "\"";
3927 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003928 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003929 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003930 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003931 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff23f41272008-03-11 18:14:26 +00003932 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003933 Result += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003934 Result += "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003935 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003936 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003937 Result += ", 0\n";
Chris Lattnercafeb352009-02-20 18:18:36 +00003938 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003939 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003940 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003941 Result += ",0,0\n";
3942 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003943 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003944 Result += "\t,0,0,0,0\n";
3945 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003946
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003947 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003948 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003949 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003950 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003951 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003952 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003953 if (SuperClass) {
3954 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003955 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003956 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003957 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003958 Result += "\"";
3959 }
3960 else {
3961 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003962 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003963 Result += "\"";
3964 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003965 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003966 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003967 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003968 Result += ",0";
3969 else {
3970 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003971 Result += ",sizeof(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003972 Result += CDecl->getNameAsString();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003973 if (LangOpts.Microsoft)
3974 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003975 Result += ")";
3976 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003977 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00003978 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003979 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003980 Result += "\n\t";
3981 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003982 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003983 Result += ",0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003984 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroff946a6932008-03-11 00:12:29 +00003985 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003986 Result += CDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003987 Result += ", 0\n\t";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003988 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003989 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003990 Result += ",0,0";
Chris Lattnercafeb352009-02-20 18:18:36 +00003991 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003992 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003993 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003994 Result += ", 0,0\n";
3995 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003996 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003997 Result += ",0,0,0\n";
3998 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003999}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00004000
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00004001/// RewriteImplementations - This routine rewrites all method implementations
4002/// and emits meta-data.
4003
Steve Narofface66252008-11-13 20:07:04 +00004004void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004005 int ClsDefCount = ClassImplementation.size();
4006 int CatDefCount = CategoryImplementation.size();
Mike Stump1eb44332009-09-09 15:08:12 +00004007
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00004008 // Rewrite implemented methods
4009 for (int i = 0; i < ClsDefCount; i++)
4010 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00004011
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00004012 for (int i = 0; i < CatDefCount; i++)
4013 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00004014}
Mike Stump1eb44332009-09-09 15:08:12 +00004015
Steve Narofface66252008-11-13 20:07:04 +00004016void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
4017 int ClsDefCount = ClassImplementation.size();
4018 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00004019
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00004020 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00004021 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004022 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump1eb44332009-09-09 15:08:12 +00004023
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00004024 // For each implemented category, write out all its meta data.
4025 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004026 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroff621edce2009-04-29 16:37:50 +00004027
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004028 // Write objc_symtab metadata
4029 /*
4030 struct _objc_symtab
4031 {
4032 long sel_ref_cnt;
4033 SEL *refs;
4034 short cls_def_cnt;
4035 short cat_def_cnt;
4036 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump1eb44332009-09-09 15:08:12 +00004037 };
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004038 */
Mike Stump1eb44332009-09-09 15:08:12 +00004039
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004040 Result += "\nstruct _objc_symtab {\n";
4041 Result += "\tlong sel_ref_cnt;\n";
4042 Result += "\tSEL *refs;\n";
4043 Result += "\tshort cls_def_cnt;\n";
4044 Result += "\tshort cat_def_cnt;\n";
4045 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
4046 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004047
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004048 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00004049 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004050 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004051 + ", " + utostr(CatDefCount) + "\n";
4052 for (int i = 0; i < ClsDefCount; i++) {
4053 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004054 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004055 Result += "\n";
4056 }
Mike Stump1eb44332009-09-09 15:08:12 +00004057
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004058 for (int i = 0; i < CatDefCount; i++) {
4059 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004060 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004061 Result += "_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004062 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004063 Result += "\n";
4064 }
Mike Stump1eb44332009-09-09 15:08:12 +00004065
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004066 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004067
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004068 // Write objc_module metadata
Mike Stump1eb44332009-09-09 15:08:12 +00004069
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004070 /*
4071 struct _objc_module {
4072 long version;
4073 long size;
4074 const char *name;
4075 struct _objc_symtab *symtab;
4076 }
4077 */
Mike Stump1eb44332009-09-09 15:08:12 +00004078
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004079 Result += "\nstruct _objc_module {\n";
4080 Result += "\tlong version;\n";
4081 Result += "\tlong size;\n";
4082 Result += "\tconst char *name;\n";
4083 Result += "\tstruct _objc_symtab *symtab;\n";
4084 Result += "};\n\n";
4085 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00004086 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004087 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00004088 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004089 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00004090
4091 if (LangOpts.Microsoft) {
Steve Naroff621edce2009-04-29 16:37:50 +00004092 if (ProtocolExprDecls.size()) {
4093 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
4094 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004095 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00004096 E = ProtocolExprDecls.end(); I != E; ++I) {
4097 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
4098 Result += (*I)->getNameAsString();
4099 Result += " = &_OBJC_PROTOCOL_";
4100 Result += (*I)->getNameAsString();
4101 Result += ";\n";
4102 }
4103 Result += "#pragma data_seg(pop)\n\n";
4104 }
Steve Naroff4f943c22008-03-10 20:43:59 +00004105 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00004106 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00004107 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
4108 Result += "&_OBJC_MODULES;\n";
4109 Result += "#pragma data_seg(pop)\n\n";
4110 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004111}
Chris Lattner311ff022007-10-16 22:36:42 +00004112
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004113void RewriteObjC::RewriteByRefString(std::string &ResultStr,
4114 const std::string &Name,
4115 ValueDecl *VD) {
4116 assert(BlockByRefDeclNo.count(VD) &&
4117 "RewriteByRefString: ByRef decl missing");
4118 ResultStr += "struct __Block_byref_" + Name +
4119 "_" + utostr(BlockByRefDeclNo[VD]) ;
4120}
4121
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004122static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4123 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4124 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4125 return false;
4126}
4127
Steve Naroff54055232008-10-27 17:20:55 +00004128std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
Daniel Dunbar4087f272010-08-17 22:39:59 +00004129 llvm::StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00004130 std::string Tag) {
4131 const FunctionType *AFT = CE->getFunctionType();
4132 QualType RT = AFT->getResultType();
4133 std::string StructRef = "struct " + Tag;
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00004134 std::string S = "static " + RT.getAsString(Context->PrintingPolicy) + " __" +
Daniel Dunbar4087f272010-08-17 22:39:59 +00004135 funcName.str() + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00004136
Steve Naroff54055232008-10-27 17:20:55 +00004137 BlockDecl *BD = CE->getBlockDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00004138
Douglas Gregor72564e72009-02-26 23:50:07 +00004139 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004140 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Naroffdf8570d2009-02-02 17:19:26 +00004141 // block (to reference imported block decl refs).
4142 S += "(" + StructRef + " *__cself)";
Steve Naroff54055232008-10-27 17:20:55 +00004143 } else if (BD->param_empty()) {
4144 S += "(" + StructRef + " *__cself)";
4145 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00004146 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff54055232008-10-27 17:20:55 +00004147 assert(FT && "SynthesizeBlockFunc: No function proto");
4148 S += '(';
4149 // first add the implicit argument.
4150 S += StructRef + " *__cself, ";
4151 std::string ParamStr;
4152 for (BlockDecl::param_iterator AI = BD->param_begin(),
4153 E = BD->param_end(); AI != E; ++AI) {
4154 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004155 ParamStr = (*AI)->getNameAsString();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004156 QualType QT = (*AI)->getType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004157 if (convertBlockPointerToFunctionPointer(QT))
4158 QT.getAsStringInternal(ParamStr, Context->PrintingPolicy);
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004159 else
4160 QT.getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00004161 S += ParamStr;
4162 }
4163 if (FT->isVariadic()) {
4164 if (!BD->param_empty()) S += ", ";
4165 S += "...";
4166 }
4167 S += ')';
4168 }
4169 S += " {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004170
Steve Naroff54055232008-10-27 17:20:55 +00004171 // Create local declarations to avoid rewriting all closure decl ref exprs.
4172 // First, emit a declaration for all "by ref" decls.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004173 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004174 E = BlockByRefDecls.end(); I != E; ++I) {
4175 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004176 std::string Name = (*I)->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004177 std::string TypeString;
4178 RewriteByRefString(TypeString, Name, (*I));
4179 TypeString += " *";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004180 Name = TypeString + Name;
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004181 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004182 }
Steve Naroff54055232008-10-27 17:20:55 +00004183 // Next, emit a declaration for all "by copy" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004184 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004185 E = BlockByCopyDecls.end(); I != E; ++I) {
4186 S += " ";
Steve Naroff54055232008-10-27 17:20:55 +00004187 // Handle nested closure invocation. For example:
4188 //
4189 // void (^myImportedClosure)(void);
4190 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004191 //
Steve Naroff54055232008-10-27 17:20:55 +00004192 // void (^anotherClosure)(void);
4193 // anotherClosure = ^(void) {
4194 // myImportedClosure(); // import and invoke the closure
4195 // };
4196 //
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00004197 if (isTopLevelBlockPointerType((*I)->getType())) {
4198 RewriteBlockPointerTypeVariable(S, (*I));
4199 S += " = (";
4200 RewriteBlockPointerType(S, (*I)->getType());
4201 S += ")";
4202 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4203 }
4204 else {
Fariborz Jahanian210c2482010-02-16 17:26:03 +00004205 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004206 QualType QT = (*I)->getType();
4207 if (HasLocalVariableExternalStorage(*I))
4208 QT = Context->getPointerType(QT);
4209 QT.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00004210 S += Name + " = __cself->" +
4211 (*I)->getNameAsString() + "; // bound by copy\n";
4212 }
Steve Naroff54055232008-10-27 17:20:55 +00004213 }
4214 std::string RewrittenStr = RewrittenBlockExprs[CE];
4215 const char *cstr = RewrittenStr.c_str();
4216 while (*cstr++ != '{') ;
4217 S += cstr;
4218 S += "\n";
4219 return S;
4220}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00004221
Steve Naroff54055232008-10-27 17:20:55 +00004222std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Daniel Dunbar4087f272010-08-17 22:39:59 +00004223 llvm::StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00004224 std::string Tag) {
4225 std::string StructRef = "struct " + Tag;
4226 std::string S = "static void __";
Mike Stump1eb44332009-09-09 15:08:12 +00004227
Steve Naroff54055232008-10-27 17:20:55 +00004228 S += funcName;
4229 S += "_block_copy_" + utostr(i);
4230 S += "(" + StructRef;
4231 S += "*dst, " + StructRef;
4232 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00004233 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004234 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00004235 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004236 S += (*I)->getNameAsString();
Steve Naroff47a24222008-12-11 20:51:38 +00004237 S += ", (void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004238 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004239 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004240 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004241 else
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004242 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00004243 }
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004244 S += "}\n";
4245
Steve Naroff54055232008-10-27 17:20:55 +00004246 S += "\nstatic void __";
4247 S += funcName;
4248 S += "_block_dispose_" + utostr(i);
4249 S += "(" + StructRef;
4250 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00004251 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004252 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00004253 S += "_Block_object_dispose((void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004254 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004255 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004256 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004257 else
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004258 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00004259 }
Mike Stump1eb44332009-09-09 15:08:12 +00004260 S += "}\n";
Steve Naroff54055232008-10-27 17:20:55 +00004261 return S;
4262}
4263
Steve Naroff01aec112009-12-06 21:14:13 +00004264std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4265 std::string Desc) {
Steve Naroffced80a82008-10-30 12:09:33 +00004266 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00004267 std::string Constructor = " " + Tag;
Mike Stump1eb44332009-09-09 15:08:12 +00004268
Steve Naroff54055232008-10-27 17:20:55 +00004269 S += " {\n struct __block_impl impl;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004270 S += " struct " + Desc;
4271 S += "* Desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004272
Steve Naroff01aec112009-12-06 21:14:13 +00004273 Constructor += "(void *fp, "; // Invoke function pointer.
4274 Constructor += "struct " + Desc; // Descriptor pointer.
4275 Constructor += " *desc";
Mike Stump1eb44332009-09-09 15:08:12 +00004276
Steve Naroff54055232008-10-27 17:20:55 +00004277 if (BlockDeclRefs.size()) {
4278 // Output all "by copy" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004279 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004280 E = BlockByCopyDecls.end(); I != E; ++I) {
4281 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004282 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004283 std::string ArgName = "_" + FieldName;
4284 // Handle nested closure invocation. For example:
4285 //
4286 // void (^myImportedBlock)(void);
4287 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004288 //
Steve Naroff54055232008-10-27 17:20:55 +00004289 // void (^anotherBlock)(void);
4290 // anotherBlock = ^(void) {
4291 // myImportedBlock(); // import and invoke the closure
4292 // };
4293 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004294 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00004295 S += "struct __block_impl *";
4296 Constructor += ", void *" + ArgName;
4297 } else {
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004298 QualType QT = (*I)->getType();
4299 if (HasLocalVariableExternalStorage(*I))
4300 QT = Context->getPointerType(QT);
4301 QT.getAsStringInternal(FieldName, Context->PrintingPolicy);
4302 QT.getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00004303 Constructor += ", " + ArgName;
4304 }
4305 S += FieldName + ";\n";
4306 }
4307 // Output all "by ref" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004308 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004309 E = BlockByRefDecls.end(); I != E; ++I) {
4310 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004311 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004312 std::string ArgName = "_" + FieldName;
4313 // Handle nested closure invocation. For example:
4314 //
4315 // void (^myImportedBlock)(void);
4316 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004317 //
Steve Naroff54055232008-10-27 17:20:55 +00004318 // void (^anotherBlock)(void);
4319 // anotherBlock = ^(void) {
4320 // myImportedBlock(); // import and invoke the closure
4321 // };
4322 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004323 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00004324 S += "struct __block_impl *";
4325 Constructor += ", void *" + ArgName;
4326 } else {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004327 std::string TypeString;
4328 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004329 TypeString += " *";
4330 FieldName = TypeString + FieldName;
4331 ArgName = TypeString + ArgName;
Steve Naroff54055232008-10-27 17:20:55 +00004332 Constructor += ", " + ArgName;
4333 }
4334 S += FieldName + "; // by ref\n";
4335 }
4336 // Finish writing the constructor.
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00004337 Constructor += ", int flags=0)";
4338 // Initialize all "by copy" arguments.
4339 bool firsTime = true;
4340 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4341 E = BlockByCopyDecls.end(); I != E; ++I) {
4342 std::string Name = (*I)->getNameAsString();
4343 if (firsTime) {
4344 Constructor += " : ";
4345 firsTime = false;
4346 }
4347 else
4348 Constructor += ", ";
4349 if (isTopLevelBlockPointerType((*I)->getType()))
4350 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4351 else
4352 Constructor += Name + "(_" + Name + ")";
4353 }
4354 // Initialize all "by ref" arguments.
4355 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4356 E = BlockByRefDecls.end(); I != E; ++I) {
4357 std::string Name = (*I)->getNameAsString();
4358 if (firsTime) {
4359 Constructor += " : ";
4360 firsTime = false;
4361 }
4362 else
4363 Constructor += ", ";
4364 if (isTopLevelBlockPointerType((*I)->getType()))
4365 Constructor += Name + "((struct __block_impl *)_"
4366 + Name + "->__forwarding)";
4367 else
4368 Constructor += Name + "(_" + Name + "->__forwarding)";
4369 }
4370
4371 Constructor += " {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00004372 if (GlobalVarDecl)
4373 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4374 else
4375 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004376 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004377
Steve Naroff01aec112009-12-06 21:14:13 +00004378 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004379 } else {
4380 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00004381 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00004382 if (GlobalVarDecl)
4383 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4384 else
4385 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004386 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4387 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004388 }
4389 Constructor += " ";
4390 Constructor += "}\n";
4391 S += Constructor;
4392 S += "};\n";
4393 return S;
4394}
4395
Steve Naroff01aec112009-12-06 21:14:13 +00004396std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
4397 std::string ImplTag, int i,
Daniel Dunbar4087f272010-08-17 22:39:59 +00004398 llvm::StringRef FunName,
Steve Naroff01aec112009-12-06 21:14:13 +00004399 unsigned hasCopy) {
4400 std::string S = "\nstatic struct " + DescTag;
4401
4402 S += " {\n unsigned long reserved;\n";
4403 S += " unsigned long Block_size;\n";
4404 if (hasCopy) {
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00004405 S += " void (*copy)(struct ";
4406 S += ImplTag; S += "*, struct ";
4407 S += ImplTag; S += "*);\n";
4408
4409 S += " void (*dispose)(struct ";
4410 S += ImplTag; S += "*);\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004411 }
4412 S += "} ";
4413
4414 S += DescTag + "_DATA = { 0, sizeof(struct ";
4415 S += ImplTag + ")";
4416 if (hasCopy) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00004417 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4418 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
Steve Naroff01aec112009-12-06 21:14:13 +00004419 }
4420 S += "};\n";
4421 return S;
4422}
4423
Steve Naroff54055232008-10-27 17:20:55 +00004424void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Daniel Dunbar4087f272010-08-17 22:39:59 +00004425 llvm::StringRef FunName) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004426 // Insert declaration for the function in which block literal is used.
Fariborz Jahanianbf070122010-01-15 18:14:52 +00004427 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004428 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004429 bool RewriteSC = (GlobalVarDecl &&
4430 !Blocks.empty() &&
John McCalld931b082010-08-26 03:08:43 +00004431 GlobalVarDecl->getStorageClass() == SC_Static &&
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004432 GlobalVarDecl->getType().getCVRQualifiers());
4433 if (RewriteSC) {
4434 std::string SC(" void __");
4435 SC += GlobalVarDecl->getNameAsString();
4436 SC += "() {}";
4437 InsertText(FunLocStart, SC);
4438 }
4439
Steve Naroff54055232008-10-27 17:20:55 +00004440 // Insert closures that were part of the function.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004441 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4442 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004443 // Need to copy-in the inner copied-in variables not actually used in this
4444 // block.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004445 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
4446 BlockDeclRefExpr *Exp = InnerDeclRefs[count++];
4447 ValueDecl *VD = Exp->getDecl();
4448 BlockDeclRefs.push_back(Exp);
4449 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
4450 BlockByCopyDeclsPtrSet.insert(VD);
4451 BlockByCopyDecls.push_back(VD);
4452 }
4453 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
4454 BlockByRefDeclsPtrSet.insert(VD);
4455 BlockByRefDecls.push_back(VD);
4456 }
Fariborz Jahanian92c85682010-10-05 18:05:06 +00004457 // imported objects in the inner blocks not used in the outer
4458 // blocks must be copied/disposed in the outer block as well.
4459 if (Exp->isByRef() ||
4460 VD->getType()->isObjCObjectPointerType() ||
4461 VD->getType()->isBlockPointerType())
4462 ImportedBlockDecls.insert(VD);
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004463 }
Steve Naroff54055232008-10-27 17:20:55 +00004464
Daniel Dunbar4087f272010-08-17 22:39:59 +00004465 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4466 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
Mike Stump1eb44332009-09-09 15:08:12 +00004467
Steve Naroff01aec112009-12-06 21:14:13 +00004468 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff54055232008-10-27 17:20:55 +00004469
Benjamin Kramerd999b372010-02-14 14:14:16 +00004470 InsertText(FunLocStart, CI);
Steve Naroff54055232008-10-27 17:20:55 +00004471
Steve Naroff01aec112009-12-06 21:14:13 +00004472 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump1eb44332009-09-09 15:08:12 +00004473
Benjamin Kramerd999b372010-02-14 14:14:16 +00004474 InsertText(FunLocStart, CF);
Steve Naroff54055232008-10-27 17:20:55 +00004475
4476 if (ImportedBlockDecls.size()) {
Steve Naroff01aec112009-12-06 21:14:13 +00004477 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004478 InsertText(FunLocStart, HF);
Steve Naroff54055232008-10-27 17:20:55 +00004479 }
Steve Naroff01aec112009-12-06 21:14:13 +00004480 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4481 ImportedBlockDecls.size() > 0);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004482 InsertText(FunLocStart, BD);
Mike Stump1eb44332009-09-09 15:08:12 +00004483
Steve Naroff54055232008-10-27 17:20:55 +00004484 BlockDeclRefs.clear();
4485 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004486 BlockByRefDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004487 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004488 BlockByCopyDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004489 ImportedBlockDecls.clear();
4490 }
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004491 if (RewriteSC) {
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004492 // Must insert any 'const/volatile/static here. Since it has been
4493 // removed as result of rewriting of block literals.
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004494 std::string SC;
John McCalld931b082010-08-26 03:08:43 +00004495 if (GlobalVarDecl->getStorageClass() == SC_Static)
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004496 SC = "static ";
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004497 if (GlobalVarDecl->getType().isConstQualified())
4498 SC += "const ";
4499 if (GlobalVarDecl->getType().isVolatileQualified())
4500 SC += "volatile ";
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004501 if (GlobalVarDecl->getType().isRestrictQualified())
4502 SC += "restrict ";
4503 InsertText(FunLocStart, SC);
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004504 }
4505
Steve Naroff54055232008-10-27 17:20:55 +00004506 Blocks.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004507 InnerDeclRefsCount.clear();
4508 InnerDeclRefs.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004509 RewrittenBlockExprs.clear();
4510}
4511
4512void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4513 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Daniel Dunbar4087f272010-08-17 22:39:59 +00004514 llvm::StringRef FuncName = FD->getName();
Mike Stump1eb44332009-09-09 15:08:12 +00004515
Steve Naroff54055232008-10-27 17:20:55 +00004516 SynthesizeBlockLiterals(FunLocStart, FuncName);
4517}
4518
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004519static void BuildUniqueMethodName(std::string &Name,
4520 ObjCMethodDecl *MD) {
4521 ObjCInterfaceDecl *IFace = MD->getClassInterface();
Daniel Dunbar4087f272010-08-17 22:39:59 +00004522 Name = IFace->getName();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004523 Name += "__" + MD->getSelector().getAsString();
4524 // Convert colons to underscores.
4525 std::string::size_type loc = 0;
4526 while ((loc = Name.find(":", loc)) != std::string::npos)
4527 Name.replace(loc, 1, "_");
4528}
4529
Steve Naroff54055232008-10-27 17:20:55 +00004530void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00004531 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4532 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanian0e1c99a2010-01-29 01:55:49 +00004533 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004534 std::string FuncName;
4535 BuildUniqueMethodName(FuncName, MD);
Daniel Dunbar4087f272010-08-17 22:39:59 +00004536 SynthesizeBlockLiterals(FunLocStart, FuncName);
Steve Naroff54055232008-10-27 17:20:55 +00004537}
4538
4539void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
4540 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4541 CI != E; ++CI)
4542 if (*CI) {
4543 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4544 GetBlockDeclRefExprs(CBE->getBody());
4545 else
4546 GetBlockDeclRefExprs(*CI);
4547 }
4548 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004549 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Steve Naroff54055232008-10-27 17:20:55 +00004550 // FIXME: Handle enums.
4551 if (!isa<FunctionDecl>(CDRE->getDecl()))
4552 BlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004553 }
4554 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
4555 if (HasLocalVariableExternalStorage(DRE->getDecl())) {
4556 BlockDeclRefExpr *BDRE =
4557 new (Context)BlockDeclRefExpr(DRE->getDecl(), DRE->getType(),
4558 DRE->getLocation(), false);
4559 BlockDeclRefs.push_back(BDRE);
4560 }
4561
Steve Naroff54055232008-10-27 17:20:55 +00004562 return;
4563}
4564
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004565void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4566 llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004567 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004568 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4569 CI != E; ++CI)
4570 if (*CI) {
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004571 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4572 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004573 GetInnerBlockDeclRefExprs(CBE->getBody(),
4574 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004575 InnerContexts);
4576 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004577 else
4578 GetInnerBlockDeclRefExprs(*CI,
4579 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004580 InnerContexts);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004581
4582 }
4583 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004584 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004585 if (!isa<FunctionDecl>(CDRE->getDecl()) &&
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004586 !InnerContexts.count(CDRE->getDecl()->getDeclContext()))
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004587 InnerBlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004588 }
4589 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4590 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4591 if (Var->isFunctionOrMethodVarDecl())
4592 ImportedLocalExternalDecls.insert(Var);
4593 }
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004594
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004595 return;
4596}
4597
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004598/// convertFunctionTypeOfBlocks - This routine converts a function type
4599/// whose result type may be a block pointer or whose argument type(s)
4600/// might be block pointers to an equivalent funtion type replacing
4601/// all block pointers to function pointers.
4602QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4603 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4604 // FTP will be null for closures that don't take arguments.
4605 // Generate a funky cast.
4606 llvm::SmallVector<QualType, 8> ArgTypes;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004607 QualType Res = FT->getResultType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004608 bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004609
4610 if (FTP) {
4611 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4612 E = FTP->arg_type_end(); I && (I != E); ++I) {
4613 QualType t = *I;
4614 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004615 if (convertBlockPointerToFunctionPointer(t))
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004616 HasBlockType = true;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004617 ArgTypes.push_back(t);
4618 }
4619 }
4620 QualType FuncType;
4621 // FIXME. Does this work if block takes no argument but has a return type
4622 // which is of block type?
4623 if (HasBlockType)
4624 FuncType = Context->getFunctionType(Res,
4625 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0,
4626 false, false, 0, 0, FunctionType::ExtInfo());
4627 else FuncType = QualType(FT, 0);
4628 return FuncType;
4629}
4630
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004631Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff54055232008-10-27 17:20:55 +00004632 // Navigate to relevant type information.
Steve Naroff54055232008-10-27 17:20:55 +00004633 const BlockPointerType *CPT = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004634
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004635 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004636 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004637 } else if (const BlockDeclRefExpr *CDRE =
4638 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004639 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004640 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004641 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004642 }
4643 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4644 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4645 }
4646 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4647 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4648 else if (const ConditionalOperator *CEXPR =
4649 dyn_cast<ConditionalOperator>(BlockExp)) {
4650 Expr *LHSExp = CEXPR->getLHS();
4651 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4652 Expr *RHSExp = CEXPR->getRHS();
4653 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4654 Expr *CONDExp = CEXPR->getCond();
4655 ConditionalOperator *CondExpr =
4656 new (Context) ConditionalOperator(CONDExp,
4657 SourceLocation(), cast<Expr>(LHSStmt),
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00004658 SourceLocation(), cast<Expr>(RHSStmt),
4659 (Expr*)0,
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004660 Exp->getType());
4661 return CondExpr;
Fariborz Jahaniane24b22b2009-12-18 01:15:21 +00004662 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4663 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004664 } else {
4665 assert(1 && "RewriteBlockClass: Bad type");
4666 }
4667 assert(CPT && "RewriteBlockClass: Bad type");
John McCall183700f2009-09-21 23:43:11 +00004668 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff54055232008-10-27 17:20:55 +00004669 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor72564e72009-02-26 23:50:07 +00004670 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff54055232008-10-27 17:20:55 +00004671 // FTP will be null for closures that don't take arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004672
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004673 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004674 SourceLocation(),
4675 &Context->Idents.get("__block_impl"));
4676 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00004677
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004678 // Generate a funky cast.
4679 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00004680
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004681 // Push the block argument type.
4682 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00004683 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004684 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004685 E = FTP->arg_type_end(); I && (I != E); ++I) {
4686 QualType t = *I;
4687 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004688 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004689 ArgTypes.push_back(t);
4690 }
Steve Naroff54055232008-10-27 17:20:55 +00004691 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004692 // Now do the pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00004693 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00004694 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0,
4695 false, false, 0, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00004696 FunctionType::ExtInfo());
Mike Stump1eb44332009-09-09 15:08:12 +00004697
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004698 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump1eb44332009-09-09 15:08:12 +00004699
John McCall9d125032010-01-15 18:39:57 +00004700 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
John McCall2de56d12010-08-25 11:45:40 +00004701 CK_Unknown,
John McCall9d125032010-01-15 18:39:57 +00004702 const_cast<Expr*>(BlockExp));
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004703 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004704 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4705 BlkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004706 //PE->dump();
Mike Stump1eb44332009-09-09 15:08:12 +00004707
Douglas Gregor44b43212008-12-11 16:49:14 +00004708 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00004709 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004710 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004711 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4712 FD->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00004713
John McCall9d125032010-01-15 18:39:57 +00004714 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
John McCall2de56d12010-08-25 11:45:40 +00004715 CK_Unknown, ME);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004716 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump1eb44332009-09-09 15:08:12 +00004717
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004718 llvm::SmallVector<Expr*, 8> BlkExprs;
4719 // Add the implicit argument.
4720 BlkExprs.push_back(BlkCast);
4721 // Add the user arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004722 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004723 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004724 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00004725 }
Ted Kremenek668bf912009-02-09 20:51:47 +00004726 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4727 BlkExprs.size(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00004728 Exp->getType(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004729 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00004730}
4731
Steve Naroff621edce2009-04-29 16:37:50 +00004732// We need to return the rewritten expression to handle cases where the
4733// BlockDeclRefExpr is embedded in another expression being rewritten.
4734// For example:
4735//
4736// int main() {
4737// __block Foo *f;
4738// __block int i;
Mike Stump1eb44332009-09-09 15:08:12 +00004739//
Steve Naroff621edce2009-04-29 16:37:50 +00004740// void (^myblock)() = ^() {
4741// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4742// i = 77;
4743// };
4744//}
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004745Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanianbbf37e22009-12-23 19:26:34 +00004746 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004747 // for each DeclRefExp where BYREFVAR is name of the variable.
4748 ValueDecl *VD;
4749 bool isArrow = true;
4750 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4751 VD = BDRE->getDecl();
4752 else {
4753 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4754 isArrow = false;
4755 }
4756
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004757 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4758 &Context->Idents.get("__forwarding"),
4759 Context->VoidPtrTy, 0,
4760 /*BitWidth=*/0, /*Mutable=*/true);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004761 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4762 FD, SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004763 FD->getType());
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004764
Daniel Dunbar4087f272010-08-17 22:39:59 +00004765 llvm::StringRef Name = VD->getName();
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004766 FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4767 &Context->Idents.get(Name),
4768 Context->VoidPtrTy, 0,
4769 /*BitWidth=*/0, /*Mutable=*/true);
4770 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004771 DeclRefExp->getType());
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004772
4773
4774
Steve Naroffdf8570d2009-02-02 17:19:26 +00004775 // Need parens to enforce precedence.
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004776 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4777 ME);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004778 ReplaceStmt(DeclRefExp, PE);
Steve Naroff621edce2009-04-29 16:37:50 +00004779 return PE;
Steve Naroff54055232008-10-27 17:20:55 +00004780}
4781
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004782// Rewrites the imported local variable V with external storage
4783// (static, extern, etc.) as *V
4784//
4785Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4786 ValueDecl *VD = DRE->getDecl();
4787 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4788 if (!ImportedLocalExternalDecls.count(Var))
4789 return DRE;
John McCall2de56d12010-08-25 11:45:40 +00004790 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref,
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004791 DRE->getType(), DRE->getLocation());
4792 // Need parens to enforce precedence.
4793 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4794 Exp);
4795 ReplaceStmt(DRE, PE);
4796 return PE;
4797}
4798
Steve Naroffb2f9e512008-11-03 23:29:32 +00004799void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4800 SourceLocation LocStart = CE->getLParenLoc();
4801 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00004802
4803 // Need to avoid trying to rewrite synthesized casts.
4804 if (LocStart.isInvalid())
4805 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00004806 // Need to avoid trying to rewrite casts contained in macros.
4807 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4808 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004809
Steve Naroff54055232008-10-27 17:20:55 +00004810 const char *startBuf = SM->getCharacterData(LocStart);
4811 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004812 QualType QT = CE->getType();
4813 const Type* TypePtr = QT->getAs<Type>();
4814 if (isa<TypeOfExprType>(TypePtr)) {
4815 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4816 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4817 std::string TypeAsString = "(";
Fariborz Jahanianafad76f2010-02-18 01:20:22 +00004818 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004819 TypeAsString += ")";
Benjamin Kramerd999b372010-02-14 14:14:16 +00004820 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004821 return;
4822 }
Steve Naroff54055232008-10-27 17:20:55 +00004823 // advance the location to startArgList.
4824 const char *argPtr = startBuf;
Mike Stump1eb44332009-09-09 15:08:12 +00004825
Steve Naroff54055232008-10-27 17:20:55 +00004826 while (*argPtr++ && (argPtr < endBuf)) {
4827 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004828 case '^':
4829 // Replace the '^' with '*'.
4830 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004831 ReplaceText(LocStart, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004832 break;
Steve Naroff54055232008-10-27 17:20:55 +00004833 }
4834 }
4835 return;
4836}
4837
4838void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4839 SourceLocation DeclLoc = FD->getLocation();
4840 unsigned parenCount = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004841
Steve Naroff54055232008-10-27 17:20:55 +00004842 // We have 1 or more arguments that have closure pointers.
4843 const char *startBuf = SM->getCharacterData(DeclLoc);
4844 const char *startArgList = strchr(startBuf, '(');
Mike Stump1eb44332009-09-09 15:08:12 +00004845
Steve Naroff54055232008-10-27 17:20:55 +00004846 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004847
Steve Naroff54055232008-10-27 17:20:55 +00004848 parenCount++;
4849 // advance the location to startArgList.
4850 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4851 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump1eb44332009-09-09 15:08:12 +00004852
Steve Naroff54055232008-10-27 17:20:55 +00004853 const char *argPtr = startArgList;
Mike Stump1eb44332009-09-09 15:08:12 +00004854
Steve Naroff54055232008-10-27 17:20:55 +00004855 while (*argPtr++ && parenCount) {
4856 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004857 case '^':
4858 // Replace the '^' with '*'.
4859 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004860 ReplaceText(DeclLoc, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004861 break;
4862 case '(':
4863 parenCount++;
4864 break;
4865 case ')':
4866 parenCount--;
4867 break;
Steve Naroff54055232008-10-27 17:20:55 +00004868 }
4869 }
4870 return;
4871}
4872
4873bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004874 const FunctionProtoType *FTP;
Ted Kremenek6217b802009-07-29 21:53:49 +00004875 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004876 if (PT) {
John McCall183700f2009-09-21 23:43:11 +00004877 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004878 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00004879 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004880 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall183700f2009-09-21 23:43:11 +00004881 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004882 }
4883 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004884 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004885 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004886 if (isTopLevelBlockPointerType(*I))
Steve Naroff54055232008-10-27 17:20:55 +00004887 return true;
4888 }
4889 return false;
4890}
4891
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004892bool RewriteObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4893 const FunctionProtoType *FTP;
4894 const PointerType *PT = QT->getAs<PointerType>();
4895 if (PT) {
4896 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4897 } else {
4898 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4899 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4900 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4901 }
4902 if (FTP) {
4903 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Fariborz Jahanian06de2cf2010-11-03 23:50:34 +00004904 E = FTP->arg_type_end(); I != E; ++I) {
4905 if ((*I)->isObjCQualifiedIdType())
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004906 return true;
Fariborz Jahanian06de2cf2010-11-03 23:50:34 +00004907 if ((*I)->isObjCObjectPointerType() &&
4908 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4909 return true;
4910 }
4911
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004912 }
4913 return false;
4914}
4915
Ted Kremenek8189cde2009-02-07 01:47:29 +00004916void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4917 const char *&RParen) {
Steve Naroff54055232008-10-27 17:20:55 +00004918 const char *argPtr = strchr(Name, '(');
4919 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004920
Steve Naroff54055232008-10-27 17:20:55 +00004921 LParen = argPtr; // output the start.
4922 argPtr++; // skip past the left paren.
4923 unsigned parenCount = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004924
Steve Naroff54055232008-10-27 17:20:55 +00004925 while (*argPtr && parenCount) {
4926 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004927 case '(': parenCount++; break;
4928 case ')': parenCount--; break;
4929 default: break;
Steve Naroff54055232008-10-27 17:20:55 +00004930 }
4931 if (parenCount) argPtr++;
4932 }
4933 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4934 RParen = argPtr; // output the end
4935}
4936
4937void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4938 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4939 RewriteBlockPointerFunctionArgs(FD);
4940 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004941 }
Steve Naroff54055232008-10-27 17:20:55 +00004942 // Handle Variables and Typedefs.
4943 SourceLocation DeclLoc = ND->getLocation();
4944 QualType DeclT;
4945 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4946 DeclT = VD->getType();
4947 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4948 DeclT = TDD->getUnderlyingType();
4949 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4950 DeclT = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00004951 else
Steve Naroff54055232008-10-27 17:20:55 +00004952 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump1eb44332009-09-09 15:08:12 +00004953
Steve Naroff54055232008-10-27 17:20:55 +00004954 const char *startBuf = SM->getCharacterData(DeclLoc);
4955 const char *endBuf = startBuf;
4956 // scan backward (from the decl location) for the end of the previous decl.
4957 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4958 startBuf--;
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004959 SourceLocation Start = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
4960 std::string buf;
4961 unsigned OrigLength=0;
Steve Naroff54055232008-10-27 17:20:55 +00004962 // *startBuf != '^' if we are dealing with a pointer to function that
4963 // may take block argument types (which will be handled below).
4964 if (*startBuf == '^') {
4965 // Replace the '^' with '*', computing a negative offset.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004966 buf = '*';
4967 startBuf++;
4968 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00004969 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004970 while (*startBuf != ')') {
4971 buf += *startBuf;
4972 startBuf++;
4973 OrigLength++;
4974 }
4975 buf += ')';
4976 OrigLength++;
4977
4978 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4979 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
Steve Naroff54055232008-10-27 17:20:55 +00004980 // Replace the '^' with '*' for arguments.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004981 // Replace id<P> with id/*<>*/
Steve Naroff54055232008-10-27 17:20:55 +00004982 DeclLoc = ND->getLocation();
4983 startBuf = SM->getCharacterData(DeclLoc);
4984 const char *argListBegin, *argListEnd;
4985 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4986 while (argListBegin < argListEnd) {
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004987 if (*argListBegin == '^')
4988 buf += '*';
4989 else if (*argListBegin == '<') {
4990 buf += "/*";
4991 buf += *argListBegin++;
4992 OrigLength++;;
4993 while (*argListBegin != '>') {
4994 buf += *argListBegin++;
4995 OrigLength++;
4996 }
4997 buf += *argListBegin;
4998 buf += "*/";
Steve Naroff54055232008-10-27 17:20:55 +00004999 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005000 else
5001 buf += *argListBegin;
Steve Naroff54055232008-10-27 17:20:55 +00005002 argListBegin++;
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005003 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00005004 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005005 buf += ')';
5006 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00005007 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005008 ReplaceText(Start, OrigLength, buf);
5009
Steve Naroff54055232008-10-27 17:20:55 +00005010 return;
5011}
5012
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005013
5014/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
5015/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
5016/// struct Block_byref_id_object *src) {
5017/// _Block_object_assign (&_dest->object, _src->object,
5018/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5019/// [|BLOCK_FIELD_IS_WEAK]) // object
5020/// _Block_object_assign(&_dest->object, _src->object,
5021/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5022/// [|BLOCK_FIELD_IS_WEAK]) // block
5023/// }
5024/// And:
5025/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
5026/// _Block_object_dispose(_src->object,
5027/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5028/// [|BLOCK_FIELD_IS_WEAK]) // object
5029/// _Block_object_dispose(_src->object,
5030/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5031/// [|BLOCK_FIELD_IS_WEAK]) // block
5032/// }
5033
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005034std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
5035 int flag) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005036 std::string S;
Benjamin Kramer1211a712010-01-10 19:57:50 +00005037 if (CopyDestroyCache.count(flag))
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005038 return S;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005039 CopyDestroyCache.insert(flag);
5040 S = "static void __Block_byref_id_object_copy_";
5041 S += utostr(flag);
5042 S += "(void *dst, void *src) {\n";
5043
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005044 // offset into the object pointer is computed as:
5045 // void * + void* + int + int + void* + void *
5046 unsigned IntSize =
5047 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5048 unsigned VoidPtrSize =
5049 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
5050
5051 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/8;
5052 S += " _Block_object_assign((char*)dst + ";
5053 S += utostr(offset);
5054 S += ", *(void * *) ((char*)src + ";
5055 S += utostr(offset);
5056 S += "), ";
5057 S += utostr(flag);
5058 S += ");\n}\n";
5059
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005060 S += "static void __Block_byref_id_object_dispose_";
5061 S += utostr(flag);
5062 S += "(void *src) {\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005063 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
5064 S += utostr(offset);
5065 S += "), ";
5066 S += utostr(flag);
5067 S += ");\n}\n";
5068 return S;
5069}
5070
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005071/// RewriteByRefVar - For each __block typex ND variable this routine transforms
5072/// the declaration into:
5073/// struct __Block_byref_ND {
5074/// void *__isa; // NULL for everything except __weak pointers
5075/// struct __Block_byref_ND *__forwarding;
5076/// int32_t __flags;
5077/// int32_t __size;
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005078/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5079/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005080/// typex ND;
5081/// };
5082///
5083/// It then replaces declaration of ND variable with:
5084/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5085/// __size=sizeof(struct __Block_byref_ND),
5086/// ND=initializer-if-any};
5087///
5088///
5089void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005090 // Insert declaration for the function in which block literal is
5091 // used.
5092 if (CurFunctionDeclToDeclareForBlock)
5093 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005094 int flag = 0;
5095 int isa = 0;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005096 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
Fariborz Jahaniand64a4f42010-02-26 22:49:11 +00005097 if (DeclLoc.isInvalid())
5098 // If type location is missing, it is because of missing type (a warning).
5099 // Use variable's location which is good for this case.
5100 DeclLoc = ND->getLocation();
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005101 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00005102 SourceLocation X = ND->getLocEnd();
5103 X = SM->getInstantiationLoc(X);
5104 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005105 std::string Name(ND->getNameAsString());
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005106 std::string ByrefType;
5107 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005108 ByrefType += " {\n";
5109 ByrefType += " void *__isa;\n";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005110 RewriteByRefString(ByrefType, Name, ND);
5111 ByrefType += " *__forwarding;\n";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005112 ByrefType += " int __flags;\n";
5113 ByrefType += " int __size;\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005114 // Add void *__Block_byref_id_object_copy;
5115 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005116 QualType Ty = ND->getType();
5117 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
5118 if (HasCopyAndDispose) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005119 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5120 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005121 }
5122
5123 Ty.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005124 ByrefType += " " + Name + ";\n";
5125 ByrefType += "};\n";
5126 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005127 SourceLocation FunLocStart;
5128 if (CurFunctionDef)
5129 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
5130 else {
5131 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5132 FunLocStart = CurMethodDef->getLocStart();
5133 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00005134 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005135 if (Ty.isObjCGCWeak()) {
5136 flag |= BLOCK_FIELD_IS_WEAK;
5137 isa = 1;
5138 }
5139
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005140 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005141 flag = BLOCK_BYREF_CALLER;
5142 QualType Ty = ND->getType();
5143 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5144 if (Ty->isBlockPointerType())
5145 flag |= BLOCK_FIELD_IS_BLOCK;
5146 else
5147 flag |= BLOCK_FIELD_IS_OBJECT;
5148 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005149 if (!HF.empty())
Benjamin Kramerd999b372010-02-14 14:14:16 +00005150 InsertText(FunLocStart, HF);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005151 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005152
5153 // struct __Block_byref_ND ND =
5154 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5155 // initializer-if-any};
5156 bool hasInit = (ND->getInit() != 0);
Fariborz Jahaniane1f84f82010-01-05 18:15:57 +00005157 unsigned flags = 0;
5158 if (HasCopyAndDispose)
5159 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005160 Name = ND->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005161 ByrefType.clear();
5162 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005163 std::string ForwardingCastType("(");
5164 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005165 if (!hasInit) {
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005166 ByrefType += " " + Name + " = {(void*)";
5167 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005168 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005169 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005170 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005171 ByrefType += "sizeof(";
5172 RewriteByRefString(ByrefType, Name, ND);
5173 ByrefType += ")";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005174 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005175 ByrefType += ", __Block_byref_id_object_copy_";
5176 ByrefType += utostr(flag);
5177 ByrefType += ", __Block_byref_id_object_dispose_";
5178 ByrefType += utostr(flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005179 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005180 ByrefType += "};\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00005181 ReplaceText(DeclLoc, endBuf-startBuf+Name.size(), ByrefType);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005182 }
5183 else {
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005184 SourceLocation startLoc;
5185 Expr *E = ND->getInit();
5186 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5187 startLoc = ECE->getLParenLoc();
5188 else
5189 startLoc = E->getLocStart();
Fariborz Jahanian791b10d2010-01-05 23:06:29 +00005190 startLoc = SM->getInstantiationLoc(startLoc);
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005191 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005192 ByrefType += " " + Name;
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005193 ByrefType += " = {(void*)";
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005194 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005195 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005196 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005197 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005198 ByrefType += "sizeof(";
5199 RewriteByRefString(ByrefType, Name, ND);
5200 ByrefType += "), ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005201 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005202 ByrefType += "__Block_byref_id_object_copy_";
5203 ByrefType += utostr(flag);
5204 ByrefType += ", __Block_byref_id_object_dispose_";
5205 ByrefType += utostr(flag);
5206 ByrefType += ", ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005207 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00005208 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroffc5143c52009-12-23 17:24:33 +00005209
5210 // Complete the newly synthesized compound expression by inserting a right
5211 // curly brace before the end of the declaration.
5212 // FIXME: This approach avoids rewriting the initializer expression. It
5213 // also assumes there is only one declarator. For example, the following
5214 // isn't currently supported by this routine (in general):
5215 //
5216 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
5217 //
Fariborz Jahanian5f371ee2010-07-21 17:36:39 +00005218 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5219 const char *semiBuf = strchr(startInitializerBuf, ';');
Steve Naroffc5143c52009-12-23 17:24:33 +00005220 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
5221 SourceLocation semiLoc =
Fariborz Jahanian5f371ee2010-07-21 17:36:39 +00005222 startLoc.getFileLocWithOffset(semiBuf-startInitializerBuf);
Steve Naroffc5143c52009-12-23 17:24:33 +00005223
Benjamin Kramerd999b372010-02-14 14:14:16 +00005224 InsertText(semiLoc, "}");
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005225 }
Fariborz Jahanian1be6b462009-12-22 00:48:54 +00005226 return;
5227}
5228
Mike Stump1eb44332009-09-09 15:08:12 +00005229void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00005230 // Add initializers for any closure decl refs.
5231 GetBlockDeclRefExprs(Exp->getBody());
5232 if (BlockDeclRefs.size()) {
5233 // Unique all "by copy" declarations.
5234 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005235 if (!BlockDeclRefs[i]->isByRef()) {
5236 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5237 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5238 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5239 }
5240 }
Steve Naroff54055232008-10-27 17:20:55 +00005241 // Unique all "by ref" declarations.
5242 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5243 if (BlockDeclRefs[i]->isByRef()) {
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005244 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5245 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5246 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5247 }
Steve Naroff54055232008-10-27 17:20:55 +00005248 }
5249 // Find any imported blocks...they will need special attention.
5250 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00005251 if (BlockDeclRefs[i]->isByRef() ||
5252 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian5b011b02010-02-26 21:46:27 +00005253 BlockDeclRefs[i]->getType()->isBlockPointerType())
Steve Naroff54055232008-10-27 17:20:55 +00005254 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
Steve Naroff54055232008-10-27 17:20:55 +00005255 }
5256}
5257
Daniel Dunbar4087f272010-08-17 22:39:59 +00005258FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(llvm::StringRef name) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005259 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor72564e72009-02-26 23:50:07 +00005260 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Mike Stump1eb44332009-09-09 15:08:12 +00005261 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
John McCalld931b082010-08-26 03:08:43 +00005262 ID, FType, 0, SC_Extern,
5263 SC_None, false, false);
Steve Narofffa15fd92008-10-28 20:29:00 +00005264}
5265
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005266Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
5267 const llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005268 Blocks.push_back(Exp);
5269
5270 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005271
5272 // Add inner imported variables now used in current block.
5273 int countOfInnerDecls = 0;
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005274 if (!InnerBlockDeclRefs.empty()) {
5275 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
5276 BlockDeclRefExpr *Exp = InnerBlockDeclRefs[i];
5277 ValueDecl *VD = Exp->getDecl();
5278 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005279 // We need to save the copied-in variables in nested
5280 // blocks because it is needed at the end for some of the API generations.
5281 // See SynthesizeBlockLiterals routine.
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005282 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5283 BlockDeclRefs.push_back(Exp);
5284 BlockByCopyDeclsPtrSet.insert(VD);
5285 BlockByCopyDecls.push_back(VD);
5286 }
5287 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
5288 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5289 BlockDeclRefs.push_back(Exp);
5290 BlockByRefDeclsPtrSet.insert(VD);
5291 BlockByRefDecls.push_back(VD);
5292 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005293 }
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005294 // Find any imported blocks...they will need special attention.
5295 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
5296 if (InnerBlockDeclRefs[i]->isByRef() ||
5297 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5298 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5299 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005300 }
5301 InnerDeclRefsCount.push_back(countOfInnerDecls);
5302
Steve Narofffa15fd92008-10-28 20:29:00 +00005303 std::string FuncName;
Mike Stump1eb44332009-09-09 15:08:12 +00005304
Steve Narofffa15fd92008-10-28 20:29:00 +00005305 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00005306 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00005307 else if (CurMethodDef)
5308 BuildUniqueMethodName(FuncName, CurMethodDef);
5309 else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005310 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump1eb44332009-09-09 15:08:12 +00005311
Steve Narofffa15fd92008-10-28 20:29:00 +00005312 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump1eb44332009-09-09 15:08:12 +00005313
Steve Narofffa15fd92008-10-28 20:29:00 +00005314 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
5315 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00005316
Steve Narofffa15fd92008-10-28 20:29:00 +00005317 // Get a pointer to the function type so we can cast appropriately.
Fariborz Jahanian1f906222010-05-25 15:56:08 +00005318 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5319 QualType FType = Context->getPointerType(BFT);
Steve Narofffa15fd92008-10-28 20:29:00 +00005320
5321 FunctionDecl *FD;
5322 Expr *NewRep;
Mike Stump1eb44332009-09-09 15:08:12 +00005323
Steve Narofffa15fd92008-10-28 20:29:00 +00005324 // Simulate a contructor call...
Daniel Dunbar4087f272010-08-17 22:39:59 +00005325 FD = SynthBlockInitFunctionDecl(Tag);
Ted Kremenek8189cde2009-02-07 01:47:29 +00005326 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00005327
Steve Narofffa15fd92008-10-28 20:29:00 +00005328 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00005329
Steve Narofffdc03722008-10-29 21:23:59 +00005330 // Initialize the block function.
Daniel Dunbar4087f272010-08-17 22:39:59 +00005331 FD = SynthBlockInitFunctionDecl(Func);
Ted Kremenek8189cde2009-02-07 01:47:29 +00005332 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
5333 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00005334 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCall2de56d12010-08-25 11:45:40 +00005335 CK_Unknown, Arg);
Mike Stump1eb44332009-09-09 15:08:12 +00005336 InitExprs.push_back(castExpr);
5337
Steve Naroff01aec112009-12-06 21:14:13 +00005338 // Initialize the block descriptor.
5339 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump1eb44332009-09-09 15:08:12 +00005340
Steve Naroff01aec112009-12-06 21:14:13 +00005341 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
5342 &Context->Idents.get(DescData.c_str()),
5343 Context->VoidPtrTy, 0,
John McCalld931b082010-08-26 03:08:43 +00005344 SC_Static, SC_None);
Steve Naroff01aec112009-12-06 21:14:13 +00005345 UnaryOperator *DescRefExpr = new (Context) UnaryOperator(
5346 new (Context) DeclRefExpr(NewVD,
5347 Context->VoidPtrTy, SourceLocation()),
John McCall2de56d12010-08-25 11:45:40 +00005348 UO_AddrOf,
Steve Naroff01aec112009-12-06 21:14:13 +00005349 Context->getPointerType(Context->VoidPtrTy),
5350 SourceLocation());
5351 InitExprs.push_back(DescRefExpr);
5352
Steve Narofffa15fd92008-10-28 20:29:00 +00005353 // Add initializers for any closure decl refs.
5354 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00005355 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00005356 // Output all "by copy" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005357 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00005358 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005359 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00005360 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Daniel Dunbar4087f272010-08-17 22:39:59 +00005361 FD = SynthBlockInitFunctionDecl((*I)->getName());
Ted Kremenek8189cde2009-02-07 01:47:29 +00005362 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00005363 if (HasLocalVariableExternalStorage(*I)) {
5364 QualType QT = (*I)->getType();
5365 QT = Context->getPointerType(QT);
John McCall2de56d12010-08-25 11:45:40 +00005366 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT,
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00005367 SourceLocation());
5368 }
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005369 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00005370 FD = SynthBlockInitFunctionDecl((*I)->getName());
Ted Kremenek8189cde2009-02-07 01:47:29 +00005371 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00005372 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCall2de56d12010-08-25 11:45:40 +00005373 CK_Unknown, Arg);
Steve Narofffa15fd92008-10-28 20:29:00 +00005374 } else {
Daniel Dunbar4087f272010-08-17 22:39:59 +00005375 FD = SynthBlockInitFunctionDecl((*I)->getName());
Ted Kremenek8189cde2009-02-07 01:47:29 +00005376 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005377 if (HasLocalVariableExternalStorage(*I)) {
5378 QualType QT = (*I)->getType();
5379 QT = Context->getPointerType(QT);
John McCall2de56d12010-08-25 11:45:40 +00005380 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT,
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005381 SourceLocation());
5382 }
5383
Steve Narofffa15fd92008-10-28 20:29:00 +00005384 }
Mike Stump1eb44332009-09-09 15:08:12 +00005385 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00005386 }
5387 // Output all "by ref" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005388 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00005389 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005390 ValueDecl *ND = (*I);
5391 std::string Name(ND->getNameAsString());
5392 std::string RecName;
5393 RewriteByRefString(RecName, Name, ND);
5394 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5395 + sizeof("struct"));
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005396 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005397 SourceLocation(), II);
5398 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5399 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5400
Daniel Dunbar4087f272010-08-17 22:39:59 +00005401 FD = SynthBlockInitFunctionDecl((*I)->getName());
Ted Kremenek8189cde2009-02-07 01:47:29 +00005402 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00005403 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00005404 Context->getPointerType(Exp->getType()),
Steve Narofffdc03722008-10-29 21:23:59 +00005405 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00005406 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_Unknown, Exp);
Mike Stump1eb44332009-09-09 15:08:12 +00005407 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00005408 }
5409 }
Fariborz Jahanianff127882009-12-23 21:52:32 +00005410 if (ImportedBlockDecls.size()) {
5411 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5412 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff01aec112009-12-06 21:14:13 +00005413 unsigned IntSize =
5414 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00005415 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5416 Context->IntTy, SourceLocation());
Fariborz Jahanianff127882009-12-23 21:52:32 +00005417 InitExprs.push_back(FlagExp);
Steve Naroff01aec112009-12-06 21:14:13 +00005418 }
Ted Kremenek668bf912009-02-09 20:51:47 +00005419 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
5420 FType, SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00005421 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00005422 Context->getPointerType(NewRep->getType()),
Steve Narofffa15fd92008-10-28 20:29:00 +00005423 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00005424 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_Unknown,
John McCall9d125032010-01-15 18:39:57 +00005425 NewRep);
Steve Narofffa15fd92008-10-28 20:29:00 +00005426 BlockDeclRefs.clear();
5427 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005428 BlockByRefDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005429 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005430 BlockByCopyDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005431 ImportedBlockDecls.clear();
5432 return NewRep;
5433}
5434
5435//===----------------------------------------------------------------------===//
5436// Function Body / Expression rewriting
5437//===----------------------------------------------------------------------===//
5438
Steve Naroffc77a6362008-12-04 16:24:46 +00005439// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
5440// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
5441// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
5442// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
5443// Since the rewriter isn't capable of rewriting rewritten code, it's important
5444// we get this right.
5445void RewriteObjC::CollectPropertySetters(Stmt *S) {
5446 // Perform a bottom up traversal of all children.
5447 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
5448 CI != E; ++CI)
5449 if (*CI)
5450 CollectPropertySetters(*CI);
5451
5452 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
5453 if (BinOp->isAssignmentOp()) {
Fariborz Jahanian8537f7b2010-10-11 22:21:03 +00005454 if (isa<ObjCPropertyRefExpr>(BinOp->getLHS()) ||
5455 isa<ObjCImplicitSetterGetterRefExpr>(BinOp->getLHS()))
5456 PropSetters[BinOp->getLHS()] = BinOp;
Steve Naroffc77a6362008-12-04 16:24:46 +00005457 }
5458 }
5459}
5460
Steve Narofffa15fd92008-10-28 20:29:00 +00005461Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump1eb44332009-09-09 15:08:12 +00005462 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005463 isa<DoStmt>(S) || isa<ForStmt>(S))
5464 Stmts.push_back(S);
5465 else if (isa<ObjCForCollectionStmt>(S)) {
5466 Stmts.push_back(S);
Chris Lattner4824fcd2010-01-09 21:45:57 +00005467 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofffa15fd92008-10-28 20:29:00 +00005468 }
Mike Stump1eb44332009-09-09 15:08:12 +00005469
Steve Narofffa15fd92008-10-28 20:29:00 +00005470 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00005471
Steve Narofffa15fd92008-10-28 20:29:00 +00005472 // Perform a bottom up rewrite of all children.
5473 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
5474 CI != E; ++CI)
5475 if (*CI) {
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00005476 Stmt *newStmt;
5477 Stmt *S = (*CI);
5478 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5479 Expr *OldBase = IvarRefExpr->getBase();
5480 bool replaced = false;
5481 newStmt = RewriteObjCNestedIvarRefExpr(S, replaced);
5482 if (replaced) {
5483 if (ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(newStmt))
5484 ReplaceStmt(OldBase, IRE->getBase());
5485 else
5486 ReplaceStmt(S, newStmt);
5487 }
5488 }
5489 else
5490 newStmt = RewriteFunctionBodyOrGlobalInitializer(S);
Mike Stump1eb44332009-09-09 15:08:12 +00005491 if (newStmt)
Steve Narofffa15fd92008-10-28 20:29:00 +00005492 *CI = newStmt;
Fariborz Jahanian90fe4bc2010-10-08 21:12:22 +00005493 // If dealing with an assignment with LHS being a property reference
5494 // expression, the entire assignment tree is rewritten into a property
5495 // setter messaging. This involvs the RHS too. Do not attempt to rewrite
5496 // RHS again.
Fariborz Jahanian8537f7b2010-10-11 22:21:03 +00005497 if (Expr *Exp = dyn_cast<Expr>(S))
5498 if (isa<ObjCPropertyRefExpr>(Exp) ||
5499 isa<ObjCImplicitSetterGetterRefExpr>(Exp)) {
5500 if (PropSetters[Exp]) {
5501 ++CI;
5502 continue;
5503 }
Fariborz Jahanian90fe4bc2010-10-08 21:12:22 +00005504 }
Nick Lewycky7e749242010-10-31 21:07:24 +00005505 }
Mike Stump1eb44332009-09-09 15:08:12 +00005506
Steve Narofffa15fd92008-10-28 20:29:00 +00005507 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005508 llvm::SmallVector<BlockDeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00005509 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5510 InnerContexts.insert(BE->getBlockDecl());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005511 ImportedLocalExternalDecls.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005512 GetInnerBlockDeclRefExprs(BE->getBody(),
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00005513 InnerBlockDeclRefs, InnerContexts);
Steve Narofffa15fd92008-10-28 20:29:00 +00005514 // Rewrite the block body in place.
5515 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005516 ImportedLocalExternalDecls.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005517 // Now we snarf the rewritten text and stash it away for later use.
Ted Kremenek6a12a142010-01-07 18:00:35 +00005518 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005519 RewrittenBlockExprs[BE] = Str;
Mike Stump1eb44332009-09-09 15:08:12 +00005520
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005521 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5522
Steve Narofffa15fd92008-10-28 20:29:00 +00005523 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005524 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00005525 return blockTranscribed;
5526 }
5527 // Handle specific things.
5528 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5529 return RewriteAtEncode(AtEncode);
Mike Stump1eb44332009-09-09 15:08:12 +00005530
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005531 if (isa<ObjCPropertyRefExpr>(S) || isa<ObjCImplicitSetterGetterRefExpr>(S)) {
5532 Expr *PropOrImplicitRefExpr = dyn_cast<Expr>(S);
5533 assert(PropOrImplicitRefExpr && "Property or implicit setter/getter is null");
5534
5535 BinaryOperator *BinOp = PropSetters[PropOrImplicitRefExpr];
Steve Naroffc77a6362008-12-04 16:24:46 +00005536 if (BinOp) {
5537 // Because the rewriter doesn't allow us to rewrite rewritten code,
5538 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroffb619d952008-12-09 12:56:34 +00005539 DisableReplaceStmt = true;
5540 // Save the source range. Even if we disable the replacement, the
5541 // rewritten node will have been inserted into the tree. If the synthesized
5542 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump1eb44332009-09-09 15:08:12 +00005543 // self.errorHandler = handler ? handler :
Steve Naroffb619d952008-12-09 12:56:34 +00005544 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
5545 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroffc77a6362008-12-04 16:24:46 +00005546 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Fariborz Jahanianf2c6fa42010-10-14 23:31:39 +00005547 // Need to rewrite the ivar access expression if need be.
5548 if (isa<ObjCIvarRefExpr>(newStmt)) {
5549 bool replaced = false;
5550 newStmt = RewriteObjCNestedIvarRefExpr(newStmt, replaced);
5551 }
5552
Steve Naroffb619d952008-12-09 12:56:34 +00005553 DisableReplaceStmt = false;
Steve Naroff4c3580e2008-12-04 23:50:32 +00005554 //
5555 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
5556 // we changed the RHS of BinOp, the rewriter would fail (since it needs
5557 // to see the original expression). Consider this example:
5558 //
5559 // Foo *obj1, *obj2;
5560 //
5561 // obj1.i = [obj2 rrrr];
5562 //
5563 // 'BinOp' for the previous expression looks like:
5564 //
5565 // (BinaryOperator 0x231ccf0 'int' '='
5566 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
5567 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
5568 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
5569 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
5570 //
5571 // 'newStmt' represents the rewritten message expression. For example:
5572 //
5573 // (CallExpr 0x231d300 'id':'struct objc_object *'
5574 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
5575 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
5576 // (CStyleCastExpr 0x231d220 'void *'
5577 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
5578 //
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005579 // Note that 'newStmt' is passed to RewritePropertyOrImplicitSetter so that it
Steve Naroff4c3580e2008-12-04 23:50:32 +00005580 // can be used as the setter argument. ReplaceStmt() will still 'see'
5581 // the original RHS (since we haven't altered BinOp).
5582 //
Mike Stump1eb44332009-09-09 15:08:12 +00005583 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff4c3580e2008-12-04 23:50:32 +00005584 // node. As a result, we now leak the original AST nodes.
5585 //
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005586 return RewritePropertyOrImplicitSetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroffc77a6362008-12-04 16:24:46 +00005587 } else {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005588 return RewritePropertyOrImplicitGetter(PropOrImplicitRefExpr);
Steve Naroff15f081d2008-12-03 00:56:33 +00005589 }
5590 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005591
Steve Narofffa15fd92008-10-28 20:29:00 +00005592 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5593 return RewriteAtSelector(AtSelector);
Mike Stump1eb44332009-09-09 15:08:12 +00005594
Steve Narofffa15fd92008-10-28 20:29:00 +00005595 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5596 return RewriteObjCStringLiteral(AtString);
Mike Stump1eb44332009-09-09 15:08:12 +00005597
Steve Narofffa15fd92008-10-28 20:29:00 +00005598 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00005599#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00005600 // Before we rewrite it, put the original message expression in a comment.
5601 SourceLocation startLoc = MessExpr->getLocStart();
5602 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00005603
Steve Narofffa15fd92008-10-28 20:29:00 +00005604 const char *startBuf = SM->getCharacterData(startLoc);
5605 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00005606
Steve Narofffa15fd92008-10-28 20:29:00 +00005607 std::string messString;
5608 messString += "// ";
5609 messString.append(startBuf, endBuf-startBuf+1);
5610 messString += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00005611
5612 // FIXME: Missing definition of
Steve Narofffa15fd92008-10-28 20:29:00 +00005613 // InsertText(clang::SourceLocation, char const*, unsigned int).
5614 // InsertText(startLoc, messString.c_str(), messString.size());
5615 // Tried this, but it didn't work either...
5616 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00005617#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00005618 return RewriteMessageExpr(MessExpr);
5619 }
Mike Stump1eb44332009-09-09 15:08:12 +00005620
Steve Narofffa15fd92008-10-28 20:29:00 +00005621 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5622 return RewriteObjCTryStmt(StmtTry);
5623
5624 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5625 return RewriteObjCSynchronizedStmt(StmtTry);
5626
5627 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5628 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump1eb44332009-09-09 15:08:12 +00005629
Steve Narofffa15fd92008-10-28 20:29:00 +00005630 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5631 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump1eb44332009-09-09 15:08:12 +00005632
5633 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofffa15fd92008-10-28 20:29:00 +00005634 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump1eb44332009-09-09 15:08:12 +00005635 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofffa15fd92008-10-28 20:29:00 +00005636 OrigStmtRange.getEnd());
5637 if (BreakStmt *StmtBreakStmt =
5638 dyn_cast<BreakStmt>(S))
5639 return RewriteBreakStmt(StmtBreakStmt);
5640 if (ContinueStmt *StmtContinueStmt =
5641 dyn_cast<ContinueStmt>(S))
5642 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00005643
5644 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofffa15fd92008-10-28 20:29:00 +00005645 // and cast exprs.
5646 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5647 // FIXME: What we're doing here is modifying the type-specifier that
5648 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump1eb44332009-09-09 15:08:12 +00005649 // a separate type-specifier that we can rewrite.
Steve Naroff3d7e7862009-12-05 15:55:59 +00005650 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5651 // the context of an ObjCForCollectionStmt. For example:
5652 // NSArray *someArray;
5653 // for (id <FooProtocol> index in someArray) ;
5654 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5655 // and it depends on the original text locations/positions.
Benjamin Kramerb2041de2009-12-05 22:16:51 +00005656 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
Steve Naroff3d7e7862009-12-05 15:55:59 +00005657 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump1eb44332009-09-09 15:08:12 +00005658
Steve Narofffa15fd92008-10-28 20:29:00 +00005659 // Blocks rewrite rules.
5660 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5661 DI != DE; ++DI) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00005662 Decl *SD = *DI;
Steve Narofffa15fd92008-10-28 20:29:00 +00005663 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005664 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005665 RewriteBlockPointerDecl(ND);
Mike Stump1eb44332009-09-09 15:08:12 +00005666 else if (ND->getType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005667 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00005668 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005669 if (VD->hasAttr<BlocksAttr>()) {
5670 static unsigned uniqueByrefDeclCount = 0;
5671 assert(!BlockByRefDeclNo.count(ND) &&
5672 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5673 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005674 RewriteByRefVar(VD);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005675 }
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00005676 else
5677 RewriteTypeOfDecl(VD);
5678 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005679 }
5680 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005681 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005682 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005683 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005684 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5685 }
5686 }
5687 }
Mike Stump1eb44332009-09-09 15:08:12 +00005688
Steve Narofffa15fd92008-10-28 20:29:00 +00005689 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5690 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump1eb44332009-09-09 15:08:12 +00005691
5692 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005693 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5694 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump1eb44332009-09-09 15:08:12 +00005695 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5696 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005697 && "Statement stack mismatch");
5698 Stmts.pop_back();
5699 }
5700 // Handle blocks rewriting.
5701 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
5702 if (BDRE->isByRef())
Steve Naroff621edce2009-04-29 16:37:50 +00005703 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofffa15fd92008-10-28 20:29:00 +00005704 }
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005705 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5706 ValueDecl *VD = DRE->getDecl();
5707 if (VD->hasAttr<BlocksAttr>())
5708 return RewriteBlockDeclRefExpr(DRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005709 if (HasLocalVariableExternalStorage(VD))
5710 return RewriteLocalVariableExternalStorage(DRE);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005711 }
5712
Steve Narofffa15fd92008-10-28 20:29:00 +00005713 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005714 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00005715 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005716 ReplaceStmt(S, BlockCall);
5717 return BlockCall;
5718 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005719 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00005720 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005721 RewriteCastExpr(CE);
5722 }
5723#if 0
5724 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Sebastian Redl906082e2010-07-20 04:20:21 +00005725 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5726 ICE->getSubExpr(),
5727 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00005728 // Get the new text.
5729 std::string SStr;
5730 llvm::raw_string_ostream Buf(SStr);
Eli Friedman3a9eb442009-05-30 05:19:26 +00005731 Replacement->printPretty(Buf, *Context);
Steve Narofffa15fd92008-10-28 20:29:00 +00005732 const std::string &Str = Buf.str();
5733
5734 printf("CAST = %s\n", &Str[0]);
5735 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5736 delete S;
5737 return Replacement;
5738 }
5739#endif
5740 // Return this stmt unmodified.
5741 return S;
5742}
5743
Steve Naroff3d7e7862009-12-05 15:55:59 +00005744void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
5745 for (RecordDecl::field_iterator i = RD->field_begin(),
5746 e = RD->field_end(); i != e; ++i) {
5747 FieldDecl *FD = *i;
5748 if (isTopLevelBlockPointerType(FD->getType()))
5749 RewriteBlockPointerDecl(FD);
5750 if (FD->getType()->isObjCQualifiedIdType() ||
5751 FD->getType()->isObjCQualifiedInterfaceType())
5752 RewriteObjCQualifiedInterfaceTypes(FD);
5753 }
5754}
5755
Steve Narofffa15fd92008-10-28 20:29:00 +00005756/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5757/// main file of the input.
5758void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5759 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffcb735302008-12-17 00:20:22 +00005760 if (FD->isOverloadedOperator())
5761 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005762
Steve Narofffa15fd92008-10-28 20:29:00 +00005763 // Since function prototypes don't have ParmDecl's, we check the function
5764 // prototype. This enables us to rewrite function declarations and
5765 // definitions using the same code.
Douglas Gregor72564e72009-02-26 23:50:07 +00005766 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005767
Sebastian Redld3a413d2009-04-26 20:35:05 +00005768 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidis5f1bfc12010-07-07 11:31:34 +00005769 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005770 CurFunctionDef = FD;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005771 CurFunctionDeclToDeclareForBlock = FD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005772 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005773 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005774 Body =
5775 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5776 FD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005777 CurrentBody = 0;
5778 if (PropParentMap) {
5779 delete PropParentMap;
5780 PropParentMap = 0;
5781 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005782 // This synthesizes and inserts the block "impl" struct, invoke function,
5783 // and any copy/dispose helper functions.
5784 InsertBlockLiteralsWithinFunction(FD);
5785 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005786 CurFunctionDeclToDeclareForBlock = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00005787 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005788 return;
5789 }
5790 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00005791 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005792 CurMethodDef = MD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005793 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005794 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005795 Body =
5796 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5797 MD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005798 CurrentBody = 0;
5799 if (PropParentMap) {
5800 delete PropParentMap;
5801 PropParentMap = 0;
5802 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005803 InsertBlockLiteralsWithinMethod(MD);
5804 CurMethodDef = 0;
5805 }
5806 }
5807 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5808 ClassImplementation.push_back(CI);
5809 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5810 CategoryImplementation.push_back(CI);
5811 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
5812 RewriteForwardClassDecl(CD);
5813 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5814 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005815 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005816 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005817 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005818 CheckFunctionPointerDecl(VD->getType(), VD);
5819 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00005820 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005821 RewriteCastExpr(CE);
5822 }
5823 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00005824 } else if (VD->getType()->isRecordType()) {
5825 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5826 if (RD->isDefinition())
5827 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005828 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005829 if (VD->getInit()) {
5830 GlobalVarDecl = VD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005831 CollectPropertySetters(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005832 CurrentBody = VD->getInit();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005833 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005834 CurrentBody = 0;
5835 if (PropParentMap) {
5836 delete PropParentMap;
5837 PropParentMap = 0;
5838 }
Mike Stump1eb44332009-09-09 15:08:12 +00005839 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00005840 VD->getName());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005841 GlobalVarDecl = 0;
5842
5843 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00005844 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005845 RewriteCastExpr(CE);
5846 }
5847 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005848 return;
5849 }
5850 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005851 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005852 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005853 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005854 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5855 return;
5856 }
5857 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroff3d7e7862009-12-05 15:55:59 +00005858 if (RD->isDefinition())
5859 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005860 return;
5861 }
5862 // Nothing yet.
5863}
5864
Chris Lattnerdacbc5d2009-03-28 04:11:33 +00005865void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005866 if (Diags.hasErrorOccurred())
5867 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005868
Steve Narofffa15fd92008-10-28 20:29:00 +00005869 RewriteInclude();
Mike Stump1eb44332009-09-09 15:08:12 +00005870
Steve Naroff621edce2009-04-29 16:37:50 +00005871 // Here's a great place to add any extra declarations that may be needed.
5872 // Write out meta data for each @protocol(<expr>).
Mike Stump1eb44332009-09-09 15:08:12 +00005873 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00005874 E = ProtocolExprDecls.end(); I != E; ++I)
5875 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5876
Benjamin Kramerd999b372010-02-14 14:14:16 +00005877 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff0aab7962008-11-14 14:10:01 +00005878 if (ClassImplementation.size() || CategoryImplementation.size())
5879 RewriteImplementations();
Steve Naroff621edce2009-04-29 16:37:50 +00005880
Steve Narofffa15fd92008-10-28 20:29:00 +00005881 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5882 // we are done.
Mike Stump1eb44332009-09-09 15:08:12 +00005883 if (const RewriteBuffer *RewriteBuf =
Steve Narofffa15fd92008-10-28 20:29:00 +00005884 Rewrite.getRewriteBufferFor(MainFileID)) {
5885 //printf("Changed:\n");
5886 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5887 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +00005888 llvm::errs() << "No changes\n";
Steve Narofffa15fd92008-10-28 20:29:00 +00005889 }
Steve Narofface66252008-11-13 20:07:04 +00005890
Steve Naroff621edce2009-04-29 16:37:50 +00005891 if (ClassImplementation.size() || CategoryImplementation.size() ||
5892 ProtocolExprDecls.size()) {
Steve Naroff0aab7962008-11-14 14:10:01 +00005893 // Rewrite Objective-c meta data*
5894 std::string ResultStr;
5895 SynthesizeMetaDataIntoBuffer(ResultStr);
5896 // Emit metadata.
5897 *OutFile << ResultStr;
5898 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005899 OutFile->flush();
5900}